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 |
|---|---|---|---|---|---|---|---|---|---|
Why are Python's 'private' methods not actually private? | 70,528 | 344 | 2008-09-16T08:59:32Z | 80,000 | 11 | 2008-09-17T04:29:45Z | [
"python",
"python-2.7",
"encapsulation",
"information-hiding"
] | Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: `__myPrivateMethod()`. How, then, can one explain this
```
>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMeth... | Similar behavior exists when module attribute names begin with a single underscore (e.g. \_foo).
Module attributes named as such will not be copied into an importing module when using the `from*` method, e.g.:
```
from bar import *
```
However, this is a convention and not a language constraint. These are not privat... |
Why are Python's 'private' methods not actually private? | 70,528 | 344 | 2008-09-16T08:59:32Z | 1,949,874 | 100 | 2009-12-22T23:25:42Z | [
"python",
"python-2.7",
"encapsulation",
"information-hiding"
] | Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: `__myPrivateMethod()`. How, then, can one explain this
```
>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMeth... | When I first came from Java to Python i **hated** this. It scared me to death.
Today it might just be the one thing **I love most** about Python.
I love being on a platform, where people trust each other and don't feel like they need to build impenetrable walls around their code. In strongly encapsulated languages, i... |
Why are Python's 'private' methods not actually private? | 70,528 | 344 | 2008-09-16T08:59:32Z | 3,147,548 | 185 | 2010-06-30T08:24:05Z | [
"python",
"python-2.7",
"encapsulation",
"information-hiding"
] | Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: `__myPrivateMethod()`. How, then, can one explain this
```
>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMeth... | ### Example of private function
```
import re
import inspect
class MyClass :
def __init__(self) :
pass
def private_function ( self ) :
try :
function_call = inspect.stack()[1][4][0].strip()
# See if the function_call has "self." in the begining
matched = ... |
Python Authentication API | 70,653 | 5 | 2008-09-16T09:17:41Z | 80,008 | 9 | 2008-09-17T04:31:02Z | [
"python",
"authentication",
"desktop"
] | I'm looking for a python library that will help me to create an authentication method for a desktop app I'm writing.
I have found several method in web framework such as django or turbogears.
I just want a kind of username-password association stored into a local file.
I can write it by myself, but I'm really it alrea... | dbr said:
> ```
> def hash_password(password):
> """Returns the hashed version of a string
> """
> return hasher.new( str(password) ).hexdigest()
> ```
This is a really insecure way to hash passwords. You *don't* want to do this. If you want to know why read the [Bycrypt Paper](http://www.openbsd.org/pape... |
Python: user input and commandline arguments | 70,797 | 222 | 2008-09-16T09:44:59Z | 70,814 | 296 | 2008-09-16T09:48:16Z | [
"python",
"input",
"command-line-arguments"
] | How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line? | ```
var = raw_input("Please enter something: ")
print "you entered", var
``` |
Python: user input and commandline arguments | 70,797 | 222 | 2008-09-16T09:44:59Z | 70,818 | 22 | 2008-09-16T09:48:40Z | [
"python",
"input",
"command-line-arguments"
] | How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line? | The best way to process command line arguments is the [`argparse` module.](https://docs.python.org/library/argparse.html)
Use `raw_input()` to get user input. If you import the [`readline module`](https://docs.python.org/library/readline.html) your users will have line editing and history. |
Python: user input and commandline arguments | 70,797 | 222 | 2008-09-16T09:44:59Z | 70,833 | 182 | 2008-09-16T09:50:40Z | [
"python",
"input",
"command-line-arguments"
] | How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line? | To read user input you can try [the cmd module](http://docs.python.org/2/library/cmd.html) for easily creating a mini-command line interpreter (with help texts and autocompletion) and [raw\_input](http://docs.python.org/2/library/functions.html#raw_input) for less fancy stuff (just reading a line of text from the user)... |
Python: user input and commandline arguments | 70,797 | 222 | 2008-09-16T09:44:59Z | 70,869 | 10 | 2008-09-16T09:58:33Z | [
"python",
"input",
"command-line-arguments"
] | How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line? | Careful not to use the `input` function, unless you know what you're doing. Unlike `raw_input`, `input` will accept any python expression, so it's kinda like `eval` |
Python: user input and commandline arguments | 70,797 | 222 | 2008-09-16T09:44:59Z | 8,334,188 | 127 | 2011-11-30T22:53:49Z | [
"python",
"input",
"command-line-arguments"
] | How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line? | `raw_input` is no longer available in Python 3.x. But `raw_input` was renamed `input`, so the same functionality exists.
```
input_var = input("Enter something: ")
print ("you entered " + input_var)
```
[Documentation of the change](http://docs.python.org/py3k/whatsnew/3.0.html#builtins) |
HTML parser in Python | 71,151 | 7 | 2008-09-16T10:49:36Z | 71,161 | 12 | 2008-09-16T10:51:40Z | [
"python",
"import"
] | Using the Python Documentation I found the [HTML parser](http://docs.python.org/lib/module-HTMLParser.html) but I have no idea which library to import to use it, how do I find this out (bearing in mind it doesn't say on the page). | Try:
```
import HTMLParser
```
In Python 3.0, the HTMLParser module has been renamed to html.parser
you can check about this [here](http://docs.python.org/library/htmlparser.html)
Python 3.0
```
import html.parser
```
Python 2.2 and above
```
import HTMLParser
``` |
HTML parser in Python | 71,151 | 7 | 2008-09-16T10:49:36Z | 71,174 | 22 | 2008-09-16T10:54:05Z | [
"python",
"import"
] | Using the Python Documentation I found the [HTML parser](http://docs.python.org/lib/module-HTMLParser.html) but I have no idea which library to import to use it, how do I find this out (bearing in mind it doesn't say on the page). | You probably really want [BeautifulSoup](http://stackoverflow.com/questions/55391/python-regular-expression-for-html-parsing-beautifulsoup#55424), check the link for an example.
But in any case
```
>>> import HTMLParser
>>> h = HTMLParser.HTMLParser()
>>> h.feed('<html></html>')
>>> h.get_starttag_text()
'<html>'
>>>... |
Python and "re" | 72,393 | 6 | 2008-09-16T13:47:48Z | 72,470 | 19 | 2008-09-16T13:53:03Z | [
"python",
"regex"
] | A tutorial I have on Regex in python explains how to use the re module in python, I wanted to grab the URL out of an A tag so knowing Regex I wrote the correct expression and tested it in my regex testing app of choice and ensured it worked. When placed into python it failed.
After much head scratching I found out the... | In Python, there's a distinction between "match" and "search"; match only looks for the pattern at the start of the string, and search looks for the pattern starting at any location within the string.
[Python regex docs](http://docs.python.org/lib/module-re.html)
[Matching vs searching](http://docs.python.org/lib/ma... |
Python's unittest logic | 72,422 | 3 | 2008-09-16T13:50:25Z | 72,504 | 11 | 2008-09-16T13:55:02Z | [
"python",
"unit-testing"
] | Can someone explain this result to me. The first test succeeds but the second fails, although the variable tested is changed in the first test.
```
>>> class MyTest(unittest.TestCase):
def setUp(self):
self.i = 1
def testA(self):
self.i = 3
self.assertEqual(self.i, 3)
def testB(self):
s... | From <http://docs.python.org/lib/minimal-example.html> :
> When a setUp() method is defined, the
> test runner will run that method prior
> to each test.
So setUp() gets run before both testA and testB, setting i to 1 each time. Behind the scenes, the entire test object is actually being re-instantiated for each test... |
Python's unittest logic | 72,422 | 3 | 2008-09-16T13:50:25Z | 73,791 | 9 | 2008-09-16T15:47:30Z | [
"python",
"unit-testing"
] | Can someone explain this result to me. The first test succeeds but the second fails, although the variable tested is changed in the first test.
```
>>> class MyTest(unittest.TestCase):
def setUp(self):
self.i = 1
def testA(self):
self.i = 3
self.assertEqual(self.i, 3)
def testB(self):
s... | Each test is run using a new instance of the MyTest class. That means if you change self in one test, changes will not carry over to other tests, since self will refer to a different instance.
Additionally, as others have pointed out, setUp is called before each test. |
How to do relative imports in Python? | 72,852 | 309 | 2008-09-16T14:24:02Z | 73,149 | 189 | 2008-09-16T14:48:56Z | [
"python",
"python-import",
"python-module"
] | Imagine this directory structure:
```
app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
```
I'm coding `mod1`, and I need to import something from `mod2`. How should I do it?
I tried `from ..sub2 import mod2` but I'm getting an "Attempted relative import in non-pac... | Everyone seems to want to tell you what you should be doing rather than just answering the question.
The problem is that you're running the module as '\_\_main\_\_' by passing the mod1.py as an argument to the interpreter.
From [PEP 328](http://www.python.org/dev/peps/pep-0328/):
> Relative imports use a module's \_... |
How to do relative imports in Python? | 72,852 | 309 | 2008-09-16T14:24:02Z | 465,129 | 82 | 2009-01-21T12:42:11Z | [
"python",
"python-import",
"python-module"
] | Imagine this directory structure:
```
app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
```
I'm coding `mod1`, and I need to import something from `mod2`. How should I do it?
I tried `from ..sub2 import mod2` but I'm getting an "Attempted relative import in non-pac... | ```
main.py
setup.py
app/ ->
__init__.py
package_a/ ->
__init__.py
module_a.py
package_b/ ->
__init__.py
module_b.py
```
1. You run `python main.py`.
2. `main.py` does: `import app.package_a.module_a`
3. `module_a.py` does `import app.package_b.module_b`
Alternatively 2 or 3 co... |
How to do relative imports in Python? | 72,852 | 309 | 2008-09-16T14:24:02Z | 1,083,169 | 24 | 2009-07-04T23:27:50Z | [
"python",
"python-import",
"python-module"
] | Imagine this directory structure:
```
app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
```
I'm coding `mod1`, and I need to import something from `mod2`. How should I do it?
I tried `from ..sub2 import mod2` but I'm getting an "Attempted relative import in non-pac... | ```
def import_path(fullpath):
"""
Import a file with full path specification. Allows one to
import from anywhere, something __import__ does not do.
"""
path, filename = os.path.split(fullpath)
filename, ext = os.path.splitext(filename)
sys.path.append(path)
module = __import__(filenam... |
How to do relative imports in Python? | 72,852 | 309 | 2008-09-16T14:24:02Z | 8,195,271 | 26 | 2011-11-19T16:05:29Z | [
"python",
"python-import",
"python-module"
] | Imagine this directory structure:
```
app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
```
I'm coding `mod1`, and I need to import something from `mod2`. How should I do it?
I tried `from ..sub2 import mod2` but I'm getting an "Attempted relative import in non-pac... | "Guido views running scripts within a package as an anti-pattern" (rejected
[PEP-3122](http://www.python.org/dev/peps/pep-3122/))
I have spent so much time trying to find a solution, reading related posts here on Stack Overflow and saying to myself "there must be a better way!". Looks like there is not. |
How to do relative imports in Python? | 72,852 | 309 | 2008-09-16T14:24:02Z | 15,458,607 | 67 | 2013-03-17T07:43:34Z | [
"python",
"python-import",
"python-module"
] | Imagine this directory structure:
```
app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
```
I'm coding `mod1`, and I need to import something from `mod2`. How should I do it?
I tried `from ..sub2 import mod2` but I'm getting an "Attempted relative import in non-pac... | Here is the solution which works for me:
I do the relative imports as `from ..sub2 import mod2`
and then, if I want to run `mod1.py` then I go to the parent directory of `app` and run the module using the python -m switch as `python -m app.sub1.mod1`.
The real reason why this problem occurs with relative imports, is ... |
How to do relative imports in Python? | 72,852 | 309 | 2008-09-16T14:24:02Z | 20,449,492 | 8 | 2013-12-08T03:19:42Z | [
"python",
"python-import",
"python-module"
] | Imagine this directory structure:
```
app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
```
I'm coding `mod1`, and I need to import something from `mod2`. How should I do it?
I tried `from ..sub2 import mod2` but I'm getting an "Attempted relative import in non-pac... | explanation of `nosklo's` answer with examples
*note: all `__init__.py` files are empty.*
```
main.py
app/ ->
__init__.py
package_a/ ->
__init__.py
fun_a.py
package_b/ ->
__init__.py
fun_b.py
```
### app/package\_a/fun\_a.py
```
def print_a():
print 'This is a function in... |
How do I sort a list of dictionaries by values of the dictionary in Python? | 72,899 | 822 | 2008-09-16T14:27:47Z | 72,950 | 7 | 2008-09-16T14:31:52Z | [
"python",
"list",
"sorting",
"dictionary"
] | I got a list of dictionaries and want that to be sorted by a value of that dictionary.
This
```
[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
```
sorted by name, should become
```
[{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]
``` | You have to implement your own comparison function that will compare the dictionaries by values of name keys. See [Sorting Mini-HOW TO from PythonInfo Wiki](http://wiki.python.org/moin/HowTo/Sorting) |
How do I sort a list of dictionaries by values of the dictionary in Python? | 72,899 | 822 | 2008-09-16T14:27:47Z | 73,019 | 7 | 2008-09-16T14:36:54Z | [
"python",
"list",
"sorting",
"dictionary"
] | I got a list of dictionaries and want that to be sorted by a value of that dictionary.
This
```
[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
```
sorted by name, should become
```
[{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]
``` | I guess you've meant:
```
[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
```
This would be sorted like this:
```
sorted(l,cmp=lambda x,y: cmp(x['name'],y['name']))
``` |
How do I sort a list of dictionaries by values of the dictionary in Python? | 72,899 | 822 | 2008-09-16T14:27:47Z | 73,044 | 12 | 2008-09-16T14:39:11Z | [
"python",
"list",
"sorting",
"dictionary"
] | I got a list of dictionaries and want that to be sorted by a value of that dictionary.
This
```
[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
```
sorted by name, should become
```
[{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]
``` | ```
my_list = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
my_list.sort(lambda x,y : cmp(x['name'], y['name']))
```
`my_list` will now be what you want.
**(3 years later) Edited to add:**
The new `key` argument is more efficient and neater. A better answer now looks like:
```
my_list = sorted(my_list, k... |
How do I sort a list of dictionaries by values of the dictionary in Python? | 72,899 | 822 | 2008-09-16T14:27:47Z | 73,050 | 1,147 | 2008-09-16T14:39:44Z | [
"python",
"list",
"sorting",
"dictionary"
] | I got a list of dictionaries and want that to be sorted by a value of that dictionary.
This
```
[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
```
sorted by name, should become
```
[{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]
``` | It may look cleaner using a key instead a cmp:
```
newlist = sorted(list_to_be_sorted, key=lambda k: k['name'])
```
or as J.F.Sebastian and others suggested,
```
from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name'))
```
For completeness (as pointed out in comments by fitzgerald... |
How do I sort a list of dictionaries by values of the dictionary in Python? | 72,899 | 822 | 2008-09-16T14:27:47Z | 73,098 | 13 | 2008-09-16T14:43:51Z | [
"python",
"list",
"sorting",
"dictionary"
] | I got a list of dictionaries and want that to be sorted by a value of that dictionary.
This
```
[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
```
sorted by name, should become
```
[{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]
``` | ```
import operator
a_list_of_dicts.sort(key=operator.itemgetter('name'))
```
'key' is used to sort by an arbitrary value and 'itemgetter' sets that value to each item's 'name' attribute. |
How do I sort a list of dictionaries by values of the dictionary in Python? | 72,899 | 822 | 2008-09-16T14:27:47Z | 73,186 | 8 | 2008-09-16T14:52:14Z | [
"python",
"list",
"sorting",
"dictionary"
] | I got a list of dictionaries and want that to be sorted by a value of that dictionary.
This
```
[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
```
sorted by name, should become
```
[{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]
``` | You could use a custom comparison function, or you could pass in a function that calculates a custom sort key. That's usually more efficient as the key is only calculated once per item, while the comparison function would be called many more times.
You could do it this way:
```
def mykey(adict): return adict['name']
... |
How do I sort a list of dictionaries by values of the dictionary in Python? | 72,899 | 822 | 2008-09-16T14:27:47Z | 73,465 | 68 | 2008-09-16T15:18:14Z | [
"python",
"list",
"sorting",
"dictionary"
] | I got a list of dictionaries and want that to be sorted by a value of that dictionary.
This
```
[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
```
sorted by name, should become
```
[{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]
``` | ```
import operator
```
To sort the list of dictionaries by key='name':
```
list_of_dicts.sort(key=operator.itemgetter('name'))
```
To sort the list of dictionaries by key='age':
```
list_of_dicts.sort(key=operator.itemgetter('age'))
``` |
How do I sort a list of dictionaries by values of the dictionary in Python? | 72,899 | 822 | 2008-09-16T14:27:47Z | 2,858,683 | 24 | 2010-05-18T15:28:11Z | [
"python",
"list",
"sorting",
"dictionary"
] | I got a list of dictionaries and want that to be sorted by a value of that dictionary.
This
```
[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
```
sorted by name, should become
```
[{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]
``` | If you want to sort the list by multiple keys you can do the following:
```
my_list = [{'name':'Homer', 'age':39}, {'name':'Milhouse', 'age':10}, {'name':'Bart', 'age':10} ]
sortedlist = sorted(my_list , key=lambda elem: "%02d %s" % (elem['age'], elem['name']))
```
It is rather hackish, since it relies on converting ... |
How do I sort a list of dictionaries by values of the dictionary in Python? | 72,899 | 822 | 2008-09-16T14:27:47Z | 16,772,049 | 8 | 2013-05-27T11:21:03Z | [
"python",
"list",
"sorting",
"dictionary"
] | I got a list of dictionaries and want that to be sorted by a value of that dictionary.
This
```
[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
```
sorted by name, should become
```
[{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]
``` | Using Schwartzian transform from Perl,
```
py = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
```
do
```
sort_on = "name"
decorated = [(dict_[sort_on], dict_) for dict_ in py]
decorated.sort()
result = [dict_ for (key, dict_) in decorated]
```
gives
```
>>> result
[{'age': 10, 'name': 'Bart'}, {'age': 39... |
How to create a triple-join table with Django | 72,945 | 9 | 2008-09-16T14:31:21Z | 77,898 | 8 | 2008-09-16T22:22:52Z | [
"python",
"django",
"model-view-controller",
"model"
] | Using Django's built in models, how would one create a triple-join between three models.
For example:
* Users, Roles, and Events are the models.
* Users have many Roles, and Roles many Users. (ManyToMany)
* Events have many Users, and Users many Events. (ManyToMany)
* But for any given Event, any User may have only o... | **zacherates** writes:
> I'd model Role as an association class between Users and Roles (...)
I'd also reccomed this solution, but you can also make use of some syntactical sugar provided by Django: [ManyToMany relation with extra fields](http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-... |
Terminating a Python script | 73,663 | 469 | 2008-09-16T15:35:55Z | 73,673 | 644 | 2008-09-16T15:36:36Z | [
"python",
"termination"
] | I am aware of the `die()` command in PHP which stops a script early.
How can I do this in Python? | ```
import sys
sys.exit()
```
details from the [`sys` module documentation](https://docs.python.org/2/library/constants.html#exit):
> `sys.exit([arg])`
>
> > Exit from Python. This is implemented by raising the
> > [`SystemExit`](https://docs.python.org/2/library/exceptions.html#SystemExit) exception, so cleanup acti... |
Terminating a Python script | 73,663 | 469 | 2008-09-16T15:35:55Z | 73,680 | 72 | 2008-09-16T15:37:13Z | [
"python",
"termination"
] | I am aware of the `die()` command in PHP which stops a script early.
How can I do this in Python? | Another way is:
```
raise SystemExit
``` |
Terminating a Python script | 73,663 | 469 | 2008-09-16T15:35:55Z | 73,695 | 16 | 2008-09-16T15:38:28Z | [
"python",
"termination"
] | I am aware of the `die()` command in PHP which stops a script early.
How can I do this in Python? | ```
from sys import exit
exit()
```
As a parameter you can pass an exit code, which will be returned to OS. Default is 0. |
Terminating a Python script | 73,663 | 469 | 2008-09-16T15:35:55Z | 76,374 | 48 | 2008-09-16T20:08:04Z | [
"python",
"termination"
] | I am aware of the `die()` command in PHP which stops a script early.
How can I do this in Python? | While you should generally prefer `sys.exit` because it is more "friendly" to other code, all it actually does is raise an exception.
If you are sure that you need to exit a process immediately, and you might be inside of some exception handler which would catch `SystemExit`, there is another function - `os._exit` - w... |
Terminating a Python script | 73,663 | 469 | 2008-09-16T15:35:55Z | 14,836,329 | 89 | 2013-02-12T15:50:06Z | [
"python",
"termination"
] | I am aware of the `die()` command in PHP which stops a script early.
How can I do this in Python? | A simple way to terminate a Python script early is to use the built-in function quit(). There is no need to import any library, and it is efficient and simple.
Example:
```
#do stuff
if this == that:
quit()
``` |
Terminating a Python script | 73,663 | 469 | 2008-09-16T15:35:55Z | 16,150,238 | 30 | 2013-04-22T14:57:00Z | [
"python",
"termination"
] | I am aware of the `die()` command in PHP which stops a script early.
How can I do this in Python? | You can also use simply `exit()`.
Keep in mind that `sys.exit()`, `exit()`, `quit()`, and `os._exit(0)` **kill** the Python interpreter. Therefore, if it appears in a script called from another script by `execfile()`, it stops execution of both scripts.
See "[Stop execution of a script called with execfile](http://st... |
Terminating a Python script | 73,663 | 469 | 2008-09-16T15:35:55Z | 22,504,027 | 8 | 2014-03-19T11:13:22Z | [
"python",
"termination"
] | I am aware of the `die()` command in PHP which stops a script early.
How can I do this in Python? | I'm a total novice but surely this is cleaner and more controlled
```
def main():
try:
Answer = 1/0
print Answer
except:
print 'Program terminated'
return
print 'You wont see this'
if __name__ == '__main__':
main()
```
...
> Program terminated
than
```
import sys
... |
Sending mail via sendmail from python | 73,781 | 47 | 2008-09-16T15:46:43Z | 73,844 | 24 | 2008-09-16T15:51:40Z | [
"python",
"email",
"sendmail"
] | If I want to send mail not via SMTP, but rather via sendmail, is there a library for python that encapsulates this process?
Better yet, is there a good library that abstracts the whole 'sendmail -versus- smtp' choice?
I'll be running this script on a bunch of unix hosts, only some of which are listening on localhost:... | This is a simple python function that uses the unix sendmail to deliver a mail.
```
def sendMail():
sendmail_location = "/usr/sbin/sendmail" # sendmail location
p = os.popen("%s -t" % sendmail_location, "w")
p.write("From: %s\n" % "[email protected]")
p.write("To: %s\n" % "[email protected]")
p... |
Sending mail via sendmail from python | 73,781 | 47 | 2008-09-16T15:46:43Z | 74,084 | 79 | 2008-09-16T16:12:37Z | [
"python",
"email",
"sendmail"
] | If I want to send mail not via SMTP, but rather via sendmail, is there a library for python that encapsulates this process?
Better yet, is there a good library that abstracts the whole 'sendmail -versus- smtp' choice?
I'll be running this script on a bunch of unix hosts, only some of which are listening on localhost:... | Header injection isn't a factor in how you send the mail, it's a factor in how you construct the mail. Check the [email](https://docs.python.org/2/library/email.html) package, construct the mail with that, serialise it, and send it to `/usr/sbin/sendmail` using the [subprocess](https://docs.python.org/2/library/subproc... |
Is there a common way to check in Python if an object is any function type? | 74,092 | 6 | 2008-09-16T16:13:09Z | 75,507 | 13 | 2008-09-16T18:34:03Z | [
"python",
"types"
] | I have a function in Python which is iterating over the attributes returned from dir(obj), and I want to check to see if any of the objects contained within is a function, method, built-in function, etc. Normally you could use callable() for this, but I don't want to include classes. The best I've come up with so far i... | The inspect module has exactly what you want:
```
inspect.isroutine( obj )
```
FYI, the code is:
```
def isroutine(object):
"""Return true if the object is any kind of function or method."""
return (isbuiltin(object)
or isfunction(object)
or ismethod(object)
or ismethoddes... |
Random in python 2.5 not working? | 74,430 | 8 | 2008-09-16T16:49:33Z | 75,427 | 34 | 2008-09-16T18:26:02Z | [
"python"
] | I am trying to use the `import random` statement in python, but it doesn't appear to have any methods in it to use.
Am I missing something? | You probably have a file named random.py or random.pyc in your working directory. That's shadowing the built-in random module. You need to rename random.py to something like my\_random.py and/or remove the random.pyc file.
To tell for sure what's going on, do this:
```
>>> import random
>>> print random.__file__
```
... |
How do I get the name of a python class as a string? | 75,440 | 30 | 2008-09-16T18:26:47Z | 75,456 | 28 | 2008-09-16T18:27:58Z | [
"python"
] | What method do I call to get the name of a class? | It's not a method, it's a field. The field is called `__name__`. `class.__name__` will give the name of the class as a string. `object.__class__.__name__` will give the name of the class of an object. |
How do I get the name of a python class as a string? | 75,440 | 30 | 2008-09-16T18:26:47Z | 75,467 | 33 | 2008-09-16T18:28:51Z | [
"python"
] | What method do I call to get the name of a class? | ```
In [1]: class test(object):
...: pass
...:
In [2]: test.__name__
Out[2]: 'test'
``` |
Django -vs- Grails -vs-? | 75,798 | 16 | 2008-09-16T19:05:48Z | 77,693 | 9 | 2008-09-16T22:02:55Z | [
"python",
"django",
"frameworks"
] | I'm wondering if there's such a thing as Django-like ease of web app development combined with good deployment, debugging and other tools?
Django is a very productive framework for building content-heavy sites; the best I've tried and a breath of fresh air compared to some of the Java monstrosities out there. However ... | > However it's written in Python which
> means there's little real support in
> the way of deployment/packaging,
> debugging, profilers and other tools
> that make building and maintaining
> applications much easier.
Python has:
1. a [great interactive debugger](http://docs.python.org/lib/module-pdb.html), which make... |
Django -vs- Grails -vs-? | 75,798 | 16 | 2008-09-16T19:05:48Z | 460,360 | 9 | 2009-01-20T07:32:41Z | [
"python",
"django",
"frameworks"
] | I'm wondering if there's such a thing as Django-like ease of web app development combined with good deployment, debugging and other tools?
Django is a very productive framework for building content-heavy sites; the best I've tried and a breath of fresh air compared to some of the Java monstrosities out there. However ... | Grails.
Grails just looks like Rails (Ruby),but it uses groovy which is simpler than java. It uses java technology and you can use any java lib without any trouble.
I also choose Grails over simplicity and there are lots of java lib (such as jasper report, jawr etc) and I am glad that now they join with SpringSource ... |
Django -vs- Grails -vs-? | 75,798 | 16 | 2008-09-16T19:05:48Z | 1,955,727 | 26 | 2009-12-23T22:42:54Z | [
"python",
"django",
"frameworks"
] | I'm wondering if there's such a thing as Django-like ease of web app development combined with good deployment, debugging and other tools?
Django is a very productive framework for building content-heavy sites; the best I've tried and a breath of fresh air compared to some of the Java monstrosities out there. However ... | You asked for someone who used both Grails and Django. I've done work on both for big projects. Here's my Thoughts:
**IDE's:**
Django works really well in Eclipse, Grails works really well in IntelliJ Idea.
**Debugging:**
Practically the same (assuming you use IntelliJ for Grails, and Eclipse for Python). Step debugg... |
Django -vs- Grails -vs-? | 75,798 | 16 | 2008-09-16T19:05:48Z | 1,997,668 | 7 | 2010-01-04T05:37:55Z | [
"python",
"django",
"frameworks"
] | I'm wondering if there's such a thing as Django-like ease of web app development combined with good deployment, debugging and other tools?
Django is a very productive framework for building content-heavy sites; the best I've tried and a breath of fresh air compared to some of the Java monstrosities out there. However ... | The statement that *grails deletes the database on start-up* is completely wrong. It's behavior on start-up is completely configurable and easy to configure. I generally use create-drop when running an app in dev mode. I use update when I run in test and production.
I also love the bootstrap processing that lets me pr... |
Best way to access table instances when using SQLAlchemy's declarative syntax | 75,829 | 5 | 2008-09-16T19:08:29Z | 156,968 | 7 | 2008-10-01T10:14:09Z | [
"python",
"sql",
"sqlalchemy"
] | All the docs for SQLAlchemy give `INSERT` and `UPDATE` examples using the local table instance (e.g. `tablename.update()`... )
Doing this seems difficult with the declarative syntax, I need to reference `Base.metadata.tables["tablename"]` to get the table reference.
Am I supposed to do this another way? Is there a di... | well it works for me:
```
class Users(Base):
__tablename__ = 'users'
__table_args__ = {'autoload':True}
users = Users()
print users.__table__.select()
```
...SELECT users....... |
Which is faster, python webpages or php webpages? | 77,086 | 27 | 2008-09-16T21:05:26Z | 77,297 | 27 | 2008-09-16T21:24:46Z | [
"php",
"python",
"performance",
"pylons"
] | Does anyone know how the speed of pylons(or any of the other frameworks) compares to a similar website made with php?
I know that serving a python base webpage via cgi is slower than php because of its long start up every time.
I enjoy using pylons and I would still use it if it was slower than php. But if pylons was ... | There's no point in attempting to convince your employer to port from PHP to Python, especially not for an existing system, which is what I think you implied in your question.
The reason for this is that you already have a (presumably) working system, with an existing investment of time and effort (and experience). To... |
Which is faster, python webpages or php webpages? | 77,086 | 27 | 2008-09-16T21:05:26Z | 79,744 | 81 | 2008-09-17T03:44:12Z | [
"php",
"python",
"performance",
"pylons"
] | Does anyone know how the speed of pylons(or any of the other frameworks) compares to a similar website made with php?
I know that serving a python base webpage via cgi is slower than php because of its long start up every time.
I enjoy using pylons and I would still use it if it was slower than php. But if pylons was ... | It sounds like you don't want to compare the two **languages**, but that you want to compare two **web systems**.
This is tricky, because there are many variables involved.
For example, Python web applications can take advantage of [mod\_wsgi](http://code.google.com/p/modwsgi/) to talk to web servers, which is faster... |
'id' is a bad variable name in Python | 77,552 | 73 | 2008-09-16T21:50:58Z | 77,612 | 87 | 2008-09-16T21:55:59Z | [
"python"
] | Why is it bad to name a variable `id` in Python? | `id()` is a fundamental built-in:
> Help on built-in function `id` in module
> `__builtin__`:
>
> ```
> id(...)
>
> id(object) -> integer
>
> Return the identity of an object. This is guaranteed to be unique among
> simultaneously existing objects. (Hint: it's the object's memory
> address.)
> ```
I... |
'id' is a bad variable name in Python | 77,552 | 73 | 2008-09-16T21:50:58Z | 77,925 | 30 | 2008-09-16T22:27:26Z | [
"python"
] | Why is it bad to name a variable `id` in Python? | I might say something unpopular here: `id()` is a rather specialized built-in function that is rarely used in business logic. Therefore I don't see a problem in using it as a variable name in a tight and well-written function, where it's clear that id doesn't mean the built-in function. |
'id' is a bad variable name in Python | 77,552 | 73 | 2008-09-16T21:50:58Z | 79,198 | 38 | 2008-09-17T02:13:34Z | [
"python"
] | Why is it bad to name a variable `id` in Python? | `id` is a built-in function that gives the memory address of an object. If you name one of your functions `id`, you will have to say `__builtins__.id` to get the original. Renaming `id` globally is confusing in anything but a small script.
However, reusing built-in names as variables isn't all that bad as long as the ... |
'id' is a bad variable name in Python | 77,552 | 73 | 2008-09-16T21:50:58Z | 28,091,085 | 17 | 2015-01-22T14:24:12Z | [
"python"
] | Why is it bad to name a variable `id` in Python? | In **PEP 8 - Style Guide for Python Code**, the following guidance appears in the section [Descriptive: Naming Styles](https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles) :
> * `single_trailing_underscore_` : used by convention to avoid conflicts
> with Python keyword, e.g.
>
> `Tkinter.Toplevel(m... |
iBATIS for Python? | 77,731 | 4 | 2008-09-16T22:05:58Z | 78,147 | 10 | 2008-09-16T22:53:33Z | [
"python",
"orm",
"ibatis"
] | At my current gig, we use iBATIS through Java to CRUD our databases. I like the abstract qualities of the tool, especially when working with legacy databases, as it doesn't impose its own syntax on you.
**I'm looking for a Python analogue to this library**, since the website only has Java/.NET/Ruby versions available.... | iBatis sequesters the SQL DML (or the definitions of the SQL) in an XML file. It specifically focuses on the mapping between the SQL and some object model defined elsewhere.
SQL Alchemy can do this -- but it isn't really a very complete solution. Like iBatis, you can merely have SQL table definitions and a mapping bet... |
What's the best way to calculate a 3D (or n-D) centroid? | 77,936 | 10 | 2008-09-16T22:28:58Z | 77,978 | 12 | 2008-09-16T22:33:06Z | [
"python",
"math",
"3d",
"geometry"
] | As part of a project at work I have to calculate the centroid of a set of points in 3D space. Right now I'm doing it in a way that seems simple but naive -- by taking the average of each set of points, as in:
```
centroid = average(x), average(y), average(z)
```
where `x`, `y` and `z` are arrays of floating-point num... | Nope, that is the only formula for the centroid of a collection of points. See Wikipedia: <http://en.wikipedia.org/wiki/Centroid> |
What's the best way to calculate a 3D (or n-D) centroid? | 77,936 | 10 | 2008-09-16T22:28:58Z | 88,394 | 10 | 2008-09-17T22:35:44Z | [
"python",
"math",
"3d",
"geometry"
] | As part of a project at work I have to calculate the centroid of a set of points in 3D space. Right now I'm doing it in a way that seems simple but naive -- by taking the average of each set of points, as in:
```
centroid = average(x), average(y), average(z)
```
where `x`, `y` and `z` are arrays of floating-point num... | You vaguely mention "a way to get a more accurate centroid". Maybe you're talking about a centroid that isn't affected by outliers. For example, the *average* household income in the USA is probably very high, because a small number of *very* rich people skew the average; they are the "outliers". For that reason, stati... |
Redirect command to input of another in Python | 78,431 | 5 | 2008-09-16T23:46:47Z | 78,482 | 8 | 2008-09-16T23:57:32Z | [
"python",
"bash",
"redirect",
"diff",
"vimdiff"
] | I would like to replicate this in python:
```
gvimdiff <(hg cat file.txt) file.txt
```
(hg cat file.txt outputs the most recently committed version of file.txt)
I know how to pipe the file to gvimdiff, but it won't accept another file:
```
$ hg cat file.txt | gvimdiff file.txt -
Too many edit arguments: "-"
```
Ge... | It can be done. As of Python 2.5, however, this mechanism is Linux-specific and not portable:
```
import subprocess
import sys
file = sys.argv[1]
p1 = subprocess.Popen(['hg', 'cat', file], stdout=subprocess.PIPE)
p2 = subprocess.Popen([
'gvimdiff',
'/proc/self/fd/%s' % p1.stdout.fileno(),
file])
p2.wait()... |
Is there a benefit to defining a class inside another class in Python? | 78,799 | 54 | 2008-09-17T01:02:31Z | 78,858 | 72 | 2008-09-17T01:12:59Z | [
"python",
"oop"
] | What I'm talking about here are nested classes. Essentially, I have two classes that I'm modeling. A DownloadManager class and a DownloadThread class. The obvious OOP concept here is composition. However, composition doesn't necessarily mean nesting, right?
I have code that looks something like this:
```
class Downlo... | You might want to do this when the "inner" class is a one-off, which will never be used outside the *definition* of the outer class. For example to use a metaclass, it's sometimes handy to do
```
class Foo(object):
class __metaclass__(type):
....
```
instead of defining a metaclass separately, if you're o... |
Is there a benefit to defining a class inside another class in Python? | 78,799 | 54 | 2008-09-17T01:02:31Z | 78,868 | 14 | 2008-09-17T01:14:33Z | [
"python",
"oop"
] | What I'm talking about here are nested classes. Essentially, I have two classes that I'm modeling. A DownloadManager class and a DownloadThread class. The obvious OOP concept here is composition. However, composition doesn't necessarily mean nesting, right?
I have code that looks something like this:
```
class Downlo... | I don't know Python, but your question seems very general. Ignore me if it's specific to Python.
Class nesting is all about scope. If you think that one class will only make sense in the context of another one, then the former is probably a good candidate to become a nested class.
It is a common pattern make helper c... |
Testing GUI code: should I use a mocking library? | 79,454 | 5 | 2008-09-17T02:52:58Z | 80,028 | 7 | 2008-09-17T04:33:46Z | [
"python",
"unit-testing",
"user-interface",
"tdd"
] | Recently I've been experimenting with TDD while developing a GUI application in Python. I find it very reassuring to have tests that verify the functionality of my code, but it's been tricky to follow some of the recommened practices of TDD. Namely, writing tests first has been hard. And I'm finding it difficult to mak... | **If you are writing your tests after you've written your code and making them pass, you are not doing TDD** (nor are you getting any benefits of Test-First or Test-Driven development.. check out SO questions for definitive books on TDD)
> One of the things I've noticed with
> using mocker is that it's easier to
> wri... |
Unittest causing sys.exit() | 79,754 | 11 | 2008-09-17T03:46:55Z | 79,826 | 10 | 2008-09-17T03:58:24Z | [
"python",
"unit-testing"
] | No matter what I do sys.exit() is called by unittest, even the most trivial examples. I can't tell if my install is messed up or what is going on.
```
IDLE 1.2.2 ==== No Subprocess ====
>>> import unittest
>>>
>>> class Test(unittest.TestCase):
def testA(self):
a = 1
self.assertEqual(a,... | Don't try to run `unittest.main()` from IDLE. It's trying to access `sys.argv`, and it's getting the args that IDLE was started with. Either run your tests in a different way from IDLE, or call `unittest.main()` in its own Python process. |
Unittest causing sys.exit() | 79,754 | 11 | 2008-09-17T03:46:55Z | 79,833 | 10 | 2008-09-17T03:59:27Z | [
"python",
"unit-testing"
] | No matter what I do sys.exit() is called by unittest, even the most trivial examples. I can't tell if my install is messed up or what is going on.
```
IDLE 1.2.2 ==== No Subprocess ====
>>> import unittest
>>>
>>> class Test(unittest.TestCase):
def testA(self):
a = 1
self.assertEqual(a,... | Your example is exiting on my install too. I can make it execute the tests and stay within Python by changing
```
unittest.main()
```
to
```
unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromTestCase(Test))
```
More information is available [here](http://docs.python.org/library/unittest.html#basic-ex... |
Unittest causing sys.exit() | 79,754 | 11 | 2008-09-17T03:46:55Z | 3,215,505 | 17 | 2010-07-09T18:30:28Z | [
"python",
"unit-testing"
] | No matter what I do sys.exit() is called by unittest, even the most trivial examples. I can't tell if my install is messed up or what is going on.
```
IDLE 1.2.2 ==== No Subprocess ====
>>> import unittest
>>>
>>> class Test(unittest.TestCase):
def testA(self):
a = 1
self.assertEqual(a,... | In new Python 2.7 release, [unittest.main()](http://docs.python.org/library/unittest.html#unittest.main) has a new argument.
If 'exit' is set to `False`, `sys.exit()` is not called during the execution of `unittest.main()`. |
How do I convert local time to UTC in Python? | 79,797 | 147 | 2008-09-17T03:52:42Z | 79,808 | 20 | 2008-09-17T03:54:39Z | [
"python",
"datetime",
"utc"
] | How do I convert a datetime *string in local time* to a *string in UTC time*?
I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.
**Clarification**: For example, if I have `2008-09-17 14:02:00` in my local timezone (`+10`), I'd like to generate a string with... | ```
def local_to_utc(t):
secs = time.mktime(t)
return time.gmtime(secs)
def utc_to_local(t):
secs = calendar.timegm(t)
return time.localtime(secs)
```
Source: <http://feihonghsu.blogspot.com/2008/02/converting-from-local-time-to-utc.html>
Example usage from [bd808](http://stackoverflow.com/users/8171... |
How do I convert local time to UTC in Python? | 79,797 | 147 | 2008-09-17T03:52:42Z | 79,877 | 137 | 2008-09-17T04:07:28Z | [
"python",
"datetime",
"utc"
] | How do I convert a datetime *string in local time* to a *string in UTC time*?
I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.
**Clarification**: For example, if I have `2008-09-17 14:02:00` in my local timezone (`+10`), I'd like to generate a string with... | First, parse the string into a naive datetime object. This is an instance of `datetime.datetime` with no attached timezone information. See documentation for `datetime.strptime` for information on parsing the date string.
Use the [`pytz`](http://pytz.sourceforge.net/) module, which comes with a full list of time zones... |
How do I convert local time to UTC in Python? | 79,797 | 147 | 2008-09-17T03:52:42Z | 79,913 | 51 | 2008-09-17T04:15:39Z | [
"python",
"datetime",
"utc"
] | How do I convert a datetime *string in local time* to a *string in UTC time*?
I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.
**Clarification**: For example, if I have `2008-09-17 14:02:00` in my local timezone (`+10`), I'd like to generate a string with... | Thanks @rofly, the full conversion from string to string is as follows:
```
time.strftime("%Y-%m-%d %H:%M:%S",
time.gmtime(time.mktime(time.strptime("2008-09-17 14:04:00",
"%Y-%m-%d %H:%M:%S"))))
```
My summary of the `time`/`calendar` functions:
`t... |
How do I convert local time to UTC in Python? | 79,797 | 147 | 2008-09-17T03:52:42Z | 2,175,170 | 60 | 2010-02-01T07:00:27Z | [
"python",
"datetime",
"utc"
] | How do I convert a datetime *string in local time* to a *string in UTC time*?
I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.
**Clarification**: For example, if I have `2008-09-17 14:02:00` in my local timezone (`+10`), I'd like to generate a string with... | The datetime module's [utcnow()](http://docs.python.org/library/datetime.html#datetime.datetime.utcnow) function can be used to obtain the current UTC time.
```
>>> import datetime
>>> utc_datetime = datetime.datetime.utcnow()
>>> utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
'2010-02-01 06:59:19'
```
As the link mentio... |
How do I convert local time to UTC in Python? | 79,797 | 147 | 2008-09-17T03:52:42Z | 8,563,126 | 11 | 2011-12-19T14:58:01Z | [
"python",
"datetime",
"utc"
] | How do I convert a datetime *string in local time* to a *string in UTC time*?
I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.
**Clarification**: For example, if I have `2008-09-17 14:02:00` in my local timezone (`+10`), I'd like to generate a string with... | I'm having good luck with [dateutil](http://labix.org/python-dateutil) (which is widely recommended on SO for other related questions):
```
from datetime import *
from dateutil import *
from dateutil.tz import *
# METHOD 1: Hardcode zones:
utc_zone = tz.gettz('UTC')
local_zone = tz.gettz('America/Chicago')
# METHOD 2... |
How do I convert local time to UTC in Python? | 79,797 | 147 | 2008-09-17T03:52:42Z | 10,040,725 | 14 | 2012-04-06T07:54:41Z | [
"python",
"datetime",
"utc"
] | How do I convert a datetime *string in local time* to a *string in UTC time*?
I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.
**Clarification**: For example, if I have `2008-09-17 14:02:00` in my local timezone (`+10`), I'd like to generate a string with... | One more example with pytz, but includes localize(), which saved my day.
```
import pytz, datetime
utc = pytz.utc
fmt = '%Y-%m-%d %H:%M:%S'
amsterdam = pytz.timezone('Europe/Amsterdam')
dt = datetime.datetime.strptime("2012-04-06 10:00:00", fmt)
am_dt = amsterdam.localize(dt)
print am_dt.astimezone(utc).strftime(fmt)... |
How do I convert local time to UTC in Python? | 79,797 | 147 | 2008-09-17T03:52:42Z | 13,084,428 | 9 | 2012-10-26T09:38:42Z | [
"python",
"datetime",
"utc"
] | How do I convert a datetime *string in local time* to a *string in UTC time*?
I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.
**Clarification**: For example, if I have `2008-09-17 14:02:00` in my local timezone (`+10`), I'd like to generate a string with... | Here's a summary of common Python time conversions
* struct\_time (UTC) â POSIX:
`calendar.timegm(struct_time)`
* Naïve datetime (local) â POSIX:
`calendar.timegm(stz.localize(dt, is_dst=None).utctimetuple())`
* Naïve datetime (UTC) â POSIX:
`calendar.timegm(dt.utctimetuple())`
* Aware datetime â... |
How do you design data models for Bigtable/Datastore (GAE)? | 79,850 | 17 | 2008-09-17T04:02:53Z | 80,425 | 18 | 2008-09-17T06:02:38Z | [
"python",
"database",
"google-app-engine",
"bigtable"
] | Since the Google App Engine Datastore is based on [Bigtable](http://research.google.com/archive/bigtable.html) and we know that's not a relational database, how do you design a ***database schema*/\*data model\*** for applications that use this type of database system? | Designing a bigtable schema is an open process, and basically requires you to think about:
* The access patterns you will be using and how often each will be used
* The relationships between your types
* What indices you are going to need
* The write patterns you will be using (in order to effectively spread load)
GA... |
Split a string by spaces -- preserving quoted substrings -- in Python | 79,968 | 163 | 2008-09-17T04:25:15Z | 79,985 | 253 | 2008-09-17T04:27:32Z | [
"python",
"regex"
] | I have a string which is like this:
```
this is "a test"
```
I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:
```
['this','is','a test']
```
PS. I know you are going to ask "what happens if there are quotes within the quotes, well, i... | You want split, from the [shlex](https://docs.python.org/2/library/shlex.html) module.
```
>>> import shlex
>>> shlex.split('this is "a test"')
['this', 'is', 'a test']
```
This should do exactly what you want. |
Split a string by spaces -- preserving quoted substrings -- in Python | 79,968 | 163 | 2008-09-17T04:25:15Z | 79,989 | 45 | 2008-09-17T04:27:59Z | [
"python",
"regex"
] | I have a string which is like this:
```
this is "a test"
```
I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:
```
['this','is','a test']
```
PS. I know you are going to ask "what happens if there are quotes within the quotes, well, i... | Have a look at the `shlex` module, particularly `shlex.split`.
> `>>> import shlex`
>
> `>>> shlex.split('This is "a test"')`
>
> `['This', 'is', 'a test']` |
Split a string by spaces -- preserving quoted substrings -- in Python | 79,968 | 163 | 2008-09-17T04:25:15Z | 80,449 | 8 | 2008-09-17T06:08:38Z | [
"python",
"regex"
] | I have a string which is like this:
```
this is "a test"
```
I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:
```
['this','is','a test']
```
PS. I know you are going to ask "what happens if there are quotes within the quotes, well, i... | Since this question is tagged with regex, I decided to try a regex approach. I first replace all the spaces in the quotes parts with \x00, then split by spaces, then replace the \x00 back to spaces in each part.
Both versions do the same thing, but splitter is a bit more readable then splitter2.
```
import re
s = 't... |
Split a string by spaces -- preserving quoted substrings -- in Python | 79,968 | 163 | 2008-09-17T04:25:15Z | 524,796 | 26 | 2009-02-07T23:17:26Z | [
"python",
"regex"
] | I have a string which is like this:
```
this is "a test"
```
I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:
```
['this','is','a test']
```
PS. I know you are going to ask "what happens if there are quotes within the quotes, well, i... | I see regex approaches here that look complex and/or wrong. This surprises me, because regex syntax can easily describe "whitespace or thing-surrounded-by-quotes", and most regex engines (including Python's) can split on a regex. So if you're going to use regexes, why not just say exactly what you mean?:
```
test = 't... |
Split a string by spaces -- preserving quoted substrings -- in Python | 79,968 | 163 | 2008-09-17T04:25:15Z | 525,011 | 17 | 2009-02-08T02:18:46Z | [
"python",
"regex"
] | I have a string which is like this:
```
this is "a test"
```
I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:
```
['this','is','a test']
```
PS. I know you are going to ask "what happens if there are quotes within the quotes, well, i... | Depending on your use case, you may also want to check out the csv module:
```
import csv
lines = ['this is "a string"', 'and more "stuff"']
for row in csv.reader(lines, delimiter=" "):
print row
```
Output:
```
['this', 'is', 'a string']
['and', 'more', 'stuff']
``` |
Asychronous Programming in Python Twisted | 80,617 | 29 | 2008-09-17T06:51:35Z | 81,456 | 63 | 2008-09-17T09:29:45Z | [
"python",
"asynchronous",
"twisted"
] | I'm having trouble developing a reverse proxy in Twisted. It works, but it seems overly complex and convoluted. So much of it feels like voodoo...
Are there any *simple, solid* examples of asynchronous program structure on the web or in books? A sort of best practices guide? When I complete my program I'd like to be a... | Twisted contains a [large number of examples](http://twistedmatrix.com/projects/core/documentation/howto/index.html). One in particular, the ["evolution of Finger" tutorial](http://twistedmatrix.com/projects/core/documentation/howto/tutorial/intro.html), contains a thorough explanation of how an asynchronous program gr... |
Upload files in Google App Engine | 81,451 | 73 | 2008-09-17T09:28:53Z | 143,798 | 10 | 2008-09-27T15:20:58Z | [
"python",
"google-app-engine"
] | I am planning to create a web app that allows users to downgrade their visual studio project files. However, It seems Google App Engine accepts files uploading and flat file storing on the Google Server through `db.TextProperty` and `db.BlobProperty`.
I'll be glad anyone can provide code sample (both the client and th... | There is a thread in Google Groups about it:
[Uploading Files](http://groups.google.com/group/google-appengine/browse_thread/thread/f9d0f22d8de8c025/bba32165e308dd13?lnk=gst&q=uploading+files#bba32165e308dd13)
With a lot of useful code, that discussion helped me very much in uploading files. |
Upload files in Google App Engine | 81,451 | 73 | 2008-09-17T09:28:53Z | 173,918 | 48 | 2008-10-06T11:15:22Z | [
"python",
"google-app-engine"
] | I am planning to create a web app that allows users to downgrade their visual studio project files. However, It seems Google App Engine accepts files uploading and flat file storing on the Google Server through `db.TextProperty` and `db.BlobProperty`.
I'll be glad anyone can provide code sample (both the client and th... | In fact, this question is answered in the App Egnine documentation. See an example on [Uploading User Images](http://code.google.com/appengine/docs/images/usingimages.html#Uploading).
HTML code, inside <form></form>:
```
<input type="file" name="img"/>
```
Python code:
```
class Guestbook(webapp.RequestHandler):
... |
Upload files in Google App Engine | 81,451 | 73 | 2008-09-17T09:28:53Z | 4,787,543 | 39 | 2011-01-24T21:46:46Z | [
"python",
"google-app-engine"
] | I am planning to create a web app that allows users to downgrade their visual studio project files. However, It seems Google App Engine accepts files uploading and flat file storing on the Google Server through `db.TextProperty` and `db.BlobProperty`.
I'll be glad anyone can provide code sample (both the client and th... | Here is a complete, working file. I pulled the original from the Google site and modified it to make it slightly more real world.
A few things to notice:
1. This code uses the [BlobStore API](http://code.google.com/appengine/docs/python/blobstore/)
2. The purpose of this line in the
ServeHandler class is to "fix" ... |
Is there any list of blog engines, written in Django? | 82,653 | 17 | 2008-09-17T12:37:48Z | 82,739 | 20 | 2008-09-17T12:45:14Z | [
"python",
"django"
] | Is there any list of blog engines, written in Django? | EDIT: Original link went dead so here's an updated link with extracts of the list sorted with the most recently updated source at the top.
[Eleven Django blog engines you should know](http://blog.montylounge.com/2010/02/10/eleven-django-blog-engines-you-should-know/)
by Monty Lounge Industries
> * [Biblion](http://g... |
How do I check whether a file exists using Python? | 82,831 | 2,729 | 2008-09-17T12:55:00Z | 82,836 | 211 | 2008-09-17T12:55:48Z | [
"python",
"file",
"filesystems"
] | How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement? | ```
import os.path
if os.path.isfile(filename):
``` |
How do I check whether a file exists using Python? | 82,831 | 2,729 | 2008-09-17T12:55:00Z | 82,841 | 85 | 2008-09-17T12:56:22Z | [
"python",
"file",
"filesystems"
] | How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement? | ```
import os
os.path.exists(filename)
``` |
How do I check whether a file exists using Python? | 82,831 | 2,729 | 2008-09-17T12:55:00Z | 82,846 | 964 | 2008-09-17T12:57:08Z | [
"python",
"file",
"filesystems"
] | How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement? | You have the [`os.path.exists`](https://docs.python.org/2/library/os.path.html#os.path.exists) function:
```
import os.path
os.path.exists(file_path)
```
This returns `True` for both files and directories but you can additionally use `os.path.isfile` to test if it's a file specifically. |
How do I check whether a file exists using Python? | 82,831 | 2,729 | 2008-09-17T12:55:00Z | 82,852 | 2,356 | 2008-09-17T12:57:51Z | [
"python",
"file",
"filesystems"
] | How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement? | You can also use [`os.path.isfile`](https://docs.python.org/2/library/os.path.html#os.path.isfile)
> Return `True` if path is an existing regular file. This follows symbolic links, so both [islink()](https://docs.python.org/2/library/os.path.html#os.path.islink) and [isfile()](https://docs.python.org/2/library/os.path... |
How do I check whether a file exists using Python? | 82,831 | 2,729 | 2008-09-17T12:55:00Z | 83,012 | 18 | 2008-09-17T13:13:31Z | [
"python",
"file",
"filesystems"
] | How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement? | Additionally, `os.access()`:
```
if os.access("myfile", os.R_OK):
with open("myfile") as fp:
return fp.read()
```
Being `R_OK`, `W_OK`, and `X_OK` the flags to test for permissions ([doc](https://docs.python.org/3/library/os.html#os.access)). |
How do I check whether a file exists using Python? | 82,831 | 2,729 | 2008-09-17T12:55:00Z | 84,173 | 640 | 2008-09-17T15:01:14Z | [
"python",
"file",
"filesystems"
] | How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement? | Unlike [`isfile()`](http://docs.python.org/3.3/library/os.path.html?highlight=os.path#os.path.isfile), [`exists()`](http://docs.python.org/3.3/library/os.path.html?highlight=os.path#os.path.exists) will yield *True* for directories.
So depending on if you want only plain files or also directories, you'll use `isfile(... |
How do I check whether a file exists using Python? | 82,831 | 2,729 | 2008-09-17T12:55:00Z | 1,671,095 | 87 | 2009-11-04T00:48:06Z | [
"python",
"file",
"filesystems"
] | How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement? | Prefer the try statement. It's considered better style and avoids race conditions.
Don't take my word for it. There's plenty of support for this theory. Here's a couple:
* Style: Section "Handling unusual conditions" of <http://allendowney.com/sd/notes/notes11.txt>
* [Avoiding Race Conditions](https://developer.apple... |
How do I check whether a file exists using Python? | 82,831 | 2,729 | 2008-09-17T12:55:00Z | 4,247,590 | 16 | 2010-11-22T16:19:19Z | [
"python",
"file",
"filesystems"
] | How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement? | Just to add to the confusion, it seems that the try: open() approach suggested above doesn't work in Python, as file access isn't exclusive, not even when writing to files, c.f. [What is the best way to open a file for exclusive access in Python?](http://stackoverflow.com/questions/186202/what-is-the-best-way-to-open-a... |
How do I check whether a file exists using Python? | 82,831 | 2,729 | 2008-09-17T12:55:00Z | 4,799,818 | 33 | 2011-01-25T23:00:01Z | [
"python",
"file",
"filesystems"
] | How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement? | You could try this: (safer)
```
try:
# http://effbot.org/zone/python-with-statement.htm
# with is more safe to open file
with open('whatever.txt') as fh:
# do something with fh
except IOError as e:
print("({})".format(e))
```
the ouput would be:
> ([Errno 2] No such file or directory:
> 'wha... |
How do I check whether a file exists using Python? | 82,831 | 2,729 | 2008-09-17T12:55:00Z | 8,876,254 | 156 | 2012-01-16T05:57:12Z | [
"python",
"file",
"filesystems"
] | How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement? | Use [`os.path.isfile()`](https://docs.python.org/3.3/library/os.path.html?highlight=os.path#os.path.isfile) with [`os.access()`](https://docs.python.org/3.3/library/os.html?highlight=os.access#os.access):
```
import os
import os.path
PATH='./file.txt'
if os.path.isfile(PATH) and os.access(PATH, os.R_OK):
print "... |
How do I check whether a file exists using Python? | 82,831 | 2,729 | 2008-09-17T12:55:00Z | 17,344,732 | 78 | 2013-06-27T13:38:04Z | [
"python",
"file",
"filesystems"
] | How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement? | This is the simplest way to check if a file exists. Just **because** the file existed when you checked doesn't **guarantee** that it will be there when you need to open it.
```
import os
fname = "foo.txt"
if os.path.isfile(fname):
print "file does exist at this time"
else:
print "no such file"
``` |
How do I check whether a file exists using Python? | 82,831 | 2,729 | 2008-09-17T12:55:00Z | 18,994,918 | 44 | 2013-09-25T01:52:46Z | [
"python",
"file",
"filesystems"
] | How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement? | It doesn't seem like there's a meaningful functional difference between try/except and `isfile()`, so you should use which one makes sense.
If you want to read a file, if it exists, do
```
try:
f = open(filepath)
except IOError:
print 'Oh dear.'
```
But if you just wanted to rename a file if it exists, and t... |
How do I check whether a file exists using Python? | 82,831 | 2,729 | 2008-09-17T12:55:00Z | 21,641,213 | 65 | 2014-02-08T02:38:42Z | [
"python",
"file",
"filesystems"
] | How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement? | **Python 3.4** has an object-oriented path module: [**pathlib**](http://docs.python.org/3.4/library/pathlib.html). Using this new module, you can check whether a file exists like this:
```
import pathlib
p = pathlib.Path('path/to/file')
if p.is_file(): # or p.is_dir() to see if it is a directory
# do stuff
```
Y... |
How do I check whether a file exists using Python? | 82,831 | 2,729 | 2008-09-17T12:55:00Z | 21,688,350 | 9 | 2014-02-10T21:30:20Z | [
"python",
"file",
"filesystems"
] | How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement? | You can write Brian's suggestion without the `try:`.
```
from contextlib import suppress
with suppress(IOError), open('filename'):
process()
```
`supress` is part of Python 3.4. In older releases you can quickly write your own supress:
```
from contextlib import contextmanager
@contextmanager
def suppress(*ex... |
How do I check whether a file exists using Python? | 82,831 | 2,729 | 2008-09-17T12:55:00Z | 23,826,292 | 7 | 2014-05-23T10:01:20Z | [
"python",
"file",
"filesystems"
] | How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement? | You can use following open method to check if file exists + readable
```
open(inputFile, 'r')
``` |
How do I check whether a file exists using Python? | 82,831 | 2,729 | 2008-09-17T12:55:00Z | 26,433,646 | 7 | 2014-10-17T21:25:30Z | [
"python",
"file",
"filesystems"
] | How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement? | To check if a file exists,
```
from sys import argv
from os.path import exists
script, filename = argv
target = open(filename)
print "file exists: %r" % exists(filename)
``` |
How do I check whether a file exists using Python? | 82,831 | 2,729 | 2008-09-17T12:55:00Z | 27,581,592 | 7 | 2014-12-20T15:21:40Z | [
"python",
"file",
"filesystems"
] | How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement? | You can use the "OS" library of python.
```
>>> import os
>>> os.path.exists("C:\\Users\\####\\Desktop\\test.txt")
True
>>> os.path.exists("C:\\Users\\####\\Desktop\\test.tx")
False
``` |
How do I check whether a file exists using Python? | 82,831 | 2,729 | 2008-09-17T12:55:00Z | 27,661,444 | 25 | 2014-12-26T20:05:32Z | [
"python",
"file",
"filesystems"
] | How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement? | Although I always recommend using `try` and `except` statements, here's a few possibilities for you (My personal favourite is using `os.access`:
1. Try opening the file:
Opening the file will always verify the existence of the file. You can make a function just like so:
```
def File_Existence(filepath):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.