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
Iron python, beautiful soup, win32 app
118,654
20
2008-09-23T01:37:48Z
170,856
33
2008-10-04T19:04:21Z
[ ".net", "python", "ironpython" ]
Does beautiful soup work with iron python? If so with which version of iron python? How easy is it to distribute a windows desktop app on .net 2.0 using iron python (mostly c# calling some python code for parsing html)?
I was asking myself this same question and after struggling to follow advice here and elsewhere to get IronPython and BeautifulSoup to play nicely with my existing code I decided to go looking for an alternative native .NET solution. BeautifulSoup is a wonderful bit of code and at first it didn't look like there was anything comparable available for .NET, but then I found the [HTML Agility Pack](http://www.codeplex.com/htmlagilitypack) and if anything I think I've actually gained some maintainability over BeautifulSoup. It takes clean or crufty HTML and produces a elegant XML DOM from it that can be queried via XPath. With a couple lines of code you can even get back a raw XDocument and then [craft your queries in LINQ to XML](http://vijay.screamingpens.com/archive/2008/05/26/linq-amp-lambda-part-3-html-agility-pack-to-linq.aspx). Honestly, if web scraping is your goal, this is about the cleanest solution you are likely to find. **Edit** Here is a simple (read: not robust at all) example that parses out the US House of Representatives holiday schedule: ``` using System; using System.Collections.Generic; using HtmlAgilityPack; namespace GovParsingTest { class Program { static void Main(string[] args) { HtmlWeb hw = new HtmlWeb(); string url = @"http://www.house.gov/house/House_Calendar.shtml"; HtmlDocument doc = hw.Load(url); HtmlNode docNode = doc.DocumentNode; HtmlNode div = docNode.SelectSingleNode("//div[@id='primary']"); HtmlNodeCollection tableRows = div.SelectNodes(".//tr"); foreach (HtmlNode row in tableRows) { HtmlNodeCollection cells = row.SelectNodes(".//td"); HtmlNode dateNode = cells[0]; HtmlNode eventNode = cells[1]; while (eventNode.HasChildNodes) { eventNode = eventNode.FirstChild; } Console.WriteLine(dateNode.InnerText); Console.WriteLine(eventNode.InnerText); Console.WriteLine(); } //Console.WriteLine(div.InnerHtml); Console.ReadKey(); } } } ```
How do I uninstall python from OSX Leopard so that I can use the MacPorts version?
118,813
18
2008-09-23T02:38:04Z
118,820
22
2008-09-23T02:40:05Z
[ "python", "osx", "osx-leopard", "macports" ]
I want to use the macports version of python instead of the one that comes with Leopard.
I have both installed: ``` $ which python /usr/bin/python $ which python2.5 /opt/local/bin/python2.5 ``` I also added the following line to my `.profile`: ``` export PATH=/opt/local/bin:/opt/local/sbin:$PATH ```
How do I uninstall python from OSX Leopard so that I can use the MacPorts version?
118,813
18
2008-09-23T02:38:04Z
118,824
29
2008-09-23T02:41:53Z
[ "python", "osx", "osx-leopard", "macports" ]
I want to use the macports version of python instead of the one that comes with Leopard.
Don't. Apple ships various system utilities that rely on the system Python (and particularly the Python "framework" build); removing it will cause you problems. Instead, modify your PATH environ variable in your `~/.bash_profile` to put `/opt/local/bin` first.
How do I uninstall python from OSX Leopard so that I can use the MacPorts version?
118,813
18
2008-09-23T02:38:04Z
604,946
20
2009-03-03T03:04:32Z
[ "python", "osx", "osx-leopard", "macports" ]
I want to use the macports version of python instead of the one that comes with Leopard.
Use the [python\_select](http://www.macports.org/ports.php?by=name&substr=python%5Fselect) port to switch python interpreters. ``` sudo port install python25 sudo port install python_select sudo python_select python25 ``` This will symlink `/opt/local/bin/python` to the selected version. Then export `PATH` as described above.
How do I uninstall python from OSX Leopard so that I can use the MacPorts version?
118,813
18
2008-09-23T02:38:04Z
6,166,416
17
2011-05-29T07:17:41Z
[ "python", "osx", "osx-leopard", "macports" ]
I want to use the macports version of python instead of the one that comes with Leopard.
`python_select` is now deprecated, use this instead: ``` sudo port select python python26 ```
Adding code to __init__.py
119,167
67
2008-09-23T04:41:18Z
119,178
63
2008-09-23T04:47:51Z
[ "python", "initialization", "package" ]
I'm taking a look at how the model system in django works and I noticed something that I don't understand. I know that you create an empty `__init__.py` file to specify that the current directory is a package. And that you can set some variable in `__init__.py` so that import \* works properly. But django adds a bunch of from ... import ... statements and defines a bunch of classes in `__init__.py`. Why? Doesn't this just make things look messy? Is there a reason that requires this code in `__init__.py`?
All imports in `__init__.py` are made available when you import the package (directory) that contains it. Example: `./dir/__init__.py`: ``` import something ``` `./test.py`: ``` import dir # can now use dir.something ``` EDIT: forgot to mention, the code in `__init__.py` runs the first time you import any module from that directory. So it's normally a good place to put any package-level initialisation code. EDIT2: dgrant pointed out to a possible confusion in my example. In `__init__.py` `import something` can import any module, not necessary from the package. For example, we can replace it with `import datetime`, then in our top level `test.py` both of these snippets will work: ``` import dir print dir.datetime.datetime.now() ``` and ``` import dir.some_module_in_dir print dir.datetime.datetime.now() ``` The bottom line is: all names assigned in `__init__.py`, be it imported modules, functions or classes, are automatically available in the package namespace whenever you import the package or a module in the package.
Adding code to __init__.py
119,167
67
2008-09-23T04:41:18Z
119,346
30
2008-09-23T06:12:15Z
[ "python", "initialization", "package" ]
I'm taking a look at how the model system in django works and I noticed something that I don't understand. I know that you create an empty `__init__.py` file to specify that the current directory is a package. And that you can set some variable in `__init__.py` so that import \* works properly. But django adds a bunch of from ... import ... statements and defines a bunch of classes in `__init__.py`. Why? Doesn't this just make things look messy? Is there a reason that requires this code in `__init__.py`?
It's just personal preference really, and has to do with the layout of your python modules. Let's say you have a module called `erikutils`. There are two ways that it can be a module, either you have a file called *erikutils.py* on your `sys.path` or you have a directory called *erikutils* on your `sys.path` with an empty *`__init__.py`* file inside it. Then let's say you have a bunch of modules called `fileutils`, `procutils`, `parseutils` and you want those to be sub-modules under `erikutils`. So you make some .py files called *fileutils.py*, *procutils.py*, and *parseutils.py*: ``` erikutils __init__.py fileutils.py procutils.py parseutils.py ``` Maybe you have a few functions that just don't belong in the `fileutils`, `procutils`, or `parseutils` modules. And let's say you don't feel like creating a new module called `miscutils`. AND, you'd like to be able to call the function like so: ``` erikutils.foo() erikutils.bar() ``` rather than doing ``` erikutils.miscutils.foo() erikutils.miscutils.bar() ``` So because the `erikutils` module is a directory, not a file, we have to define it's functions inside the *`__init__.py`* file. In django, the best example I can think of is `django.db.models.fields`. ALL the django \*Field classes are defined in the *`__init__.py`* file in the *django/db/models/fields* directory. I guess they did this because they didn't want to cram everything into a hypothetical *django/db/models/fields.py* model, so they split it out into a few submodules (*related.py*, *files.py*, for example) and they stuck the made \*Field definitions in the fields module itself (hence, *`__init__.py`*).
Adding code to __init__.py
119,167
67
2008-09-23T04:41:18Z
126,499
24
2008-09-24T11:02:55Z
[ "python", "initialization", "package" ]
I'm taking a look at how the model system in django works and I noticed something that I don't understand. I know that you create an empty `__init__.py` file to specify that the current directory is a package. And that you can set some variable in `__init__.py` so that import \* works properly. But django adds a bunch of from ... import ... statements and defines a bunch of classes in `__init__.py`. Why? Doesn't this just make things look messy? Is there a reason that requires this code in `__init__.py`?
Using the `__init__.py` file allows you to make the internal package structure invisible from the outside. If the internal structure changes (e.g. because you split one fat module into two) you only have to adjust the `__init__.py` file, but not the code that depends on the package. You can also make parts of your package invisible, e.g. if they are not ready for general usage. Note that you can use the `del` command, so a typical `__init__.py` may look like this: ``` from somemodule import some_function1, some_function2, SomeObject del somemodule ``` Now if you decide to split `somemodule` the new `__init__.py` might be: ``` from somemodule1 import some_function1, some_function2 from somemodule2 import SomeObject del somemodule1 del somemodule2 ``` From the outside the package still looks exactly as before.
Is it good to switch from c# to python?
119,198
2
2008-09-23T04:53:13Z
119,232
15
2008-09-23T05:05:53Z
[ "c#", "python" ]
Currently I am developing in the .Net environment using C# but I want to know whether it is worth learning python. I'm thinking of learning the Django framework. What is better?
Yes, you should learn Python, but it has nothing to do with Python or C# being better. It is really about making you a better programmer. Learning Python will give you a whole new perspective on programmer and how problems can be solved. It's like lifting weights, except you're building up the developer muscles in your mind. For example, if you've only ever programmed using a statically typed language then it is hard to imagine any other way. Learning Python will teach you that there is an alternative in the form of dynamic typing. For a summary of Pythons benefits: <http://www.cmswire.com/cms/enterprise-20/2007s-programming-language-of-the-year-is-002221.php>
time length of an mp3 file
119,404
13
2008-09-23T06:33:14Z
119,418
23
2008-09-23T06:37:50Z
[ "python", "mp3", "media", "music" ]
What is the simplest way to determine the length (in seconds) of a given mp3 file, **without using outside libraries**? (python source highly appreciated)
You can use [pymad](http://spacepants.org/src/pymad/). It's an external library, but don't fall for the Not Invented Here trap. Any particular reason you don't want any external libraries? ``` import mad mf = mad.MadFile("foo.mp3") track_length_in_milliseconds = mf.total_time() ``` Spotted [here](http://simonwillison.net/2003/Dec/4/mp3lengths/). -- If you really don't want to use an external library, have a look [here](http://ibofobi.dk/stuff/mp3/) and check out how he's done it. Warning: it's complicated.
time length of an mp3 file
119,404
13
2008-09-23T06:33:14Z
119,616
7
2008-09-23T07:37:41Z
[ "python", "mp3", "media", "music" ]
What is the simplest way to determine the length (in seconds) of a given mp3 file, **without using outside libraries**? (python source highly appreciated)
> > Simple, parse MP3 binary blob to calculate something, in Python That sounds like a pretty tall order. I don't know Python, but here's some code I've refactored from another program I once tried to write. **Note:** It's in C++ (sorry, it's what I've got). Also, as-is, it'll only handle constant bit rate MPEG 1 Audio Layer 3 files. That *should* cover most, but I can't make any guarantee as to this working in all situations. Hopefully this does what you want, and hopefully refactoring it into Python is easier than doing it from scratch. ``` // determines the duration, in seconds, of an MP3; // assumes MPEG 1 (not 2 or 2.5) Audio Layer 3 (not 1 or 2) // constant bit rate (not variable) #include <iostream> #include <fstream> #include <cstdlib> using namespace std; //Bitrates, assuming MPEG 1 Audio Layer 3 const int bitrates[16] = { 0, 32000, 40000, 48000, 56000, 64000, 80000, 96000, 112000, 128000, 160000, 192000, 224000, 256000, 320000, 0 }; //Intel processors are little-endian; //search Google or see: http://en.wikipedia.org/wiki/Endian int reverse(int i) { int toReturn = 0; toReturn |= ((i & 0x000000FF) << 24); toReturn |= ((i & 0x0000FF00) << 8); toReturn |= ((i & 0x00FF0000) >> 8); toReturn |= ((i & 0xFF000000) >> 24); return toReturn; } //In short, data in ID3v2 tags are stored as //"syncsafe integers". This is so the tag info //isn't mistaken for audio data, and attempted to //be "played". For more info, have fun Googling it. int syncsafe(int i) { int toReturn = 0; toReturn |= ((i & 0x7F000000) >> 24); toReturn |= ((i & 0x007F0000) >> 9); toReturn |= ((i & 0x00007F00) << 6); toReturn |= ((i & 0x0000007F) << 21); return toReturn; } //How much room does ID3 version 1 tag info //take up at the end of this file (if any)? int id3v1size(ifstream& infile) { streampos savePos = infile.tellg(); //get to 128 bytes from file end infile.seekg(0, ios::end); streampos length = infile.tellg() - (streampos)128; infile.seekg(length); int size; char buffer[3] = {0}; infile.read(buffer, 3); if( buffer[0] == 'T' && buffer[1] == 'A' && buffer[2] == 'G' ) size = 128; //found tag data else size = 0; //nothing there infile.seekg(savePos); return size; } //how much room does ID3 version 2 tag info //take up at the beginning of this file (if any) int id3v2size(ifstream& infile) { streampos savePos = infile.tellg(); infile.seekg(0, ios::beg); char buffer[6] = {0}; infile.read(buffer, 6); if( buffer[0] != 'I' || buffer[1] != 'D' || buffer[2] != '3' ) { //no tag data infile.seekg(savePos); return 0; } int size = 0; infile.read(reinterpret_cast<char*>(&size), sizeof(size)); size = syncsafe(size); infile.seekg(savePos); //"size" doesn't include the 10 byte ID3v2 header return size + 10; } int main(int argCount, char* argValues[]) { //you'll have to change this ifstream infile("C:/Music/Bush - Comedown.mp3", ios::binary); if(!infile.is_open()) { infile.close(); cout << "Error opening file" << endl; system("PAUSE"); return 0; } //determine beginning and end of primary frame data (not ID3 tags) infile.seekg(0, ios::end); streampos dataEnd = infile.tellg(); infile.seekg(0, ios::beg); streampos dataBegin = 0; dataEnd -= id3v1size(infile); dataBegin += id3v2size(infile); infile.seekg(dataBegin,ios::beg); //determine bitrate based on header for first frame of audio data int headerBytes = 0; infile.read(reinterpret_cast<char*>(&headerBytes),sizeof(headerBytes)); headerBytes = reverse(headerBytes); int bitrate = bitrates[(int)((headerBytes >> 12) & 0xF)]; //calculate duration, in seconds int duration = (dataEnd - dataBegin)/(bitrate/8); infile.close(); //print duration in minutes : seconds cout << duration/60 << ":" << duration%60 << endl; system("PAUSE"); return 0; } ```
time length of an mp3 file
119,404
13
2008-09-23T06:33:14Z
5,059,165
9
2011-02-20T18:49:58Z
[ "python", "mp3", "media", "music" ]
What is the simplest way to determine the length (in seconds) of a given mp3 file, **without using outside libraries**? (python source highly appreciated)
For google followers' sake, here are a few more external libs: mpg321 -t ffmpeg -i midentify (mplayer basically) see [Using mplayer to determine length of audio/video file](http://stackoverflow.com/questions/497681/using-mplayer-to-determine-length-of-audio-video-file) mencoder (pass it invalid params, it will spit out an error message but also give you info on the file in question, ex $ mencoder inputfile.mp3 -o fake) mediainfo program <http://mediainfo.sourceforge.net/en> exiftool the linux "file" command mp3info sox refs: <http://superuser.com/questions/36871/linux-command-line-utility-to-determine-mp3-bitrate> <http://www.ruby-forum.com/topic/139468> [mp3 length in milliseconds](http://stackoverflow.com/questions/993971/mp3-length-in-milliseconds) (making this a wiki for others to add to). and libs: .net: naudio, java: jlayer, c: libmad Cheers!
Tabs versus spaces in Python programming
119,562
207
2008-09-23T07:26:00Z
119,576
180
2008-09-23T07:28:00Z
[ "python", "coding-style", "indentation", "conventions" ]
I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes. How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true? Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?
Because [PEP-8](http://www.python.org/dev/peps/pep-0008/#tabs-or-spaces) tells us to use spaces :)
Tabs versus spaces in Python programming
119,562
207
2008-09-23T07:26:00Z
119,594
21
2008-09-23T07:31:58Z
[ "python", "coding-style", "indentation", "conventions" ]
I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes. How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true? Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?
I recently came across an article titled [Python: Myths about Indentation](http://www.secnetix.de/olli/Python/block_indentation.hawk) which discusses this and related questions. The article has good reasons for recommending the use of spaces when writing Python code, but there is certainly room for disagreement. I believe it's true that most Python programmers use spaces only.
Tabs versus spaces in Python programming
119,562
207
2008-09-23T07:26:00Z
119,598
51
2008-09-23T07:32:35Z
[ "python", "coding-style", "indentation", "conventions" ]
I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes. How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true? Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?
The most "pythonic" way is to use 4 spaces per indentation level. The Python interpreter will however recognize spaces or tabs. The only gottcha is you **must never mix spaces and tabs**, pick one or the other. That said, the specification recommends spaces, most developers use spaces, so unless you have a really good reason not to, I'd say go with spaces.
Tabs versus spaces in Python programming
119,562
207
2008-09-23T07:26:00Z
119,703
9
2008-09-23T07:56:34Z
[ "python", "coding-style", "indentation", "conventions" ]
I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes. How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true? Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?
You CAN mix tabs and spaces... BUT a tab is considered to be the same indentation as 8 spaces, so unless your editor is set up to consider a tab to be 8 spaces you're asking for trouble when mixing them.
Tabs versus spaces in Python programming
119,562
207
2008-09-23T07:26:00Z
120,265
13
2008-09-23T10:38:35Z
[ "python", "coding-style", "indentation", "conventions" ]
I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes. How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true? Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?
Use an editor that allows you to insert spaces up to the tabstop when you press the TAB key, instead of inserting a \t character. And then forget about it.
Tabs versus spaces in Python programming
119,562
207
2008-09-23T07:26:00Z
132,652
9
2008-09-25T11:11:33Z
[ "python", "coding-style", "indentation", "conventions" ]
I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes. How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true? Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?
The only inconvenience I experience with using spaces instead of tabs is that you cannot easily remove an indentation level, you have to remove 4 spaces instead of just one tab.
Tabs versus spaces in Python programming
119,562
207
2008-09-23T07:26:00Z
1,777,008
315
2009-11-21T22:30:21Z
[ "python", "coding-style", "indentation", "conventions" ]
I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes. How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true? Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?
Tired of chasing after indentation typos ( 8 spaces ? no, 7 oops 9 ... ) I switched my sources to 'tabs only'. **1 tab == 1 indent level, full stop** The point is: if you want to display the indentation as 4, 8 or pi / 12 character width, just change the settings in your text editor, don't mess with the code :p (personally I use 4 char width tab... but some would prefer 3 or 8 space, or even use variable width fonts !!)
Tabs versus spaces in Python programming
119,562
207
2008-09-23T07:26:00Z
2,389,168
43
2010-03-05T18:55:48Z
[ "python", "coding-style", "indentation", "conventions" ]
I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes. How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true? Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?
My main reason for using tabs over spaces is the backspace key. If I'm on a line and I want to backspace-remove an indentation on just that one line I have to hit backspace 4x if it were spaces; whereas, I only need to hit it once if it's a tab. I will continue to use tabs because—like was stated before—it's easier to convert from tabs to spaces, but not the other way around. I'm thinking I want to write a simple program that converts code with spaces into code with tabs, because I freaking hate spaces. They drive me up the wall! Oh! And using the arrow keys to navigate left and right is always a pain in the ass when it's spaces. *UPDATE: Sublime Text 3 now deletes a full soft tab with the backspace key; though, arrow-key navigation is still tedious.* *UPDATE: See some cool animated GIFs that illustrate my points above and more at [Tabs vs. Spaces, We Meet Again](https://web.archive.org/web/20150607064227/http://jedmao.ghost.io/2014/08/20/tabs-vs-spaces-the-age-old-war)*
Tabs versus spaces in Python programming
119,562
207
2008-09-23T07:26:00Z
2,868,181
56
2010-05-19T18:14:16Z
[ "python", "coding-style", "indentation", "conventions" ]
I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes. How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true? Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?
USE AN EDITOR THAT DISPLAYS TAB CHARACTERS (all whitespace, for that matter). You're programming, not writing an article. I use tabs. There's no room for a one-space error in the tabs (if you can see them). The problem IS that people use different editors, and the only common thing in the world is: tab==indent, as above. Some bloke comes in with the tab key set to the wrong number of spaces or does it manually and makes a mess. TABs and use a real editor. (This isn't just contrary to the PEP, it's about C/C++ and other whitespace-agnostic languages too). /steps down from soapbox
Tabs versus spaces in Python programming
119,562
207
2008-09-23T07:26:00Z
6,338,054
130
2011-06-14T01:02:09Z
[ "python", "coding-style", "indentation", "conventions" ]
I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes. How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true? Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?
*Thus spake the Lord: Thou shalt indent with four spaces. No more, no less. Four shall be the number of spaces thou shalt indent, and the number of thy indenting shall be four. Eight shalt thou not indent, nor either indent thou two, excepting that thou then proceed to four. Tabs are right out.* -- Georg Brandl
Tabs versus spaces in Python programming
119,562
207
2008-09-23T07:26:00Z
7,773,894
8
2011-10-14T21:43:41Z
[ "python", "coding-style", "indentation", "conventions" ]
I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes. How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true? Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?
I know this is an old question, but it still comes up near the top of a google search on the topic, and I think I can add a little value. When I was first learning python, I was put off a little by the idea of significant white space, as most languages to use it are inflexible. That said, I was impressed by python's ability to understand a variety of indentation styles. When considering what style to use for a new project, I think it is important to keep two things in mind. 1. First, it is important to understand how python interprets indentation. Bryan Oakley mentioned the possibility of off-by-one errors when using tabs, but this actually isn't possible with the default interpreter settings. There is a better explanation of this in *Learning Python*, from O'Rielly Media. Basically, there is a variable (which can be changed by including a comment at the top of a source file # tab-width: ) that defines the tab width. When python encounters a tab, it increases the indentation distance *to the next multiple of tab-width*. Thus if a space followed by a tab is entered along the left of the file, the next multiple of tab-width is 8. If a tab by itself is entered, the same thing happens. In this way, it is safe, if your editor is configured properly, to use tabs, and even to mix tabs and spaces. As long as you set your editor's tab stops to the same width as the python tab-width declaration (or 8 if it is absent). It is generally a bad idea to use an editor with a tab width of other than 8 spaces, unless you specify the tab-width in the file. 2. Second, much of the syntactic design of python is to encourage code readability and consistent style between programmers on the same project. That said, the question becomes, for any particular project, what will make the code the most readable *by the people working on the project*. Certainly it is a good idea to keep a consistent indentation style, but depending on the platform and the editor used by the project, a different style may make sense for different projects. If there is no compelling reason to not conform to pep8, then it makes sense to do so, because it will conform to what people expect. I have encountered projects that use a mix of tabs and spaces successfully. Basically spaces are used to indent small sections, where the fact that it is in an indented section is relatively unimportant; while tabs are used to draw the reader's attention to a large structural feature. For example, classes begin with a tab, which simple conditional checks inside a function use 2 spaces. Tabs are also useful when dealing with large blocks of text indented multiple levels. When you drop out of 3-4 levels of indentation, it is far easier to line up with the proper tab than it is to line up with the proper number of spaces. If a project doesn't use the pep8 recommended style, it is probably best to write a style guide into a file somewhere so that the indentation pattern remains consistent and other people can read explicitly how to configure their editor to match. Also, python2.x has an option `-t` to issue warnings about mixed tabs and spaces and `-tt` to issue an error. This only applied to mixed tabs and spaces inside the same scope. python3 assumes `-tt` and so far as I've found, there is no way to disable that check.
Tabs versus spaces in Python programming
119,562
207
2008-09-23T07:26:00Z
7,882,145
8
2011-10-24T21:21:55Z
[ "python", "coding-style", "indentation", "conventions" ]
I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes. How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true? Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?
Tabs rule. Same argument for nested loops and you want to bring the outer loop "back" 1 level. Tip: If you want to convert old space-riddled python code into tabs use the TabOut utility available as an executable on <http://www.textpad.com/add-ons/>.
Tabs versus spaces in Python programming
119,562
207
2008-09-23T07:26:00Z
12,974,668
29
2012-10-19T12:50:32Z
[ "python", "coding-style", "indentation", "conventions" ]
I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes. How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true? Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?
So far as I can tell, here are the pros and cons of tabs vs spaces. Pros of tabs: * Fewer keystrokes required to indent, unindent, and traverse the indentation. (Even if your IDE has some space-indentation cleverness it will never be as good as tabs.) * Different programmers can use different tab display sizes as they wish. * You can never have the cursor "inside" an indentation character. For example say you are copying some lines, with tabs you can click vaguely near the start of a line to start your selection and you will get all of the first tab. With spaces you're likely to miss the first space character unless you hit the tiny target between it and the margin. Similarly to remove an indentation from a line, most editors don't handle pressing backspace well if your cursor is in the middle of a four-space indentation character. It will usually remove one space. With tabs it works as expected. * Consistance with other languages, so you don't have to set your editor up to use, e.g. tabs for C++/Java and spaces for Python. * Wrong indentations can be more obvious (i.e. an extra tab is much larger than an extra space). Cons of tabs: * Most python programmers use spaces so you would be going against convention. * Using spaces to align multi-line statements is easier than using tabs. You *could* use tabs-for-indentation, spaces-for-alignment, but it seems a bit risky in python! There are some non-issues that are overblown by some people: 1. You might get stray spaces in tabbed indentation that screws things up: Virtually all IDEs/editors support visualising whitespace, and it's almost as likely that you'll get stray tabs in space indentations! I can't see this being a common error anyway. Besides, *most* indentation errors will be caught by python, and good IDEs should be able to highlight different indentations. 2. You can't align things easily with tabs: This is true if you're going for character-perfect alignment, but PEP-8 recommends against this, and python doesn't play well with multi-line statements anyway. 3. People have difference settings for tab display size in their editors so your code will look different in different places: Yeah, that's actually a beneficial feature of tabs. I've started out using spaces to be consistant with other python code, but to be honest it is frustrating enough that I will probably change back to tabs. A lot depends on the capabilities of your IDE, but in my experience no amount of IDE support for space indentation is as good as just using tabs. So unless you *really* don't like being inconsistant with *most* (presumably not all!) python code, use tabs and turn on whitespace visualisation and indentation highlighting (if available). The biggest reason for me is ease of selection and the (fairly significant IMO) reduction in keystrokes. Some conventions are stupid.
Parse DICOM files in native Python
119,684
14
2008-09-23T07:53:50Z
177,470
13
2008-10-07T07:17:52Z
[ "python", "image", "format", "dicom", "medical" ]
What is the simplest and most-pythonic way to parse a DICOM file? A native Python implementation without the use of non-Python libraries would be much preferred. DICOM is the standard file format in digital medical imaging (look [here](http://en.wikipedia.org/wiki/Digital_Imaging_and_Communications_in_Medicine) for more information). There are some C/C++ libraries that support reading (a subset) of DICOM files. Two or three of them even have Python bindings. A native Python parser would serve two purposes for me: 1. No need to build any external C/C++ libraries. 2. Learn about the DICOM file format.
And as of today there's another pure Python package reading DICOM files available: [pydicom](https://github.com/darcymason/pydicom)
Parse DICOM files in native Python
119,684
14
2008-09-23T07:53:50Z
213,987
8
2008-10-17T22:01:47Z
[ "python", "image", "format", "dicom", "medical" ]
What is the simplest and most-pythonic way to parse a DICOM file? A native Python implementation without the use of non-Python libraries would be much preferred. DICOM is the standard file format in digital medical imaging (look [here](http://en.wikipedia.org/wiki/Digital_Imaging_and_Communications_in_Medicine) for more information). There are some C/C++ libraries that support reading (a subset) of DICOM files. Two or three of them even have Python bindings. A native Python parser would serve two purposes for me: 1. No need to build any external C/C++ libraries. 2. Learn about the DICOM file format.
If you want to learn about the DICOM format, "Digital Imaging and Communications in Medicine (DICOM): A Practical Introduction and Survival Guide" by Oleg Pianykh is quite readable and gives a good introduction to key DICOM concepts. Springer-Verlag is the publisher of this book. The full DICOM standard is, of course, the ultimate reference although it is somewhat more intimidating. It is available from NEMA (<http://medical.nema.org>). The file format is actually less esoteric than you might imagine and consists of a preamble followed by a sequence of data elements. The preamble contains the ASCII text "DICM" and several reserved bytes that are unused. Following the preamble is a sequence of data elements. Each data element consists of the size of the element, a two-character ASCII code indicating the value representation, a DICOM tag, and the value. Data elements in the file are ordered by their DICOM tag numbers. The image itself is just another data element with a size, value representation, etc. Value representations specify exactly how to interpret the value. Is it a number? Is it a character string? If it's a character string, is it a short one or a long one and which characters are permitted? The value representation code tells you this. A DICOM tag is a 4 byte hexadecimal code composed of a 2 byte "group" number and a 2 byte "element" number. The group number is an identifier that tells you what information entity the tag applies to (for example, group 0010 refers to the patient and group 0020 refers to the study). The element number identifies the interpretation of the value (items such as the patient's ID number, the series description, etc.). To find out how you should interpret the value, your code looks up the DICOM tag in a dictionary file. There are some other details involved, but that's the essence of it. Probably the most instructive thing you can do to learn about the file format is to take an example DICOM file, look at it with a hex editor, and go through the process of parsing it mentally. I would advise against trying to learn about DICOM by looking at existing open source implementations, at least initially. It is more likely to confuse instead of enlighten. Getting the big picture is more important. Once you have the big picture, then you can descend into subtleties.
Parse DICOM files in native Python
119,684
14
2008-09-23T07:53:50Z
480,245
7
2009-01-26T15:50:42Z
[ "python", "image", "format", "dicom", "medical" ]
What is the simplest and most-pythonic way to parse a DICOM file? A native Python implementation without the use of non-Python libraries would be much preferred. DICOM is the standard file format in digital medical imaging (look [here](http://en.wikipedia.org/wiki/Digital_Imaging_and_Communications_in_Medicine) for more information). There are some C/C++ libraries that support reading (a subset) of DICOM files. Two or three of them even have Python bindings. A native Python parser would serve two purposes for me: 1. No need to build any external C/C++ libraries. 2. Learn about the DICOM file format.
The library [pydicom](http://code.google.com/p/pydicom) mentioned above seems like a great library for accessing the DICOM data structures. To use it to access e.g. RT DOSE data, I guess one would do something like ``` import dicom,numpy dose = dicom.ReadFile("RTDOSE.dcm") d = numpy.fromstring(dose.PixelData,dtype=numpy.int16) d = d.reshape((dose.NumberofFrames,dose.Columns,dose.Rows)) ``` and then, if you're in mayavi, ``` from enthought.mayavi import mlab mlab.pipeline.scalar_field(d) ``` This gives wrong coordinates and dose scaling, but the principle ought to be sound. CT data should be very similar.
Parse DICOM files in native Python
119,684
14
2008-09-23T07:53:50Z
810,849
15
2009-05-01T10:02:07Z
[ "python", "image", "format", "dicom", "medical" ]
What is the simplest and most-pythonic way to parse a DICOM file? A native Python implementation without the use of non-Python libraries would be much preferred. DICOM is the standard file format in digital medical imaging (look [here](http://en.wikipedia.org/wiki/Digital_Imaging_and_Communications_in_Medicine) for more information). There are some C/C++ libraries that support reading (a subset) of DICOM files. Two or three of them even have Python bindings. A native Python parser would serve two purposes for me: 1. No need to build any external C/C++ libraries. 2. Learn about the DICOM file format.
I'm using [pydicom](https://github.com/darcymason/pydicom "pydicom") heavily these days, and it rocks. It's pretty easy to start playing with it: ``` import dicom data = dicom.read_file("yourdicomfile.dcm") ``` To get the interesting stuff out of that "data" object, somehow resembling [dcmdump](http://support.dcmtk.org/docs/dcmdump.html "dcmdump") output: ``` for key in data.dir(): value = getattr(data, key, '') if type(value) is dicom.UID.UID or key == "PixelData": continue print "%s: %s" % (key, value) ``` I think a great way to learn more about the dicom format is to open similar files and write code to compare them according to various aspects: study description, window width and center, pixel representation and so on. Have fun! :)
Using **kwargs with SimpleXMLRPCServer in python
119,802
11
2008-09-23T08:19:44Z
120,291
10
2008-09-23T10:47:37Z
[ "python", "simplexmlrpcserver", "xmlrpclib" ]
I have a class that I wish to expose as a remote service using pythons SimpleXMLRPCServer. The server startup looks like this: ``` server = SimpleXMLRPCServer((serverSettings.LISTEN_IP,serverSettings.LISTEN_PORT)) service = Service() server.register_instance(service) server.serve_forever() ``` I then have a ServiceRemote class that looks like this: ``` def __init__(self,ip,port): self.rpcClient = xmlrpclib.Server('http://%s:%d' %(ip,port)) def __getattr__(self, name): # forward all calls to the rpc client return getattr(self.rpcClient, name) ``` So all calls on the ServiceRemote object will be forwarded to xmlrpclib.Server, which then forwards it to the remote server. The problem is a method in the service that takes named varargs: ``` @useDb def select(self, db, fields, **kwargs): pass ``` The @useDb decorator wraps the function, creating the db before the call and opening it, then closing it after the call is done before returning the result. When I call this method, I get the error "**call**() got an unexpected keyword argument 'name'". So, is it possible to call methods taking variable named arguments remotely? Or will I have to create an override for each method variation I need. --- Thanks for the responses. I changed my code around a bit so the question is no longer an issue. However now I know this for future reference if I indeed do need to implement positional arguments and support remote invocation. I think a combination of Thomas and praptaks approaches would be good. Turning kwargs into positional args on the client through xmlrpclient, and having a wrapper on methods serverside to unpack positional arguments.
You can't do this with plain xmlrpc since it has no notion of keyword arguments. However, you can superimpose this as a protocol on top of xmlrpc that would always pass a list as first argument, and a dictionary as a second, and then provide the proper support code so this becomes transparent for your usage, example below: ## Server ``` from SimpleXMLRPCServer import SimpleXMLRPCServer class Server(object): def __init__(self, hostport): self.server = SimpleXMLRPCServer(hostport) def register_function(self, function, name=None): def _function(args, kwargs): return function(*args, **kwargs) _function.__name__ = function.__name__ self.server.register_function(_function, name) def serve_forever(self): self.server.serve_forever() #example usage server = Server(('localhost', 8000)) def test(arg1, arg2): print 'arg1: %s arg2: %s' % (arg1, arg2) return 0 server.register_function(test) server.serve_forever() ``` ## Client ``` import xmlrpclib class ServerProxy(object): def __init__(self, url): self._xmlrpc_server_proxy = xmlrpclib.ServerProxy(url) def __getattr__(self, name): call_proxy = getattr(self._xmlrpc_server_proxy, name) def _call(*args, **kwargs): return call_proxy(args, kwargs) return _call #example usage server = ServerProxy('http://localhost:8000') server.test(1, 2) server.test(arg2=2, arg1=1) server.test(1, arg2=2) server.test(*[1,2]) server.test(**{'arg1':1, 'arg2':2}) ```
Fetch a Wikipedia article with Python
120,061
35
2008-09-23T09:37:21Z
120,113
36
2008-09-23T09:49:44Z
[ "python", "urllib2", "user-agent", "wikipedia", "http-status-code-403" ]
I try to fetch a Wikipedia article with Python's urllib: ``` f = urllib.urlopen("http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes") s = f.read() f.close() ``` However instead of the html page I get the following response: Error - Wikimedia Foundation: ``` Request: GET http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes, from 192.35.17.11 via knsq1.knams.wikimedia.org (squid/2.6.STABLE21) to () Error: ERR_ACCESS_DENIED, errno [No Error] at Tue, 23 Sep 2008 09:09:08 GMT ``` Wikipedia seems to block request which are not from a standard browser. Anybody know how to work around this?
It is not a solution to the specific problem. But it might be intersting for you to use the mwclient library (<http://botwiki.sno.cc/wiki/Python:Mwclient>) instead. That would be so much easier. Especially since you will directly get the article contents which removes the need for you to parse the html. I have used it myself for two projects, and it works very well.
Fetch a Wikipedia article with Python
120,061
35
2008-09-23T09:37:21Z
120,118
48
2008-09-23T09:50:39Z
[ "python", "urllib2", "user-agent", "wikipedia", "http-status-code-403" ]
I try to fetch a Wikipedia article with Python's urllib: ``` f = urllib.urlopen("http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes") s = f.read() f.close() ``` However instead of the html page I get the following response: Error - Wikimedia Foundation: ``` Request: GET http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes, from 192.35.17.11 via knsq1.knams.wikimedia.org (squid/2.6.STABLE21) to () Error: ERR_ACCESS_DENIED, errno [No Error] at Tue, 23 Sep 2008 09:09:08 GMT ``` Wikipedia seems to block request which are not from a standard browser. Anybody know how to work around this?
You need to use the [urllib2](http://docs.python.org/lib/module-urllib2.html) that superseedes [urllib](http://docs.python.org/lib/module-urllib.html) in the [python std library](http://docs.python.org/lib/) in order to change the user agent. Straight from the [examples](http://web.archive.org/web/20070202031348/http://docs.python.org/lib/urllib2-examples.html) ``` import urllib2 opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] infile = opener.open('http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes') page = infile.read() ```
Fetch a Wikipedia article with Python
120,061
35
2008-09-23T09:37:21Z
980,529
14
2009-06-11T11:14:20Z
[ "python", "urllib2", "user-agent", "wikipedia", "http-status-code-403" ]
I try to fetch a Wikipedia article with Python's urllib: ``` f = urllib.urlopen("http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes") s = f.read() f.close() ``` However instead of the html page I get the following response: Error - Wikimedia Foundation: ``` Request: GET http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes, from 192.35.17.11 via knsq1.knams.wikimedia.org (squid/2.6.STABLE21) to () Error: ERR_ACCESS_DENIED, errno [No Error] at Tue, 23 Sep 2008 09:09:08 GMT ``` Wikipedia seems to block request which are not from a standard browser. Anybody know how to work around this?
Rather than trying to trick Wikipedia, you should consider using their [High-Level API](http://www.mediawiki.org/wiki/API).
Short Integers in Python
120,250
10
2008-09-23T10:35:09Z
120,256
30
2008-09-23T10:36:44Z
[ "python", "memory-management", "short" ]
Python allocates integers automatically based on the underlying system architecture. Unfortunately I have a huge dataset which needs to be fully loaded into memory. So, is there a way to force Python to use only 2 bytes for some integers (equivalent of C++ 'short')?
Nope. But you can use short integers in arrays: ``` from array import array a = array("h") # h = signed short, H = unsigned short ``` As long as the value stays in that array it will be a short integer. * documentation for the [array module](http://docs.python.org/dev/library/array)
SVG rendering in a PyGame application
120,584
17
2008-09-23T12:13:14Z
341,742
11
2008-12-04T19:23:54Z
[ "python", "svg", "widget", "pygame" ]
In a [pyGame](http://www.pygame.org/) application, I would like to render resolution-free GUI widgets described in SVG. What tool and/or library can I use to reach this goal ? (I like the [OCEMP GUI](http://ocemp.sourceforge.net/gui.html) toolkit but it seems to be bitmap dependent for its rendering)
This is a complete example which combines hints by other people here. It should render a file called test.svg from the current directory. It was tested on Ubuntu 10.10, python-cairo 1.8.8, python-pygame 1.9.1, python-rsvg 2.30.0. ``` #!/usr/bin/python import array import math import cairo import pygame import rsvg WIDTH = 512 HEIGHT = 512 data = array.array('c', chr(0) * WIDTH * HEIGHT * 4) surface = cairo.ImageSurface.create_for_data( data, cairo.FORMAT_ARGB32, WIDTH, HEIGHT, WIDTH * 4) pygame.init() window = pygame.display.set_mode((WIDTH, HEIGHT)) svg = rsvg.Handle(file="test.svg") ctx = cairo.Context(surface) svg.render_cairo(ctx) screen = pygame.display.get_surface() image = pygame.image.frombuffer(data.tostring(), (WIDTH, HEIGHT),"ARGB") screen.blit(image, (0, 0)) pygame.display.flip() clock = pygame.time.Clock() while True: clock.tick(15) for event in pygame.event.get(): if event.type == pygame.QUIT: raise SystemExit ```
Directory listing in Python
120,656
413
2008-09-23T12:28:19Z
120,676
370
2008-09-23T12:32:00Z
[ "python", "filesystems" ]
How do I get a list of all files (and directories) in a given directory in Python?
You can use ``` os.listdir(path) ``` For reference and more os functions look here: * Python 2 docs: <https://docs.python.org/2/library/os.html#os.listdir> * Python 3 docs: <https://docs.python.org/3.4/library/os.html#os.listdir>
Directory listing in Python
120,656
413
2008-09-23T12:28:19Z
120,692
74
2008-09-23T12:34:07Z
[ "python", "filesystems" ]
How do I get a list of all files (and directories) in a given directory in Python?
``` import os for filename in os.listdir("C:\\temp"): print filename ```
Directory listing in Python
120,656
413
2008-09-23T12:28:19Z
120,695
9
2008-09-23T12:34:34Z
[ "python", "filesystems" ]
How do I get a list of all files (and directories) in a given directory in Python?
Try this: ``` import os for top, dirs, files in os.walk('./'): for nm in files: print os.path.join(top, nm) ```
Directory listing in Python
120,656
413
2008-09-23T12:28:19Z
120,701
503
2008-09-23T12:35:46Z
[ "python", "filesystems" ]
How do I get a list of all files (and directories) in a given directory in Python?
This is a way to traverse every file and directory in a directory tree: ``` import os for dirname, dirnames, filenames in os.walk('.'): # print path to all subdirectories first. for subdirname in dirnames: print(os.path.join(dirname, subdirname)) # print path to all filenames. for filename in filenames: print(os.path.join(dirname, filename)) # Advanced usage: # editing the 'dirnames' list will stop os.walk() from recursing into there. if '.git' in dirnames: # don't go into any .git directories. dirnames.remove('.git') ```
Directory listing in Python
120,656
413
2008-09-23T12:28:19Z
120,948
63
2008-09-23T13:23:29Z
[ "python", "filesystems" ]
How do I get a list of all files (and directories) in a given directory in Python?
Here's a helper function I use quite often: ``` import os def listdir_fullpath(d): return [os.path.join(d, f) for f in os.listdir(d)] ```
Directory listing in Python
120,656
413
2008-09-23T12:28:19Z
12,572,822
10
2012-09-24T20:58:14Z
[ "python", "filesystems" ]
How do I get a list of all files (and directories) in a given directory in Python?
If you need globbing abilities, there's a module for that as well. For example: ``` import glob glob.glob('./[0-9].*') ``` will return something like: ``` ['./1.gif', './2.txt'] ``` See the documentation [here](http://docs.python.org/library/glob.html).
Why does Python pep-8 strongly recommend spaces over tabs for indentation?
120,926
90
2008-09-23T13:20:34Z
120,956
25
2008-09-23T13:24:26Z
[ "python", "indentation" ]
I see on Stack Overflow and [PEP 8](http://www.python.org/dev/peps/pep-0008/) that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain. Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with.
The problem with tabs is that they are invisible, and people can never agree on the width of tabs. When you mix tabs and spaces, and you set tabstops at something other than Python (which uses tabstops every 8 spaces) you will be seeing the code in a different layout than Python sees it. And because the layout determines blocks, you will be seeing different logic. It leads to subtle bugs. If you insist on defying PEP 8 and using tabs -- or worse, mixing tabs and spaces -- at least always run python with the '-tt' argument, which makes *inconsistent* indentation (sometimes a tab, sometimes a space for the same indentation level) an error. Also, if possible, set your editor to display tabs differently. But really, the best approach is not to use tabs, period.
Why does Python pep-8 strongly recommend spaces over tabs for indentation?
120,926
90
2008-09-23T13:20:34Z
121,481
28
2008-09-23T14:45:39Z
[ "python", "indentation" ]
I see on Stack Overflow and [PEP 8](http://www.python.org/dev/peps/pep-0008/) that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain. Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with.
The reason for spaces is that tabs are optional. Spaces are the actual lowest-common denominator in punctuation. Every decent text editor has a "replace tabs with spaces" and many people use this. But not always. While some text editors might replace a run of spaces with a tab, this is really rare. **Bottom Line**. You can't go wrong with spaces. You *might* go wrong with tabs. So don't use tabs and reduce the risk of mistakes.
Why does Python pep-8 strongly recommend spaces over tabs for indentation?
120,926
90
2008-09-23T13:20:34Z
121,671
74
2008-09-23T15:19:27Z
[ "python", "indentation" ]
I see on Stack Overflow and [PEP 8](http://www.python.org/dev/peps/pep-0008/) that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain. Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with.
The answer was given right there in the PEP [ed: this passage has been edited out in [2013](https://hg.python.org/peps/rev/fb24c80e9afb#l1.75)]. I quote: > The **most popular** way of indenting Python is with spaces only. What other underlying reason do you need? To put it less bluntly: Consider also the scope of the PEP as stated in the very first paragraph: > This document gives coding conventions for the Python code comprising the standard library in the main Python distribution. The intention is to make *all code that goes in the official python distribution* consistently formatted (I hope we can agree that this is universally a Good Thing™). Since the decision between spaces and tabs for an individual programmer is a) really a matter of taste and b) easily dealt with by technical means (editors, conversion scripts, etc.), there is a clear way to end all discussion: chose one. Guido was the one to choose. He didn't even have to give a reason, but he still did by referring to empirical data. For all other purposes you can either take this PEP as a recommendation, or you can ignore it -- your choice, or your team's, or your team leaders. But if I may give you one advice: don't mix'em ;-) [ed: Mixing tabs and spaces is no longer an option.]
Why does Python pep-8 strongly recommend spaces over tabs for indentation?
120,926
90
2008-09-23T13:20:34Z
143,995
7
2008-09-27T16:56:59Z
[ "python", "indentation" ]
I see on Stack Overflow and [PEP 8](http://www.python.org/dev/peps/pep-0008/) that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain. Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with.
The answer to the question is: PEP-8 wants to make a recommendation and has decided that since spaces are more popular it will strongly recommend spaces over tabs. --- Notes on PEP-8 PEP-8 says *'Use 4 spaces per indentation level.'* Its clear that this is the standard recommendation. *'For really old code that you don't want to mess up, you can continue to use 8-space tabs.'* Its clear that there are SOME circumstances when tabs can be used. *'Never mix tabs and spaces.'* This is a clear prohibition of mixing - I think we all agree on this. Python can detect this and often chokes. Using the -tt argument makes this an explicit error. *'The most popular way of indenting Python is with spaces only. The second-most popular way is with tabs only.'* This clearly states that both are used. Just to be ultra-clear: You should still never mix spaces and tabs in same file. *'For new projects, spaces-only are strongly recommended over tabs.'* This is a clear recommendation, and a strong one, but not a prohibition of tabs. --- I can't find a good answer to my own question in PEP-8. I use tabs, which I have used historically in other languages. Python accepts source with exclusive use of tabs. That's good enough for me. I thought I would have a go at working with spaces. In my editor, I configured a file type to use spaces exclusively and so it inserts 4 spaces if I press tab. If I press tab too many times, I have to delete the spaces! **Arrgh!** Four times as many deletes as tabs! My editor can't tell that I'm using 4 spaces for indents (although AN editor might be able to do this) and obviously insists on deleting the spaces one at a time. Couldn't Python be told to consider tabs to be n spaces when its reading indentations? If we could agree on 4 spaces per indentation and 4 spaces per tab and allow Python to accept this, then there would be no problems. We should find win-win solutions to problems.
Why does Python pep-8 strongly recommend spaces over tabs for indentation?
120,926
90
2008-09-23T13:20:34Z
144,096
19
2008-09-27T17:32:09Z
[ "python", "indentation" ]
I see on Stack Overflow and [PEP 8](http://www.python.org/dev/peps/pep-0008/) that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain. Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with.
The main problems with indentation occur when you mix tabs and spaces. Obviously this doesn't tell you which you should choose, but it is a good reason to to recommend one, even if you pick it by flipping a coin. However, IMHO there are a few minor reasons to favour spaces over tabs: * Different tools. Sometimes code gets displayed outside of a programmer's editor. Eg. posted to a newsgroup or forum. Spaces generally do better than tabs here - everywhere spaces would get mangled, tabs do as well, but not vice-versa. * Programmers see the source differently. This is deeply subjective - its either the main benefit of tabs, or a reason to avoid them depending on which side you're on. On the plus side, developers can view the source with their preferred indentation, so a developer preferring 2-space indent can work with an 8-space developer on the same source and still see it as they like. The downside is that there are repercussions to this - some people like 8-space because it gives very visible feedback that they're too deeply nested - they may see code checked in by the 2-indenter constantly wrapping in their editor. Having every developer see the code the same way leads to more consistency wrt line lengths, and other matters too. * Continued line indentation. Sometimes you want to indent a line to indicate it is carried from the previous one. eg. ``` def foo(): x = some_function_with_lots_of_args(foo, bar, baz, xyzzy, blah) ``` If using tabs, theres no way to align this for people using different tabstops in their editor without mixing spaces and tabs. This effectively kills the above benefit. Obviously though, this is a deeply religious issue, which programming is plagued with. The most important issue is that we should choose one - even if thats not the one you favour. Sometimes I think that the biggest advantage of significant indentation is that at least we're spared brace placement flamewars. Also worth reading is [this](http://www.jwz.org/doc/tabs-vs-spaces.html) article by Jamie Zawinski on the issue.
Why does Python pep-8 strongly recommend spaces over tabs for indentation?
120,926
90
2008-09-23T13:20:34Z
872,883
23
2009-05-16T17:41:35Z
[ "python", "indentation" ]
I see on Stack Overflow and [PEP 8](http://www.python.org/dev/peps/pep-0008/) that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain. Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with.
I personally don't agree with spaces over tabs. To me, tabs are a document layout character/mechanism while spaces are for content or delineation between commands in the case of code. I have to agree with Jim's comments that tabs aren't really the issue, it is people and how they want to mix tabs and spaces. That said, I've forced myself to use spaces for the sake of convention. I value consistency over personal preference.
Why does Python pep-8 strongly recommend spaces over tabs for indentation?
120,926
90
2008-09-23T13:20:34Z
5,048,130
34
2011-02-19T00:56:16Z
[ "python", "indentation" ]
I see on Stack Overflow and [PEP 8](http://www.python.org/dev/peps/pep-0008/) that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain. Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with.
Well well, seems like everybody is strongly biased towards spaces. I use tabs exclusively. I know very well why. Tabs are actually a cool invention, that came **after** spaces. It allows you to indent without pushing space millions of times or using a fake tab (that produces spaces). I really don't get why everybody is discriminating the use of tabs. It is very much like old people discriminating younger people for choosing a newer more efficient technology and complaining that pulse dialing works on **every phone**, not just on these fancy new ones. "Tone dialing doesn't work on every phone, that's why it is wrong". Your editor cannot handle tabs properly? Well, get a **modern** editor. Might be darn time, we are now in the 21st century and the time when an editor was a high tech complicated piece of software is long past. We have now tons and tons of editors to choose from, all of them that support tabs just fine. Also, you can define how much a tab should be, a thing that you cannot do with spaces. Cannot see tabs? What is that for an argument? Well, you cannot see spaces neither! May I be so bold to suggest to get a better editor? One of these high tech ones, that were released some 10 years ago already, that **display invisible characters**? (sarcasm off) Using spaces causes a lot more deleting and formatting work. That is why (and all other people that know this and agree with me) use tabs for Python. Mixing tabs and spaces is a no-no and no argument about that. That is a mess and can never work.
Why does Python pep-8 strongly recommend spaces over tabs for indentation?
120,926
90
2008-09-23T13:20:34Z
18,034,554
7
2013-08-03T15:49:14Z
[ "python", "indentation" ]
I see on Stack Overflow and [PEP 8](http://www.python.org/dev/peps/pep-0008/) that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain. Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with.
Note that the use of tabs confuses another aspect of PEP 8: > Limit all lines to a maximum of 79 characters. Let's say, hypothetically, that you use a tab width of 2 and I use a tab width of 8. You write all your code so your longest lines reach 79 characters, then I start to work on your file. Now I've got hard-to-read code because (as the PEP states): > The default wrapping in most tools disrupts the visual structure of the code If we all use 4 spaces, it's ALWAYS the same. Anyone whose editor can support an 80 character width can comfortably read the code. *Note: The 80 character limit is a holy war in and of itself, so let's not start that here.* Any non-sucky editor should have an option to use spaces as if they were tabs (both inserting and deleting), so that really shouldn't be a valid argument.
How can I normalize a URL in python
120,951
55
2008-09-23T13:23:50Z
120,959
9
2008-09-23T13:25:01Z
[ "python", "url", "normalization", "normalize" ]
I'd like to know do I normalize a URL in python. For example, If I have a url string like : "http://www.example.com/foo goo/bar.html" I need a library in python that will transform the extra space (or any other non normalized character) to a proper URL.
``` import urlparse, urllib def myquote(url): parts= urlparse.urlparse(url) return urlparse.urlunparse(parts[:2] + urllib.quote(parts[2]) + parts[3:]) ``` This quotes only the path component. Otherwise, you could do: `urllib.quote(url, safe=":/")`
How can I normalize a URL in python
120,951
55
2008-09-23T13:23:50Z
120,971
18
2008-09-23T13:26:16Z
[ "python", "url", "normalization", "normalize" ]
I'd like to know do I normalize a URL in python. For example, If I have a url string like : "http://www.example.com/foo goo/bar.html" I need a library in python that will transform the extra space (or any other non normalized character) to a proper URL.
use `urllib.quote` or `urllib.quote_plus` From the [urllib documentation](http://docs.python.org/lib/module-urllib.html): > **quote(string[, safe])** > > Replace special characters in string > using the "%xx" escape. Letters, > digits, and the characters "\_.-" are > never quoted. The optional safe > parameter specifies additional > characters that should not be quoted > -- its default value is '/'. > > Example: `quote('/~connolly/')` yields `'/%7econnolly/'`. > > **quote\_plus(string[, safe])** > > Like quote(), but also replaces spaces > by plus signs, as required for quoting > HTML form values. Plus signs in the > original string are escaped unless > they are included in safe. It also > does not have safe default to '/'. EDIT: Using urllib.quote or urllib.quote\_plus on the whole URL will mangle it, as @[ΤΖΩΤΖΙΟΥ](#120959) points out: ``` >>> quoted_url = urllib.quote('http://www.example.com/foo goo/bar.html') >>> quoted_url 'http%3A//www.example.com/foo%20goo/bar.html' >>> urllib2.urlopen(quoted_url) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "c:\python25\lib\urllib2.py", line 124, in urlopen return _opener.open(url, data) File "c:\python25\lib\urllib2.py", line 373, in open protocol = req.get_type() File "c:\python25\lib\urllib2.py", line 244, in get_type raise ValueError, "unknown url type: %s" % self.__original ValueError: unknown url type: http%3A//www.example.com/foo%20goo/bar.html ``` @[ΤΖΩΤΖΙΟΥ](#120959) provides a function that uses [urlparse.urlparse and urlparse.urlunparse](http://docs.python.org/lib/module-urlparse.html) to parse the url and only encode the path. This may be more useful for you, although if you're building the URL from a known protocol and host but with a suspect path, you could probably do just as well to avoid urlparse and just quote the suspect part of the URL, concatenating with known safe parts.
How can I normalize a URL in python
120,951
55
2008-09-23T13:23:50Z
121,017
60
2008-09-23T13:33:06Z
[ "python", "url", "normalization", "normalize" ]
I'd like to know do I normalize a URL in python. For example, If I have a url string like : "http://www.example.com/foo goo/bar.html" I need a library in python that will transform the extra space (or any other non normalized character) to a proper URL.
Have a look at this module: [werkzeug.utils](https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/urls.py). (now in `werkzeug.urls`) The function you are looking for is called "url\_fix" and works like this: ``` >>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)') 'http://de.wikipedia.org/wiki/Elf%20%28Begriffskl%C3%A4rung%29' ``` It's implemented in Werkzeug as follows: ``` import urllib import urlparse def url_fix(s, charset='utf-8'): """Sometimes you get an URL by a user that just isn't a real URL because it contains unsafe characters like ' ' and so on. This function can fix some of the problems in a similar way browsers handle data entered by the user: >>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)') 'http://de.wikipedia.org/wiki/Elf%20%28Begriffskl%C3%A4rung%29' :param charset: The target charset for the URL if the url was given as unicode string. """ if isinstance(s, unicode): s = s.encode(charset, 'ignore') scheme, netloc, path, qs, anchor = urlparse.urlsplit(s) path = urllib.quote(path, '/%') qs = urllib.quote_plus(qs, ':&=') return urlparse.urlunsplit((scheme, netloc, path, qs, anchor)) ```
How can I normalize a URL in python
120,951
55
2008-09-23T13:23:50Z
845,595
46
2009-05-10T16:15:40Z
[ "python", "url", "normalization", "normalize" ]
I'd like to know do I normalize a URL in python. For example, If I have a url string like : "http://www.example.com/foo goo/bar.html" I need a library in python that will transform the extra space (or any other non normalized character) to a proper URL.
[Real fix in Python 2.7 for that problem](http://svn.python.org/view/python/trunk/Lib/urllib.py?r1=71780&r2=71779&pathrev=71780) Right solution was: ``` # percent encode url, fixing lame server errors for e.g, like space # within url paths. fullurl = quote(fullurl, safe="%/:=&?~#+!$,;'@()*[]") ``` For more information see [Issue918368: "urllib doesn't correct server returned urls"](http://bugs.python.org/issue918368)
How can I normalize a URL in python
120,951
55
2008-09-23T13:23:50Z
962,248
12
2009-06-07T16:35:25Z
[ "python", "url", "normalization", "normalize" ]
I'd like to know do I normalize a URL in python. For example, If I have a url string like : "http://www.example.com/foo goo/bar.html" I need a library in python that will transform the extra space (or any other non normalized character) to a proper URL.
Because this page is a top result for Google searches on the topic, I think it's worth mentioning some work that has been done on URL normalization with Python that goes beyond urlencoding space characters. For example, dealing with default ports, character case, lack of trailing slashes, etc. When the Atom syndication format was being developed, there was some discussion on how to normalize URLs into canonical format; this is documented in the article [PaceCanonicalIds](http://www.intertwingly.net/wiki/pie/PaceCanonicalIds) on the Atom/Pie wiki. That article provides some good test cases. I believe that one result of this discussion was Mark Nottingham's [urlnorm.py](http://www.mnot.net/python/urlnorm.py) library, which I've used with good results on a couple projects. That script doesn't work with the URL given in this question, however. So a better choice might be [Sam Ruby's version of urlnorm.py](http://intertwingly.net/blog/2004/08/04/Urlnorm), which handles that URL, and all of the aforementioned test cases from the Atom wiki.
Accessing object memory address
121,396
89
2008-09-23T14:35:00Z
121,422
32
2008-09-23T14:37:24Z
[ "python", "object", "tostring", "memory-address", "repr" ]
When you call the `object.__repr__()` method in python you get something like this back: `<__main__.Test object at 0x2aba1c0cf890>`, is there any way to get a hold of the memory address if you overload `__repr__()`, other then calling `super(Class, obj).__repr__()` and regexing it out?
Just use ``` id(object) ```
Accessing object memory address
121,396
89
2008-09-23T14:35:00Z
121,452
116
2008-09-23T14:41:30Z
[ "python", "object", "tostring", "memory-address", "repr" ]
When you call the `object.__repr__()` method in python you get something like this back: `<__main__.Test object at 0x2aba1c0cf890>`, is there any way to get a hold of the memory address if you overload `__repr__()`, other then calling `super(Class, obj).__repr__()` and regexing it out?
The [Python manual](https://docs.python.org/2/library/functions.html#id) has this to say about id(): > Return the ``identity'' of an object. > This is an integer (or long integer) > which is guaranteed to be unique and > constant for this object during its > lifetime. Two objects with > non-overlapping lifetimes may have the > same id() value. (Implementation note: > this is the address of the object.) So in CPython, this will be the address of the object. No such guarantee for any other Python interpreter, though. Note that if you're writing a C extension, you have full access to the internals of the Python interpreter, including access to the addresses of objects directly.
Accessing object memory address
121,396
89
2008-09-23T14:35:00Z
121,508
46
2008-09-23T14:49:57Z
[ "python", "object", "tostring", "memory-address", "repr" ]
When you call the `object.__repr__()` method in python you get something like this back: `<__main__.Test object at 0x2aba1c0cf890>`, is there any way to get a hold of the memory address if you overload `__repr__()`, other then calling `super(Class, obj).__repr__()` and regexing it out?
You could reimplement the default repr this way: ``` def __repr__(self): return '<%s.%s object at %s>' % ( self.__class__.__module__, self.__class__.__name__, hex(id(self)) ) ```
Accessing object memory address
121,396
89
2008-09-23T14:35:00Z
4,628,230
11
2011-01-07T17:14:04Z
[ "python", "object", "tostring", "memory-address", "repr" ]
When you call the `object.__repr__()` method in python you get something like this back: `<__main__.Test object at 0x2aba1c0cf890>`, is there any way to get a hold of the memory address if you overload `__repr__()`, other then calling `super(Class, obj).__repr__()` and regexing it out?
Just in response to Torsten, I wasn't able to call `addressof()` on a regular python object. Furthermore, `id(a) != addressof(a)`. This is in CPython, don't know about anything else. ``` >>> from ctypes import c_int, addressof >>> a = 69 >>> addressof(a) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: invalid type >>> b = c_int(69) >>> addressof(b) 4300673472 >>> id(b) 4300673392 ```
Accessing object memory address
121,396
89
2008-09-23T14:35:00Z
26,285,749
9
2014-10-09T18:41:51Z
[ "python", "object", "tostring", "memory-address", "repr" ]
When you call the `object.__repr__()` method in python you get something like this back: `<__main__.Test object at 0x2aba1c0cf890>`, is there any way to get a hold of the memory address if you overload `__repr__()`, other then calling `super(Class, obj).__repr__()` and regexing it out?
There are a few issues here that aren't covered by any of the other answers. First, [`id`](https://docs.python.org/3/library/functions.html#id) only returns: > the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same `id()` value. --- In CPython, this happens to be the pointer to the [`PyObject`](https://docs.python.org/3/c-api/object.html) that represents the object in the interpreter, which is the same thing that `object.__repr__` displays. But this is just an implementation detail of CPython, not something that's true of Python in general. Jython doesn't deal in pointers, it deals in Java references (which the JVM of course probably represents as pointers, but you can't see those—and wouldn't want to, because the GC is allowed to move them around). PyPy lets different types have different kinds of `id`, but the most general is just an index into a table of objects you've called `id` on, which is obviously not going to be a pointer. I'm not sure about IronPython, but I'd suspect it's more like Jython than like CPython in this regard. So, in most Python implementations, there's no way to get whatever showed up in that `repr`, and no use if you did. --- But what if you only care about CPython? That's a pretty common case, after all. Well, first, you may notice that `id` is an integer;\* if you want that `0x2aba1c0cf890` string instead of the number `46978822895760`, you're going to have to format it yourself. Under the covers, I believe `object.__repr__` is ultimately using `printf`'s `%p` format, which you don't have from Python… but you can always do this: ``` format(id(spam), '#010x' if sys.maxsize.bit_length() <= 32 else '#18x') ``` \* In 3.x, it's an `int`. In 2.x, it's an `int` if that's big enough to hold a pointer—which is may not be because of signed number issues on some platforms—and a `long` otherwise. Is there anything you can do with these pointers besides print them out? Sure (again, assuming you only care about CPython). All of the [C API](https://docs.python.org/3/c-api/index.html) functions take a pointer to a `PyObject` or a related type. For those related types, you can just call `PyFoo_Check` to make sure it really is a `Foo` object, then cast with `(PyFoo *)p`. So, if you're writing a C extension, the `id` is exactly what you need. What if you're writing pure Python code? You can call the exact same functions with [`pythonapi`](https://docs.python.org/3/library/ctypes.html#accessing-values-exported-from-dlls) from `ctypes`. --- Finally, a few of the other answers have brought up [`ctypes.addressof`](https://docs.python.org/3/library/ctypes.html#ctypes.addressof). That isn't relevant here. This only works for `ctypes` objects like `c_int32` (and maybe a few memory-buffer-like objects, like those provided by `numpy`). And, even there, it isn't giving you the address of the `c_int32` value, it's giving you the address of the C-level `int32` that the `c_int32` wraps up. That being said, more often than not, if you really think you need the address of something, you didn't want a native Python object in the first place, you wanted a `ctypes` object.
How do I include a stacktrace in my Django 500.html page?
121,439
18
2008-09-23T14:39:35Z
121,474
14
2008-09-23T14:44:50Z
[ "python", "django", "templates", "stack-trace" ]
I'm running `Django 1.0` and I'm close to deploying my app. As such, I'll be changing the DEBUG setting to False. With that being said, I'd still like to include the stacktrace on my 500.html page when errors occur. By doing so, users can copy-and-paste the errors and easily email them to the developers. Any thoughts on how best to approach this issue?
Automatically log your 500s, that way: * You know when they occur. * You don't need to rely on users sending you stacktraces. Joel recommends even going so far as automatically creating tickets in your bug tracker when your application experiences a failure. Personally, I create a (private) RSS feed with the stacktraces, urls, etc. that the developers can subscribe to. Showing stack traces to your users on the other hand could possibly leak information that malicious users could use to attack your site. Overly detailed error messages are one of the classic stepping stones to SQL injection attacks. *Edit* (added code sample to capture traceback): You can get the exception information from the sys.exc\_info call. While formatting the traceback for display comes from the traceback module: ``` import traceback import sys try: raise Exception("Message") except: type, value, tb = sys.exc_info() print >> sys.stderr, type.__name__, ":", value print >> sys.stderr, '\n'.join(traceback.format_tb(tb)) ``` Prints: ``` Exception : Message File "exception.py", line 5, in <module> raise Exception("Message") ```
How do I include a stacktrace in my Django 500.html page?
121,439
18
2008-09-23T14:39:35Z
122,482
11
2008-09-23T17:32:19Z
[ "python", "django", "templates", "stack-trace" ]
I'm running `Django 1.0` and I'm close to deploying my app. As such, I'll be changing the DEBUG setting to False. With that being said, I'd still like to include the stacktrace on my 500.html page when errors occur. By doing so, users can copy-and-paste the errors and easily email them to the developers. Any thoughts on how best to approach this issue?
As @zacherates says, you really don't want to display a stacktrace to your users. The easiest approach to this problem is what Django does by default if you have yourself and your developers listed in the ADMINS setting with email addresses; it sends an email to everyone in that list with the full stack trace (and more) everytime there is a 500 error with DEBUG = False.
How do I write this in Ruby/Python? Or, can you translate my LINQ to Ruby/Python?
122,033
7
2008-09-23T16:10:42Z
122,064
13
2008-09-23T16:18:19Z
[ "python", "ruby", "linq", "functional-programming" ]
Yesterday, I asked [this](http://stackoverflow.com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby) question and never really got an answer I was really happy with. I really would like to know how to generate a list of N unique random numbers using a functional language such as Ruby without having to be extremely imperative in style. Since I didn't see anything I really liked, I've written the solution I was looking for in LINQ: ``` static void Main(string[] args) { var temp = from q in GetRandomNumbers(100).Distinct().Take(5) select q; } private static IEnumerable GetRandomNumbers(int max) { Random r = new Random(); while (true) { yield return r.Next(max); } } ``` Can you translate my LINQ to Ruby? Python? Any other functional programming language? **Note:** Please try not to use too many loops and conditionals - otherwise the solution is trivial. Also, I'd rather see a solution where you don't have to generate an array much bigger than N so you can then just remove the duplicates and trim it down to N. I know I'm being picky, but I'd really like to see some elegant solutions to this problem. Thanks! **Edit:** Why all the downvotes? Originally my code sample had the Distinct() after the Take() which, as many pointed out, could leave me with an empty list. I've changed the order in which those methods are called to reflect what I meant in the first place. **Apology:** I've been told this post came across as rather snobbish. I wasn't trying to imply that LINQ is better than Ruby/Python; or that my solution is much better than everyone else's. My intent is just to learn how to do this (with certain constraints) in Ruby. I'm sorry if I came across as a jerk.
``` >>> import random >>> print random.sample(xrange(100), 5) [61, 54, 91, 72, 85] ``` This should yield 5 unique values in the range `0 — 99`. The `xrange` object generates values as requested so no memory is used for values that aren't sampled.
How do you translate this regular-expression idiom from Perl into Python?
122,277
35
2008-09-23T16:55:18Z
122,294
16
2008-09-23T16:58:53Z
[ "python", "regex", "perl" ]
I switched from Perl to Python about a year ago and haven't looked back. There is only *one* idiom that I've ever found I can do more easily in Perl than in Python: ``` if ($var =~ /foo(.+)/) { # do something with $1 } elsif ($var =~ /bar(.+)/) { # do something with $1 } elsif ($var =~ /baz(.+)/) { # do something with $1 } ``` The corresponding Python code is not so elegant since the if statements keep getting nested: ``` m = re.search(r'foo(.+)', var) if m: # do something with m.group(1) else: m = re.search(r'bar(.+)', var) if m: # do something with m.group(1) else: m = re.search(r'baz(.+)', var) if m: # do something with m.group(2) ``` Does anyone have an elegant way to reproduce this pattern in Python? I've seen anonymous function dispatch tables used, but those seem kind of unwieldy to me for a small number of regular expressions...
Using named groups and a dispatch table: ``` r = re.compile(r'(?P<cmd>foo|bar|baz)(?P<data>.+)') def do_foo(data): ... def do_bar(data): ... def do_baz(data): ... dispatch = { 'foo': do_foo, 'bar': do_bar, 'baz': do_baz, } m = r.match(var) if m: dispatch[m.group('cmd')](m.group('data')) ``` With a little bit of introspection you can auto-generate the regexp and the dispatch table.
How do you translate this regular-expression idiom from Perl into Python?
122,277
35
2008-09-23T16:55:18Z
123,083
10
2008-09-23T19:04:53Z
[ "python", "regex", "perl" ]
I switched from Perl to Python about a year ago and haven't looked back. There is only *one* idiom that I've ever found I can do more easily in Perl than in Python: ``` if ($var =~ /foo(.+)/) { # do something with $1 } elsif ($var =~ /bar(.+)/) { # do something with $1 } elsif ($var =~ /baz(.+)/) { # do something with $1 } ``` The corresponding Python code is not so elegant since the if statements keep getting nested: ``` m = re.search(r'foo(.+)', var) if m: # do something with m.group(1) else: m = re.search(r'bar(.+)', var) if m: # do something with m.group(1) else: m = re.search(r'baz(.+)', var) if m: # do something with m.group(2) ``` Does anyone have an elegant way to reproduce this pattern in Python? I've seen anonymous function dispatch tables used, but those seem kind of unwieldy to me for a small number of regular expressions...
Yeah, it's kind of annoying. Perhaps this will work for your case. ``` import re class ReCheck(object): def __init__(self): self.result = None def check(self, pattern, text): self.result = re.search(pattern, text) return self.result var = 'bar stuff' m = ReCheck() if m.check(r'foo(.+)',var): print m.result.group(1) elif m.check(r'bar(.+)',var): print m.result.group(1) elif m.check(r'baz(.+)',var): print m.result.group(1) ``` **EDIT:** Brian correctly pointed out that my first attempt did not work. Unfortunately, this attempt is longer.
How do you translate this regular-expression idiom from Perl into Python?
122,277
35
2008-09-23T16:55:18Z
124,128
9
2008-09-23T21:50:45Z
[ "python", "regex", "perl" ]
I switched from Perl to Python about a year ago and haven't looked back. There is only *one* idiom that I've ever found I can do more easily in Perl than in Python: ``` if ($var =~ /foo(.+)/) { # do something with $1 } elsif ($var =~ /bar(.+)/) { # do something with $1 } elsif ($var =~ /baz(.+)/) { # do something with $1 } ``` The corresponding Python code is not so elegant since the if statements keep getting nested: ``` m = re.search(r'foo(.+)', var) if m: # do something with m.group(1) else: m = re.search(r'bar(.+)', var) if m: # do something with m.group(1) else: m = re.search(r'baz(.+)', var) if m: # do something with m.group(2) ``` Does anyone have an elegant way to reproduce this pattern in Python? I've seen anonymous function dispatch tables used, but those seem kind of unwieldy to me for a small number of regular expressions...
I'd suggest this, as it uses the least regex to accomplish your goal. It is still functional code, but no worse then your old Perl. ``` import re var = "barbazfoo" m = re.search(r'(foo|bar|baz)(.+)', var) if m.group(1) == 'foo': print m.group(1) # do something with m.group(1) elif m.group(1) == "bar": print m.group(1) # do something with m.group(1) elif m.group(1) == "baz": print m.group(2) # do something with m.group(2) ```
How do you translate this regular-expression idiom from Perl into Python?
122,277
35
2008-09-23T16:55:18Z
135,720
9
2008-09-25T20:10:55Z
[ "python", "regex", "perl" ]
I switched from Perl to Python about a year ago and haven't looked back. There is only *one* idiom that I've ever found I can do more easily in Perl than in Python: ``` if ($var =~ /foo(.+)/) { # do something with $1 } elsif ($var =~ /bar(.+)/) { # do something with $1 } elsif ($var =~ /baz(.+)/) { # do something with $1 } ``` The corresponding Python code is not so elegant since the if statements keep getting nested: ``` m = re.search(r'foo(.+)', var) if m: # do something with m.group(1) else: m = re.search(r'bar(.+)', var) if m: # do something with m.group(1) else: m = re.search(r'baz(.+)', var) if m: # do something with m.group(2) ``` Does anyone have an elegant way to reproduce this pattern in Python? I've seen anonymous function dispatch tables used, but those seem kind of unwieldy to me for a small number of regular expressions...
``` r""" This is an extension of the re module. It stores the last successful match object and lets you access it's methods and attributes via this module. This module exports the following additional functions: expand Return the string obtained by doing backslash substitution on a template string. group Returns one or more subgroups of the match. groups Return a tuple containing all the subgroups of the match. start Return the indices of the start of the substring matched by group. end Return the indices of the end of the substring matched by group. span Returns a 2-tuple of (start(), end()) of the substring matched by group. This module defines the following additional public attributes: pos The value of pos which was passed to the search() or match() method. endpos The value of endpos which was passed to the search() or match() method. lastindex The integer index of the last matched capturing group. lastgroup The name of the last matched capturing group. re The regular expression object which as passed to search() or match(). string The string passed to match() or search(). """ import re as re_ from re import * from functools import wraps __all__ = re_.__all__ + [ "expand", "group", "groups", "start", "end", "span", "last_match", "pos", "endpos", "lastindex", "lastgroup", "re", "string" ] last_match = pos = endpos = lastindex = lastgroup = re = string = None def _set_match(match=None): global last_match, pos, endpos, lastindex, lastgroup, re, string if match is not None: last_match = match pos = match.pos endpos = match.endpos lastindex = match.lastindex lastgroup = match.lastgroup re = match.re string = match.string return match @wraps(re_.match) def match(pattern, string, flags=0): return _set_match(re_.match(pattern, string, flags)) @wraps(re_.search) def search(pattern, string, flags=0): return _set_match(re_.search(pattern, string, flags)) @wraps(re_.findall) def findall(pattern, string, flags=0): matches = re_.findall(pattern, string, flags) if matches: _set_match(matches[-1]) return matches @wraps(re_.finditer) def finditer(pattern, string, flags=0): for match in re_.finditer(pattern, string, flags): yield _set_match(match) def expand(template): if last_match is None: raise TypeError, "No successful match yet." return last_match.expand(template) def group(*indices): if last_match is None: raise TypeError, "No successful match yet." return last_match.group(*indices) def groups(default=None): if last_match is None: raise TypeError, "No successful match yet." return last_match.groups(default) def groupdict(default=None): if last_match is None: raise TypeError, "No successful match yet." return last_match.groupdict(default) def start(group=0): if last_match is None: raise TypeError, "No successful match yet." return last_match.start(group) def end(group=0): if last_match is None: raise TypeError, "No successful match yet." return last_match.end(group) def span(group=0): if last_match is None: raise TypeError, "No successful match yet." return last_match.span(group) del wraps # Not needed past module compilation ``` For example: ``` if gre.match("foo(.+)", var): # do something with gre.group(1) elif gre.match("bar(.+)", var): # do something with gre.group(1) elif gre.match("baz(.+)", var): # do something with gre.group(1) ```
How do I find the location of my Python site-packages directory?
122,327
396
2008-09-23T17:04:43Z
122,340
240
2008-09-23T17:06:59Z
[ "python", "installation" ]
How do I find the location of my site-packages directory?
From ["How to Install Django" documentation](http://docs.djangoproject.com/en/dev/topics/install/#remove-any-old-versions-of-django) (though this is useful to more than just Django installation) - execute the following from the shell: ``` python -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())" ``` Formatted for readability (rather than use as a one-liner), that looks like the following: ``` from distutils.sysconfig import get_python_lib print(get_python_lib()) ```
How do I find the location of my Python site-packages directory?
122,327
396
2008-09-23T17:04:43Z
122,377
19
2008-09-23T17:14:02Z
[ "python", "installation" ]
How do I find the location of my site-packages directory?
As others have noted, `distutils.sysconfig` has the relevant settings: ``` import distutils.sysconfig print distutils.sysconfig.get_python_lib() ``` ...though the default `site.py` does something a bit more crude, paraphrased below: ``` import sys, os print os.sep.join([sys.prefix, 'lib', 'python' + sys.version[:3], 'site-packages']) ``` (it also adds `${sys.prefix}/lib/site-python` and adds both paths for `sys.exec_prefix` as well, should that constant be different). That said, what's the context? You shouldn't be messing with your `site-packages` directly; setuptools/distutils will work for installation, and your program may be running in a virtualenv where your pythonpath is completely user-local, so it shouldn't assume use of the system site-packages directly either.
How do I find the location of my Python site-packages directory?
122,327
396
2008-09-23T17:04:43Z
122,387
7
2008-09-23T17:16:22Z
[ "python", "installation" ]
How do I find the location of my site-packages directory?
An additional note to the `get_python_lib` function mentioned already: on some platforms different directories are used for platform specific modules (eg: modules that require compilation). If you pass `plat_specific=True` to the function you get the site packages for platform specific packages.
How do I find the location of my Python site-packages directory?
122,327
396
2008-09-23T17:04:43Z
1,711,808
11
2009-11-10T22:49:28Z
[ "python", "installation" ]
How do I find the location of my site-packages directory?
A side-note: The proposed solution (distutils.sysconfig.get\_python\_lib()) does not work when there is more than one site-packages directory (as [recommended by this article](http://pythonsimple.noucleus.net/python-install/python-site-packages-what-they-are-and-where-to-put-them)). It will only return the main site-packages directory. Alas, I have no better solution either. Python doesn't seem to keep track of site-packages directories, just the packages within them.
How do I find the location of my Python site-packages directory?
122,327
396
2008-09-23T17:04:43Z
4,611,382
85
2011-01-06T03:08:09Z
[ "python", "installation" ]
How do I find the location of my site-packages directory?
*For Ubuntu*, ``` python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()" ``` ...is not correct. It will point you to `/usr/lib/pythonX.X/dist-packages` This folder only contains packages your operating system has automatically installed for programs to run. *On ubuntu*, the site-packages folder that contains packages installed via setup\_tools\easy\_install\pip will be in `/usr/local/lib/pythonX.X/dist-packages` The second folder is probably the more useful one if the use case is related to installation or reading source code. If you do not use Ubuntu, you are probably safe copy-pasting the first code box into the terminal.
How do I find the location of my Python site-packages directory?
122,327
396
2008-09-23T17:04:43Z
5,095,375
16
2011-02-23T18:32:10Z
[ "python", "installation" ]
How do I find the location of my site-packages directory?
Let's say you have installed the package 'django'. import it and type in dir(django). It will show you, all the functions and attributes with that module. Type in the python interpreter - ``` >>> import django >>> dir(django) ['VERSION', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'get_version'] >>> print django.__path__ ['/Library/Python/2.6/site-packages/django'] ``` You can do the same thing if you have installed mercurial. This is for Snow Leopard. But I think it should work in general as well.
How do I find the location of my Python site-packages directory?
122,327
396
2008-09-23T17:04:43Z
9,155,056
13
2012-02-06T02:40:22Z
[ "python", "installation" ]
How do I find the location of my site-packages directory?
All the answers (or: the same answer repeated over and over) are inadequate. What you want to do is this: ``` from setuptools.command.easy_install import easy_install class easy_install_default(easy_install): """ class easy_install had problems with the fist parameter not being an instance of Distribution, even though it was. This is due to some import-related mess. """ def __init__(self): from distutils.dist import Distribution dist = Distribution() self.distribution = dist self.initialize_options() self._dry_run = None self.verbose = dist.verbose self.force = None self.help = 0 self.finalized = 0 e = easy_install_default() import distutils.errors try: e.finalize_options() except distutils.errors.DistutilsError: pass print e.install_dir ``` The final line shows you the installation dir. Works on Ubuntu, whereas the above ones don't. Don't ask me about windows or other dists, but since it's the exact same dir that easy\_install uses by default, it's probably correct everywhere where easy\_install works (so, everywhere, even macs). Have fun. Note: original code has many swearwords in it.
How do I find the location of my Python site-packages directory?
122,327
396
2008-09-23T17:04:43Z
10,694,208
33
2012-05-22T00:08:55Z
[ "python", "installation" ]
How do I find the location of my site-packages directory?
This is what worked for me: ``` python -m site --user-site ```
How do I find the location of my Python site-packages directory?
122,327
396
2008-09-23T17:04:43Z
12,950,101
404
2012-10-18T08:19:45Z
[ "python", "installation" ]
How do I find the location of my site-packages directory?
``` >>> import site; site.getsitepackages() ['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages'] ``` (or just first item with `site.getsitepackages()[0]`)
How do I find the location of my Python site-packages directory?
122,327
396
2008-09-23T17:04:43Z
18,130,809
8
2013-08-08T16:05:17Z
[ "python", "installation" ]
How do I find the location of my site-packages directory?
The native system packages installed with python installation can be found at : > /usr/lib/python2.7/dist-packages/ by using this small code : ``` from distutils.sysconfig import get_python_lib print get_python_lib() ``` However, the list of packages installed via `pip` can be found at : > /usr/local/bin/ Or one can simply write the following command to list all paths where python packages are. ``` >>> import site; site.getsitepackages() ['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages'] ```
Need to create a layered dict from a flat one
122,763
6
2008-09-23T18:19:25Z
122,785
8
2008-09-23T18:23:31Z
[ "python", "algorithm", "performance" ]
I have a dict, that looks like this: ``` { 'foo': { 'opt1': 1, 'opt2': 2, }, 'foo/bar': { 'opt3': 3, 'opt4': 4, }, 'foo/bar/baz': { 'opt5': 5, 'opt6': 6, } } ``` And I need to get it to look like: ``` { 'foo': { 'opt1': 1, 'opt2': 2, 'bar': { 'opt3': 3, 'opt4': 4, 'baz': { 'opt5': 5, 'opt6': 6, } } } } ``` I should point out that there can and will be multiple top-level keys ('foo' in this case). I could probably throw something together to get what i need, but I was hoping that there is a solution that's more efficient.
Like this: ``` def nest(d): rv = {} for key, value in d.iteritems(): node = rv for part in key.split('/'): node = node.setdefault(part, {}) node.update(value) return rv ```
How do I copy a file in python?
123,198
819
2008-09-23T19:23:48Z
123,212
964
2008-09-23T19:25:35Z
[ "python", "filesystems" ]
How do I copy a file in Python? I couldn't find anything under [`os`](https://docs.python.org/2/library/os.html).
[`shutil`](http://docs.python.org/2/library/shutil.html) has many methods you can use. One of which is: ``` from shutil import copyfile copyfile(src, dst) ``` Copy the contents of the file named `src` to a file named `dst`. The destination location must be writable; otherwise, an `IOError` exception will be raised. If `dst` already exists, it will be replaced. Special files such as character or block devices and pipes cannot be copied with this function. `src` and `dst` are path names given as strings.
How do I copy a file in python?
123,198
819
2008-09-23T19:23:48Z
123,225
9
2008-09-23T19:27:07Z
[ "python", "filesystems" ]
How do I copy a file in Python? I couldn't find anything under [`os`](https://docs.python.org/2/library/os.html).
Look at module **shutil**. It contains function **copyfile**(*src*, *dst*)
How do I copy a file in python?
123,198
819
2008-09-23T19:23:48Z
123,226
25
2008-09-23T19:27:23Z
[ "python", "filesystems" ]
How do I copy a file in Python? I couldn't find anything under [`os`](https://docs.python.org/2/library/os.html).
Use the [shutil module](https://docs.python.org/3/library/shutil.html). ``` copyfile(src, dst) ``` Copy the contents of the file named src to a file named dst. The destination location must be writable; otherwise, an IOError exception will be raised. If dst already exists, it will be replaced. Special files such as character or block devices and pipes cannot be copied with this function. src and dst are path names given as strings. Take a look at [filesys](https://docs.python.org/3/library/filesys.html) for all the file and directory handling functions available in standard Python modules.
How do I copy a file in python?
123,198
819
2008-09-23T19:23:48Z
123,238
281
2008-09-23T19:29:41Z
[ "python", "filesystems" ]
How do I copy a file in Python? I couldn't find anything under [`os`](https://docs.python.org/2/library/os.html).
``` import shutil shutil.copy2('/dir/file.ext', '/new/dir/newname.ext') ``` or ``` shutil.copy2('/dir/file.ext', '/new/dir') ``` `copy2` is also often useful, it preserves the original modification and access info (mtime and atime) in the file metadata.
How do I copy a file in python?
123,198
819
2008-09-23T19:23:48Z
125,810
54
2008-09-24T07:21:12Z
[ "python", "filesystems" ]
How do I copy a file in Python? I couldn't find anything under [`os`](https://docs.python.org/2/library/os.html).
Copying a file is a relatively straightforward operation as shown by the examples below, but you should instead use the [shutil stdlib module](https://docs.python.org/library/shutil.html) for that. ``` def copyfileobj_example(source, dest, buffer_size=1024*1024): """ Copy a file from source to dest. source and dest must be file-like objects, i.e. any object with a read or write method, like for example StringIO. """ while 1: copy_buffer = source.read(buffer_size) if not copy_buffer: break dest.write(copy_buffer) ``` If you want to copy by filename you could do something like this: ``` def copyfile_example(source, dest): # Beware, this example does not handle any edge cases! with open(source, 'rb') as src, open(dest, 'wb') as dst: copyfileobj_example(src, dst) ```
How do I copy a file in python?
123,198
819
2008-09-23T19:23:48Z
5,310,215
20
2011-03-15T10:11:21Z
[ "python", "filesystems" ]
How do I copy a file in Python? I couldn't find anything under [`os`](https://docs.python.org/2/library/os.html).
Directory and File copy example - From Tim Golden's Python Stuff: <http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html> ``` import os import shutil import tempfile filename1 = tempfile.mktemp (".txt") open (filename1, "w").close () filename2 = filename1 + ".copy" print filename1, "=>", filename2 shutil.copy (filename1, filename2) if os.path.isfile (filename2): print "Success" dirname1 = tempfile.mktemp (".dir") os.mkdir (dirname1) dirname2 = dirname1 + ".copy" print dirname1, "=>", dirname2 shutil.copytree (dirname1, dirname2) if os.path.isdir (dirname2): print "Success" ```
How do I copy a file in python?
123,198
819
2008-09-23T19:23:48Z
30,359,308
126
2015-05-20T20:01:48Z
[ "python", "filesystems" ]
How do I copy a file in Python? I couldn't find anything under [`os`](https://docs.python.org/2/library/os.html).
``` ------------------------------------------------------------------------- | Function |Copies Metadata|Copies Permissions|Can Specify Buffer| ------------------------------------------------------------------------- | shutil.copy | No | Yes | No | ------------------------------------------------------------------------- | shutil.copyfile | No | No | No | ------------------------------------------------------------------------- | shutil.copy2 | Yes | Yes | No | ------------------------------------------------------------------------- | shutil.copyfileobj| No | No | Yes | ------------------------------------------------------------------------- ```
Passing apache2 digest authentication information to a wsgi script run by mod_wsgi
123,499
6
2008-09-23T20:05:07Z
123,526
13
2008-09-23T20:08:51Z
[ "python", "apache", "authentication", "mod-wsgi", "wsgi" ]
I've got the directive ``` <VirtualHost *> <Location /> AuthType Digest AuthName "global" AuthDigestDomain / AuthUserFile /root/apache_users <Limit GET> Require valid-user </Limit> </Location> WSGIScriptAlias / /some/script.wsgi WSGIDaemonProcess mywsgi user=someuser group=somegroup processes=2 threads=25 WSGIProcessGroup mywsgi ServerName some.example.org </VirtualHost> ``` I'd like to know in the /some/script.wsgi ``` def application(environ, start_response): start_response('200 OK', [ ('Content-Type', 'text/plain'), ]) return ['Hello'] ``` What user is logged in. How do I do that?
add `WSGIPassAuthorization On`: ``` <VirtualHost *> <Location /> AuthType Digest AuthName "global" AuthDigestDomain / AuthUserFile /root/apache_users <Limit GET> Require valid-user </Limit> </Location> WSGIPassAuthorization On WSGIScriptAlias / /some/script.wsgi WSGIDaemonProcess mywsgi user=someuser group=somegroup processes=2 threads=25 WSGIProcessGroup mywsgi ServerName some.example.org </VirtualHost> ``` Then just read `environ['REMOTE_USER']`: ``` def application(environ, start_response): start_response('200 OK', [ ('Content-Type', 'text/plain'), ]) return ['Hello %s' % environ['REMOTE_USER']] ``` More information at [mod\_wsgi documentation](http://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines#User_Authentication).
How to get/set logical directory path in python
123,958
5
2008-09-23T21:19:37Z
123,985
10
2008-09-23T21:22:43Z
[ "python", "path", "symlink" ]
In python is it possible to get or set a logical directory (as opposed to an absolute one). For example if I have: ``` /real/path/to/dir ``` and I have ``` /linked/path/to/dir ``` linked to the same directory. using os.getcwd and os.chdir will always use the absolute path ``` >>> import os >>> os.chdir('/linked/path/to/dir') >>> print os.getcwd() /real/path/to/dir ``` The only way I have found to get around this at all is to launch 'pwd' in another process and read the output. However, this only works until you call os.chdir for the first time.
The underlying operational system / shell reports real paths to python. So, there really is no way around it, since `os.getcwd()` is a wrapped call to C Library `getcwd()` function. There are some workarounds in the spirit of the one that you already know which is launching `pwd`. Another one would involve using `os.environ['PWD']`. If that environmnent variable is set you can make some `getcwd` function that respects it. The solution below combines both: ``` import os from subprocess import Popen, PIPE class CwdKeeper(object): def __init__(self): self._cwd = os.environ.get("PWD") if self._cwd is None: # no environment. fall back to calling pwd on shell self._cwd = Popen('pwd', stdout=PIPE).communicate()[0].strip() self._os_getcwd = os.getcwd self._os_chdir = os.chdir def chdir(self, path): if not self._cwd: return self._os_chdir(path) p = os.path.normpath(os.path.join(self._cwd, path)) result = self._os_chdir(p) self._cwd = p os.environ["PWD"] = p return result def getcwd(self): if not self._cwd: return self._os_getcwd() return self._cwd cwd = CwdKeeper() print cwd.getcwd() # use only cwd.chdir and cwd.getcwd from now on. # monkeypatch os if you want: os.chdir = cwd.chdir os.getcwd = cwd.getcwd # now you can use os.chdir and os.getcwd as normal. ```
Comparison of Python and Perl solutions to Wide Finder challenge
124,171
8
2008-09-23T21:57:11Z
124,357
10
2008-09-23T22:39:07Z
[ "python", "performance", "perl", "analysis" ]
I'd be very grateful if you could compare the winning [O’Rourke's Perl solution](http://www.cs.ucsd.edu/~sorourke/wf.pl) to [Lundh's Python solution](http://effbot.org/zone/wide-finder.htm), as I don't know Perl good enough to understand what's going on there. More specifically I'd like to know what gave Perl version 3x advantage: algorithmic superiority, quality of C extensions, other factors? [Wide Finder: Results](http://www.tbray.org/ongoing/When/200x/2007/10/30/WF-Results)
The better regex implementation of perl is one part of the story. That can't explain however why the perl implementation scales better. The difference become bigger with more processors. For some reason the python implementation has an issue there.
What is the intended use of the DEFAULT section in config files used by ConfigParser?
124,692
16
2008-09-24T00:16:34Z
124,785
23
2008-09-24T00:49:13Z
[ "python", "parsing", "configuration-files" ]
I've used ConfigParser for quite a while for simple configs. One thing that's bugged me for a long time is the DEFAULT section. I'm not really sure what's an appropriate use. I've read the documentation, but I would really like to see some clever examples of its use and how it affects other sections in the file (something that really illustrates the kind of things that are possible).
I found an explanation [here](http://www.enfoldsystems.com/software/proxy/docs/4.0/configuringmanually.html#the-default-section) by googling for "windows ini" "default section". Summary: whatever you put in the [DEFAULT] section gets propagated to every other section. Using the example from the linked website, let's say I have a config file called test1.ini: ``` [host 1] lh_server=192.168.0.1 vh_hosts = PloneSite1:8080 lh_root = PloneSite1 [host 2] lh_server=192.168.0.1 vh_hosts = PloneSite2:8080 lh_root = PloneSite2 ``` I can read this using ConfigParser: ``` >>> cp = ConfigParser.ConfigParser() >>> cp.read('test1.ini') ['test1.ini'] >>> cp.get('host 1', 'lh_server') '192.168.0.1' ``` But I notice that lh\_server is the same in both sections; and, indeed, I realise that it will be the same for most hosts I might add. So I can do this, as test2.ini: ``` [DEFAULT] lh_server=192.168.0.1 [host 1] vh_root = PloneSite1 lh_root = PloneSite1 [host 2] vh_root = PloneSite2 lh_root = PloneSite2 ``` Despite the sections not having lh\_server keys, I can still access them: ``` >>> cp.read('test2.ini') ['test2.ini'] >>> cp.get('host 1', 'lh_server') '192.168.0.1' ``` Read the linked page for a further example of using variable substitution in the DEFAULT section to simplify the INI file even more.
What is the easiest, most concise way to make selected attributes in an instance be readonly?
125,034
8
2008-09-24T02:15:21Z
125,061
7
2008-09-24T02:22:16Z
[ "python", "attributes", "readonly" ]
In Python, I want to make **selected** instance attributes of a class be readonly to code outside of the class. I want there to be no way outside code can alter the attribute, except indirectly by invoking methods on the instance. I want the syntax to be concise. What is the best way? (I give my current best answer below...)
You should use the `@property` decorator. ``` >>> class a(object): ... def __init__(self, x): ... self.x = x ... @property ... def xval(self): ... return self.x ... >>> b = a(5) >>> b.xval 5 >>> b.xval = 6 Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: can't set attribute ```
extracting text from MS word files in python
125,222
22
2008-09-24T03:15:13Z
125,248
10
2008-09-24T03:23:42Z
[ "python", "linux", "ms-word" ]
for working with MS word files in python, there is python win32 extensions, which can be used in windows. How do I do the same in linux? Is there any library?
OpenOffice.org can be scripted with Python: [see here](http://wiki.services.openoffice.org/wiki/Python). Since OOo can load most MS Word files flawlessly, I'd say that's your best bet.
extracting text from MS word files in python
125,222
22
2008-09-24T03:15:13Z
125,386
17
2008-09-24T04:13:03Z
[ "python", "linux", "ms-word" ]
for working with MS word files in python, there is python win32 extensions, which can be used in windows. How do I do the same in linux? Is there any library?
You could make a subprocess call to [antiword](http://en.wikipedia.org/wiki/Antiword). Antiword is a linux commandline utility for dumping text out of a word doc. Works pretty well for simple documents (obviously it loses formatting). It's available through apt, and probably as RPM, or you could compile it yourself.
extracting text from MS word files in python
125,222
22
2008-09-24T03:15:13Z
1,967,869
9
2009-12-28T03:39:54Z
[ "python", "linux", "ms-word" ]
for working with MS word files in python, there is python win32 extensions, which can be used in windows. How do I do the same in linux? Is there any library?
benjamin's answer is a pretty good one. I have just consolidated... ``` import zipfile, re docx = zipfile.ZipFile('/path/to/file/mydocument.docx') content = docx.read('word/document.xml') cleaned = re.sub('<(.|\n)*?>','',content) print cleaned ```
extracting text from MS word files in python
125,222
22
2008-09-24T03:15:13Z
1,979,906
26
2009-12-30T12:17:09Z
[ "python", "linux", "ms-word" ]
for working with MS word files in python, there is python win32 extensions, which can be used in windows. How do I do the same in linux? Is there any library?
Use the **native Python docx module**. Here's how to extract all the text from a doc: ``` document = docx.Document(filename) docText = '\n\n'.join([ paragraph.text.encode('utf-8') for paragraph in document.paragraphs ]) print docText ``` See [Python DocX site](https://python-docx.readthedocs.org/en/latest/) Also check out [Textract](http://textract.readthedocs.org/en/latest/) which pulls out tables etc. Parsing XML with regexs invokes cthulu. Don't do it!
How do I modify a text file in Python?
125,703
125
2008-09-24T06:30:56Z
125,713
75
2008-09-24T06:35:51Z
[ "python", "file", "text" ]
I'm using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that?
Depends on what you want to do. To append you can open it with "a": ``` with open("foo.txt", "a") as f: f.write("new line\n") ``` If you want to preprend something you have to read from the file first: ``` with open("foo.txt", "r+") as f: old = f.read() # read everything in the file f.seek(0) # rewind f.write("new line\n" + old) # write the new line before ```
How do I modify a text file in Python?
125,703
125
2008-09-24T06:30:56Z
125,759
100
2008-09-24T06:57:21Z
[ "python", "file", "text" ]
I'm using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that?
Unfortunately there is no way to insert into the middle of a file without re-writing it. As previous posters have indicated, you can append to a file or overwrite part of it using seek but if you want to add stuff at the beginning or the middle, you'll have to rewrite it. This is an operating system thing, not a Python thing. It is the same in all languages. What I usually do is read from the file, make the modifications and write it out to a new file called myfile.txt.tmp or something like that. This is better than reading the whole file into memory because the file may be too large for that. Once the temporary file is completed, I rename it the same as the original file. This is a good, safe way to do it because if the file write crashes or aborts for any reason, you still have your untouched original file.
How do I modify a text file in Python?
125,703
125
2008-09-24T06:30:56Z
126,389
28
2008-09-24T10:27:45Z
[ "python", "file", "text" ]
I'm using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that?
Rewriting a file in place is often done by saving the old copy with a modified name. Unix folks add a `~` to mark the old one. Windows folks do all kinds of things -- add .bak or .old -- or rename the file entirely or put the ~ on the front of the name. ``` import shutil shutil.move( afile, afile+"~" ) destination= open( aFile, "w" ) source= open( aFile+"~", "r" ) for line in source: destination.write( line ) if <some condition>: destination.write( >some additional line> + "\n" ) source.close() destination.close() ``` Instead of `shutil`, you can use the following. ``` import os os.rename( aFile, aFile+"~" ) ```
How do I modify a text file in Python?
125,703
125
2008-09-24T06:30:56Z
130,844
13
2008-09-25T00:41:01Z
[ "python", "file", "text" ]
I'm using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that?
Python's mmap module will allow you to insert into a file. The following sample shows how it can be done in Unix (Windows mmap may be different). Note that this does not handle all error conditions and you might corrupt or lose the original file. Also, this won't handle unicode strings. ``` import os from mmap import mmap def insert(filename, str, pos): if len(str) < 1: # nothing to insert return f = open(filename, 'r+') m = mmap(f.fileno(), os.path.getsize(filename)) origSize = m.size() # or this could be an error if pos > origSize: pos = origSize elif pos < 0: pos = 0 m.resize(origSize + len(str)) m[pos+len(str):] = m[pos:origSize] m[pos:pos+len(str)] = str m.close() f.close() ``` It is also possible to do this without mmap with files opened in 'r+' mode, but it is less convenient and less efficient as you'd have to read and temporarily store the contents of the file from the insertion position to EOF - which might be huge.
How do I modify a text file in Python?
125,703
125
2008-09-24T06:30:56Z
1,811,866
43
2009-11-28T07:25:54Z
[ "python", "file", "text" ]
I'm using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that?
The fileinput module of the Python standard library will rewrite a file inplace if you use the inplace=1 parameter: ``` import sys import fileinput # replace all occurrences of 'sit' with 'SIT' and insert a line after the 5th for i, line in enumerate(fileinput.input('lorem_ipsum.txt', inplace=1)): sys.stdout.write(line.replace('sit', 'SIT')) # replace 'sit' and write if i == 4: sys.stdout.write('\n') # write a blank line after the 5th line ```
How do I modify a text file in Python?
125,703
125
2008-09-24T06:30:56Z
13,464,228
7
2012-11-19T23:24:50Z
[ "python", "file", "text" ]
I'm using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that?
As mentioned by Adam you have to take your system limitations into consideration before you can decide on approach whether you have enough memory to read it all into memory replace parts of it and re-write it. If you're dealing with a small file or have no memory issues this might help: **Option 1)** Read entire file into memory, do a regex substitution on the entire or part of the line and replace it with that line plus the extra line. You will need to make sure that the 'middle line' is unique in the file or if you have timestamps on each line this should be pretty reliable. ``` # open file with r+b (allow write and binary mode) f = open("file.log", 'r+b') # read entire content of file into memory f_content = f.read() # basically match middle line and replace it with itself and the extra line f_content = re.sub(r'(middle line)', r'\1\nnew line', f_content) # return pointer to top of file so we can re-write the content with replaced string f.seek(0) # clear file content f.truncate() # re-write the content with the updated content f.write(f_content) # close file f.close() ``` **Option 2)** Figure out middle line, and replace it with that line plus the extra line. ``` # open file with r+b (allow write and binary mode) f = open("file.log" , 'r+b') # get array of lines f_content = f.readlines() # get middle line middle_line = len(f_content)/2 # overwrite middle line f_content[middle_line] += "\nnew line" # return pointer to top of file so we can re-write the content with replaced string f.seek(0) # clear file content f.truncate() # re-write the content with the updated content f.write(''.join(f_content)) # close file f.close() ```
Python library for rendering HTML and javascript
126,131
16
2008-09-24T09:05:57Z
126,250
7
2008-09-24T09:42:52Z
[ "javascript", "python", "html" ]
Is there any python module for rendering a HTML page with javascript and get back a DOM object? I want to parse a page which generates almost all of its content using javascript.
The big complication here is emulating the full browser environment outside of a browser. You can use stand alone javascript interpreters like Rhino and SpiderMonkey to run javascript code but they don't provide a complete browser like environment to full render a web page. If I needed to solve a problem like this I would first look at how the javascript is rendering the page, it's quite possible it's fetching data via AJAX and using that to render the page. I could then use python libraries like simplejson and httplib2 to directly fetch the data and use that, negating the need to access the DOM object. However, that's only one possible situation, I don't know the exact problem you are solving. Other options include the selenium one mentioned by Łukasz, some kind of webkit embedded craziness, some kind of IE win32 scripting craziness or, finally, a pyxpcom based solution (with added craziness). All these have the drawback of requiring pretty much a fully running web browser for python to play with, which might not be an option depending on your environment.