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
How do I calculate number of days betwen two dates using Python?
151,199
193
2008-09-29T23:36:25Z
151,214
15
2008-09-29T23:43:01Z
[ "python", "date" ]
If I have two dates (ex. `'8/18/2008'` and `'9/26/2008'`) what is the best way to get the difference measured in days?
Days until Christmas: ``` >>> import datetime >>> today = datetime.date.today() >>> someday = datetime.date(2008, 12, 25) >>> diff = someday - today >>> diff.days 86 ``` More arithmetic [here](https://web.archive.org/web/20061007015511/http://www.daniweb.com/code/snippet236.html).
Get other running processes window sizes in Python
151,846
7
2008-09-30T05:20:27Z
152,454
11
2008-09-30T10:02:38Z
[ "python", "windows", "winapi", "pywin32" ]
This isn't as malicious as it sounds, I want to get the current size of their windows, not look at what is in them. The purpose is to figure out that if every other window is fullscreen then I should start up like that too. Or if all the other processes are only 800x600 despite there being a huge resolution then that i...
Using hints from [WindowMover article](http://www.devx.com/opensource/Article/37773/1954) and [Nattee Niparnan's blog post](http://our.obor.us/?q=node/42) I managed to create this: ``` import win32con import win32gui def isRealWindow(hWnd): '''Return True iff given window is a real Windows application window.''' ...
Get other running processes window sizes in Python
151,846
7
2008-09-30T05:20:27Z
155,587
8
2008-09-30T23:30:58Z
[ "python", "windows", "winapi", "pywin32" ]
This isn't as malicious as it sounds, I want to get the current size of their windows, not look at what is in them. The purpose is to figure out that if every other window is fullscreen then I should start up like that too. Or if all the other processes are only 800x600 despite there being a huge resolution then that i...
I'm a big fan of [AutoIt](http://www.autoitscript.com/autoit3/). They have a COM version which allows you to use most of their functions from Python. ``` import win32com.client oAutoItX = win32com.client.Dispatch( "AutoItX3.Control" ) oAutoItX.Opt("WinTitleMatchMode", 2) #Match text anywhere in a window title width ...
Errors with Python's mechanize module
151,929
6
2008-09-30T06:03:47Z
155,127
8
2008-09-30T21:15:47Z
[ "python", "exception", "urllib2", "mechanize" ]
I'm using the `mechanize` module to execute some web queries from Python. I want my program to be error-resilient and handle all kinds of errors (wrong URLs, 403/404 responsese) gracefully. However, I can't find in mechanize's documentation the errors / exceptions it throws for various errors. I just call it with: ``...
``` $ perl -0777 -ne'print qq($1) if /__all__ = \[(.*?)\]/s' __init__.py | grep Error 'BrowserStateError', 'ContentTooShortError', 'FormNotFoundError', 'GopherError', 'HTTPDefaultErrorHandler', 'HTTPError', 'HTTPErrorProcessor', 'LinkNotFoundError', 'LoadError', 'ParseError', 'RobotExclusionError', 'URLError', ``` O...
Is it OK to inspect properties beginning with underscore?
152,068
3
2008-09-30T07:24:25Z
152,083
8
2008-09-30T07:29:36Z
[ "python", "sqlalchemy", "pylons" ]
I've been working on a very simple crud generator for pylons. I came up with something that inspects ``` SomeClass._sa_class_manager.mapper.c ``` Is it ok to inspect this (or to call methods begining with underscore)? I always kind of assumed this is legal though frowned upon as it relies heavily on the internal stru...
It is intentional (in Python) that there are no "private" scopes. It is a convention that anything that starts with an underscore should not ideally be used, and hence you may not complain if its behavior or definition changes in a next version.
Is it OK to inspect properties beginning with underscore?
152,068
3
2008-09-30T07:24:25Z
152,111
8
2008-09-30T07:40:11Z
[ "python", "sqlalchemy", "pylons" ]
I've been working on a very simple crud generator for pylons. I came up with something that inspects ``` SomeClass._sa_class_manager.mapper.c ``` Is it ok to inspect this (or to call methods begining with underscore)? I always kind of assumed this is legal though frowned upon as it relies heavily on the internal stru...
In general, this usually indicates that the method is effectively internal, rather than part of the documented interface, and should not be relied on. Future versions of the library are free to rename or remove such methods, so if you care about future compatability without having to rewrite, avoid doing it.
What's the canonical way to check for type in python?
152,580
588
2008-09-30T11:00:10Z
152,583
11
2008-09-30T11:01:28Z
[ "python", "types" ]
What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type? Let's say I have an object `o`. How do I check whether it's a `str`?
``` isinstance(o, str) ``` [Link](http://docs.python.org/lib/built-in-funcs.html)
What's the canonical way to check for type in python?
152,580
588
2008-09-30T11:00:10Z
152,592
22
2008-09-30T11:05:51Z
[ "python", "types" ]
What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type? Let's say I have an object `o`. How do I check whether it's a `str`?
`isinstance(o, str)` will return `true` if `o` is an `str` or is of a type that inherits from `str`. `type(o) == str` will return `true` if and only if `o` is a str. It will return `false` if `o` is of a type that inherits from `str`.
What's the canonical way to check for type in python?
152,580
588
2008-09-30T11:00:10Z
152,596
734
2008-09-30T11:07:45Z
[ "python", "types" ]
What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type? Let's say I have an object `o`. How do I check whether it's a `str`?
To check if the type of `o` is exactly `str`: ``` type(o) is str ``` To check if `o` is an instance of `str` or any subclass of `str` (this would be the "canonical" way): ``` isinstance(o, str) ``` The following also works, and can be useful in some cases: ``` issubclass(type(o), str) type(o) in ([str] + str.__sub...
What's the canonical way to check for type in python?
152,580
588
2008-09-30T11:00:10Z
154,156
105
2008-09-30T17:40:18Z
[ "python", "types" ]
What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type? Let's say I have an object `o`. How do I check whether it's a `str`?
The **most** Pythonic way to check the type of an object is... not to check it. Since Python encourages [Duck Typing](http://wikipedia.org/wiki/Duck_typing), you should just try to use the object's methods the way you want to use them. So if your function is looking for a writable file object, *don't* check that it's ...
What's the canonical way to check for type in python?
152,580
588
2008-09-30T11:00:10Z
14,532,188
8
2013-01-25T23:54:51Z
[ "python", "types" ]
What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type? Let's say I have an object `o`. How do I check whether it's a `str`?
Here is an example why duck typing is evil without knowing when it is dangerous. For instance: Here is the Python code (possibly omitting proper indenting), note that this situation is avoidable by taking care of isinstance and issubclassof functions to make sure that when you really need a duck, you don't get a bomb. ...
How to iterate over a timespan after days, hours, weeks and months in Python?
153,584
40
2008-09-30T15:35:22Z
153,667
33
2008-09-30T15:50:06Z
[ "python", "datetime" ]
How do I iterate over a timespan after days, hours, weeks or months? Something like: ``` for date in foo(from_date, to_date, delta=HOURS): print date ``` Where foo is a function, returning an iterator. I've been looking at the calendar module, but that only works for one specific year or month, not between dates...
I don't think there is a method in Python library, but you can easily create one yourself using [datetime](http://docs.python.org/lib/module-datetime.html) module: ``` from datetime import date, datetime, timedelta def datespan(startDate, endDate, delta=timedelta(days=1)): currentDate = startDate while curren...
How to iterate over a timespan after days, hours, weeks and months in Python?
153,584
40
2008-09-30T15:35:22Z
155,172
61
2008-09-30T21:30:00Z
[ "python", "datetime" ]
How do I iterate over a timespan after days, hours, weeks or months? Something like: ``` for date in foo(from_date, to_date, delta=HOURS): print date ``` Where foo is a function, returning an iterator. I've been looking at the calendar module, but that only works for one specific year or month, not between dates...
Use [dateutil](http://labix.org/python-dateutil) and its rrule implementation, like so: ``` from dateutil import rrule from datetime import datetime, timedelta now = datetime.now() hundredDaysLater = now + timedelta(days=100) for dt in rrule.rrule(rrule.MONTHLY, dtstart=now, until=hundredDaysLater): print dt ```...
How to avoid .pyc files?
154,443
204
2008-09-30T18:55:59Z
154,566
9
2008-09-30T19:27:08Z
[ "python", "compiler-construction", "interpreter" ]
Can I run the python interpreter without generating the compiled .pyc files?
In 2.5, theres no way to suppress it, other than measures like not giving users write access to the directory. In python 2.6 and 3.0 however, there may be a setting in the sys module called "dont\_write\_bytecode" that can be set to suppress this. This can also be set by passing the "-B" option, or setting the environ...
How to avoid .pyc files?
154,443
204
2008-09-30T18:55:59Z
154,617
221
2008-09-30T19:38:02Z
[ "python", "compiler-construction", "interpreter" ]
Can I run the python interpreter without generating the compiled .pyc files?
From ["What’s New in Python 2.6 - Interpreter Changes"](http://docs.python.org/dev/whatsnew/2.6.html#interpreter-changes): > Python can now be prevented from > writing .pyc or .pyo files by > supplying the [-B](http://docs.python.org/using/cmdline.html#cmdoption-B) switch to the Python > interpreter, or by setting t...
How to avoid .pyc files?
154,443
204
2008-09-30T18:55:59Z
154,640
20
2008-09-30T19:44:04Z
[ "python", "compiler-construction", "interpreter" ]
Can I run the python interpreter without generating the compiled .pyc files?
There actually IS a way to do it in Python 2.3+, but it's a bit esoteric. I don't know if you realize this, but you can do the following: ``` $ unzip -l /tmp/example.zip Archive: /tmp/example.zip Length Date Time Name -------- ---- ---- ---- 8467 11-26-02 22:30 jwzthreading.py -------- ...
How to avoid .pyc files?
154,443
204
2008-09-30T18:55:59Z
9,562,273
72
2012-03-05T05:59:47Z
[ "python", "compiler-construction", "interpreter" ]
Can I run the python interpreter without generating the compiled .pyc files?
``` import sys sys.dont_write_bytecode = True ```
Is timsort general-purpose or Python-specific?
154,504
29
2008-09-30T19:12:46Z
154,812
22
2008-09-30T20:14:57Z
[ "python", "algorithm", "sorting" ]
> Timsort is an adaptive, stable, > natural mergesort. It has supernatural > performance on many kinds of partially > ordered arrays (less than lg(N!) > comparisons needed, and as few as > N-1), yet as fast as Python's previous > highly tuned samplesort hybrid on > random arrays. Have you seen [timsort](http://svn.pyt...
The algorithm is pretty generic, but the benefits are rather Python-specific. Unlike most sorting routines, what Python's list.sort (which is what uses timsort) cares about is avoiding unnecessary comparisons, because generally comparisons are a *lot* more expensive than swapping items (which is always just a set of po...
Is timsort general-purpose or Python-specific?
154,504
29
2008-09-30T19:12:46Z
1,060,238
27
2009-06-29T20:09:52Z
[ "python", "algorithm", "sorting" ]
> Timsort is an adaptive, stable, > natural mergesort. It has supernatural > performance on many kinds of partially > ordered arrays (less than lg(N!) > comparisons needed, and as few as > N-1), yet as fast as Python's previous > highly tuned samplesort hybrid on > random arrays. Have you seen [timsort](http://svn.pyt...
Yes, it makes quite a bit of sense to use timsort outside of CPython, in specific, or Python, in general. There is currently an [effort underway](http://bugs.sun.com/bugdatabase/view%5Fbug.do?bug%5Fid=6804124) to replace Java's "modified merge sort" with timsort, and the initial results are quite positive.
Python module for wiki markup
154,592
26
2008-09-30T19:32:59Z
154,790
19
2008-09-30T20:11:43Z
[ "python", "wiki", "markup" ]
Is there a `Python` module for converting `wiki markup` to other languages (e.g. `HTML`)? A similar question was asked here, [What's the easiest way to convert wiki markup to html](http://stackoverflow.com/questions/45991/whats-the-easiest-way-to-convert-wiki-markup-to-html), but no `Python` modules are mentioned. Ju...
[mwlib](https://github.com/pediapress/mwlib) provides ways of converting MediaWiki formatted text into HTML, PDF, DocBook and OpenOffice formats.
Python module for wiki markup
154,592
26
2008-09-30T19:32:59Z
154,972
7
2008-09-30T20:38:04Z
[ "python", "wiki", "markup" ]
Is there a `Python` module for converting `wiki markup` to other languages (e.g. `HTML`)? A similar question was asked here, [What's the easiest way to convert wiki markup to html](http://stackoverflow.com/questions/45991/whats-the-easiest-way-to-convert-wiki-markup-to-html), but no `Python` modules are mentioned. Ju...
You should look at a good parser for [Creole](http://wikicreole.org/) syntax: [creole.py](http://wiki.sheep.art.pl/Wiki%20Creole%20Parser%20in%20Python). It can convert Creole (which is "a common wiki markup language to be used across different wikis") to HTML.
Python module for wiki markup
154,592
26
2008-09-30T19:32:59Z
155,184
11
2008-09-30T21:31:36Z
[ "python", "wiki", "markup" ]
Is there a `Python` module for converting `wiki markup` to other languages (e.g. `HTML`)? A similar question was asked here, [What's the easiest way to convert wiki markup to html](http://stackoverflow.com/questions/45991/whats-the-easiest-way-to-convert-wiki-markup-to-html), but no `Python` modules are mentioned. Ju...
Django uses the following libraries for markup: * [Markdown](http://www.freewisdom.org/projects/python-markdown/) * [Textile](http://pypi.python.org/pypi/textile) * [reStructuredText](http://docutils.sourceforge.net/rst.html) You can see [how they're used in Django](http://code.djangoproject.com/browser/django/trunk/...
Python Dependency Injection Framework
156,230
41
2008-10-01T04:25:33Z
156,553
12
2008-10-01T07:20:48Z
[ "python", "dependency-injection" ]
Is there a framework equivalent to Guice (<http://code.google.com/p/google-guice>) for Python?
I haven't used it, but the [Spring Python](http://springpython.webfactional.com/) framework is based on Spring and implements [Inversion of Control](http://static.springsource.org/spring-python/1.2.x/sphinx/html/objects.html). There also appears to be a Guice in Python project: [snake-guice](http://code.google.com/p/s...
Python Dependency Injection Framework
156,230
41
2008-10-01T04:25:33Z
204,482
24
2008-10-15T12:16:03Z
[ "python", "dependency-injection" ]
Is there a framework equivalent to Guice (<http://code.google.com/p/google-guice>) for Python?
[Spring Python](http://springpython.webfactional.com) is an offshoot of the Java-based Spring Framework and Spring Security, targeted for Python. This project currently contains the following features: * [Inversion Of Control (dependency injection)](http://martinfowler.com/articles/injection.html) - use either classic...
Python Dependency Injection Framework
156,230
41
2008-10-01T04:25:33Z
275,184
9
2008-11-08T20:50:17Z
[ "python", "dependency-injection" ]
Is there a framework equivalent to Guice (<http://code.google.com/p/google-guice>) for Python?
As an alternative to monkeypatching, I like DI. A nascent project such as <http://code.google.com/p/snake-guice/> may fit the bill. Or see the blog post [Dependency Injection in Python](http://web.archive.org/web/20090628142546/http://planet.open4free.org/tag/dependency%20injection/) by Dennis Kempin (Aug '08).
Python Dependency Injection Framework
156,230
41
2008-10-01T04:25:33Z
12,971,813
12
2012-10-19T09:59:39Z
[ "python", "dependency-injection" ]
Is there a framework equivalent to Guice (<http://code.google.com/p/google-guice>) for Python?
I like this simple and neat framework. <http://pypi.python.org/pypi/injector/> > Dependency injection as a formal pattern is less useful in Python than > in other languages, primarily due to its support for keyword > arguments, the ease with which objects can be mocked, and its dynamic > nature. > > That said, a fram...
Get timer ticks in Python
156,330
40
2008-10-01T05:24:38Z
156,335
29
2008-10-01T05:27:03Z
[ "python", "timer" ]
I'm just trying to time a piece of code. The pseudocode looks like: ``` start = get_ticks() do_long_code() print "It took " + (get_ticks() - start) + " seconds." ``` How does this look in Python? More specifically, how do I get the number of ticks since midnight (or however Python organizes that timing)?
What you need is `time()` function from `time` module: ``` import time start = time.time() do_long_code() print "it took", time.time() - start, "seconds." ``` You can use [timeit](http://docs.python.org/lib/module-timeit.html) module for more options though.
Get timer ticks in Python
156,330
40
2008-10-01T05:24:38Z
157,423
31
2008-10-01T12:49:11Z
[ "python", "timer" ]
I'm just trying to time a piece of code. The pseudocode looks like: ``` start = get_ticks() do_long_code() print "It took " + (get_ticks() - start) + " seconds." ``` How does this look in Python? More specifically, how do I get the number of ticks since midnight (or however Python organizes that timing)?
In the `time` module, there are two timing functions: `time` and `clock`. `time` gives you "wall" time, if this is what you care about. However, the python [docs](http://docs.python.org/lib/module-time.html) say that `clock` should be used for benchmarking. Note that `clock` behaves different in separate systems: * o...
Get all items from thread Queue
156,360
9
2008-10-01T05:40:06Z
156,564
11
2008-10-01T07:25:30Z
[ "python", "multithreading", "queue" ]
I have one thread that writes results into a Queue. In another thread (GUI), I periodically (in the IDLE event) check if there are results in the queue, like this: ``` def queue_get_all(q): items = [] while 1: try: items.append(q.get_nowait()) except Empty, e: break ...
If you're always pulling all available items off the queue, is there any real point in using a queue, rather than just a list with a lock? ie: ``` from __future__ import with_statement import threading class ItemStore(object): def __init__(self): self.lock = threading.Lock() self.items = [] d...
Customized command line parsing in Python
156,873
7
2008-10-01T09:35:36Z
156,949
10
2008-10-01T10:09:19Z
[ "python", "parsing", "shell", "command-line", "arguments" ]
I'm writing a shell for a project of mine, which by design parses commands that looks like this: COMMAND\_NAME ARG1="Long Value" ARG2=123 ARG3=me@me.com My problem is that Python's command line parsing libraries (getopt and optparse) forces me to use '-' or '--' in front of the arguments. This behavior doesn't match ...
You could split them up with shlex.split(), which can handle the quoted values you have, and pretty easily parse this with a very simple regular expression. Or, you can just use regular expressions for both splitting and parsing. Or simply use split(). ``` args = {} for arg in shlex.split(cmdln_args): key, value =...
Customized command line parsing in Python
156,873
7
2008-10-01T09:35:36Z
157,100
9
2008-10-01T10:57:17Z
[ "python", "parsing", "shell", "command-line", "arguments" ]
I'm writing a shell for a project of mine, which by design parses commands that looks like this: COMMAND\_NAME ARG1="Long Value" ARG2=123 ARG3=me@me.com My problem is that Python's command line parsing libraries (getopt and optparse) forces me to use '-' or '--' in front of the arguments. This behavior doesn't match ...
1. Try to follow "[Standards for Command Line Interfaces](http://www.gnu.org/prep/standards/standards.html#Command_002dLine-Interfaces)" 2. Convert your arguments (as Thomas suggested) to OptionParser format. ``` parser.parse_args(["--"+p if "=" in p else p for p in sys.argv[1:]]) ``` If command-line argumen...
Emacs and Python
157,018
34
2008-10-01T10:29:22Z
157,074
20
2008-10-01T10:47:59Z
[ "python", "emacs" ]
I recently started learning [Emacs](http://www.gnu.org/software/emacs/). I went through the tutorial, read some introductory articles, so far so good. Now I want to use it for Python development. From what I understand, there are two separate Python modes for Emacs: python-mode.el, which is part of the Python project;...
If you are using GNU Emacs 21 or before, or XEmacs, use python-mode.el. The GNU Emacs 22 python.el won't work on them. On GNU Emacs 22, python.el does work, and ties in better with GNU Emacs's own symbol parsing and completion, ElDoc, etc. I use XEmacs myself, so I don't use it, and I have heard people complain that it...
Emacs and Python
157,018
34
2008-10-01T10:29:22Z
158,868
8
2008-10-01T17:52:18Z
[ "python", "emacs" ]
I recently started learning [Emacs](http://www.gnu.org/software/emacs/). I went through the tutorial, read some introductory articles, so far so good. Now I want to use it for Python development. From what I understand, there are two separate Python modes for Emacs: python-mode.el, which is part of the Python project;...
[This site](http://www.rwdev.eu/articles/emacspyeng) has a description of how to get Python code completion in Emacs. [Ropemacs](http://rope.sourceforge.net/ropemacs.html) is a way to get Rope to work in emacs. I haven't had extensive experience with either, but they're worth looking into.
Emacs and Python
157,018
34
2008-10-01T10:29:22Z
4,569,972
7
2010-12-31T12:00:22Z
[ "python", "emacs" ]
I recently started learning [Emacs](http://www.gnu.org/software/emacs/). I went through the tutorial, read some introductory articles, so far so good. Now I want to use it for Python development. From what I understand, there are two separate Python modes for Emacs: python-mode.el, which is part of the Python project;...
Given the number of times I have several open buffers all called `__init__.py`, I consider the [uniquify](http://www.emacswiki.org/emacs/uniquify) library essential for python development. Pyflakes also aids productivity.
Most pythonic way of counting matching elements in something iterable
157,039
13
2008-10-01T10:37:20Z
157,141
14
2008-10-01T11:09:14Z
[ "python", "list-comprehension" ]
I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three. My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the [split loop](http://www....
Having to iterate over the list multiple times isn't elegant IMHO. I'd probably create a function that allows doing: ``` twos, threes = countmatching(xrange(1,10), lambda a: a % 2 == 0, lambda a: a % 3 == 0) ``` A starting point would be something like this: ...
Accurate timestamping in Python
157,359
12
2008-10-01T12:36:17Z
157,439
11
2008-10-01T12:54:25Z
[ "python", "timestamp", "timer" ]
I've been building an error logging app recently and was after a way of accurately timestamping the incoming data. When I say accurately I mean each timestamp should be accurate relative to each other (no need to sync to an atomic clock or anything like that). I've been using datetime.now() as a first stab, but this i...
time.clock() only measures wallclock time on Windows. On other systems, time.clock() actually measures CPU-time. On those systems time.time() is more suitable for wallclock time, and it has as high a resolution as Python can manage -- which is as high as the OS can manage; usually using gettimeofday(3) (microsecond res...
Accurate timestamping in Python
157,359
12
2008-10-01T12:36:17Z
157,711
7
2008-10-01T13:55:57Z
[ "python", "timestamp", "timer" ]
I've been building an error logging app recently and was after a way of accurately timestamping the incoming data. When I say accurately I mean each timestamp should be accurate relative to each other (no need to sync to an atomic clock or anything like that). I've been using datetime.now() as a first stab, but this i...
You're unlikely to get sufficiently fine-grained control that you can completely eliminate the possibility of duplicate timestamps - you'd need resolution smaller than the time it takes to generate a datetime object. There are a couple of other approaches you might take to deal with it: 1. Deal with it. Leave your tim...
Python 2.5 dictionary 2 key sort
157,424
14
2008-10-01T12:50:19Z
157,445
17
2008-10-01T12:56:01Z
[ "python" ]
I have a dictionary of 200,000 items (the keys are strings and the values are integers). What is the best/most pythonic way to print the items sorted by descending value then ascending key (i.e. a 2 key sort)? ``` a={ 'keyC':1, 'keyB':2, 'keyA':1 } b = a.items() b.sort( key=lambda a:a[0]) b.sort( key=lambda a:a[1], ...
You can't sort dictionaries. You have to sort the list of items. Previous versions were wrong. When you have a numeric value, it's easy to sort in reverse order. These will do that. But this isn't general. This only works because the value is numeric. ``` a = { 'key':1, 'another':2, 'key2':1 } b= a.items() b.sort( k...
Hiding a password in a (python) script
157,938
75
2008-10-01T14:37:17Z
157,975
69
2008-10-01T14:43:51Z
[ "python", "security" ]
I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. Is there an easy way to obscure this password in the file (just that nobody can read the password when I...
[Base64 encoding](http://docs.python.org/lib/module-base64.html) is in the standard library and will do to stop shoulder surfers: ``` >>> import base64 >>> print base64.b64encode("password") cGFzc3dvcmQ= >>> print base64.b64decode("cGFzc3dvcmQ=") password ```
Hiding a password in a (python) script
157,938
75
2008-10-01T14:37:17Z
158,221
10
2008-10-01T15:28:38Z
[ "python", "security" ]
I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. Is there an easy way to obscure this password in the file (just that nobody can read the password when I...
How about importing the username and password from a file external to the script? That way even if someone got hold of the script, they wouldn't automatically get the password.
Hiding a password in a (python) script
157,938
75
2008-10-01T14:37:17Z
158,248
33
2008-10-01T15:34:13Z
[ "python", "security" ]
I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. Is there an easy way to obscure this password in the file (just that nobody can read the password when I...
Douglas F Shearer's is the generally approved solution in Unix when you need to specify a password for a remote login. You add a **--password-from-file** option to specify the path and read plaintext from a file. The file can then be in the user's own area protected by the operating system. It also allows different...
Hiding a password in a (python) script
157,938
75
2008-10-01T14:37:17Z
158,387
15
2008-10-01T16:09:40Z
[ "python", "security" ]
I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. Is there an easy way to obscure this password in the file (just that nobody can read the password when I...
The best solution, assuming the username and password can't be given at runtime by the user, is probably a separate source file containing only variable initialization for the username and password that is imported into your main code. This file would only need editing when the credentials change. Otherwise, if you're ...
Hiding a password in a (python) script
157,938
75
2008-10-01T14:37:17Z
160,042
10
2008-10-01T22:26:09Z
[ "python", "security" ]
I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. Is there an easy way to obscure this password in the file (just that nobody can read the password when I...
base64 is the way to go for your simple needs. There is no need to import anything: ``` >>> 'your string'.encode('base64') 'eW91ciBzdHJpbmc=\n' >>> _.decode('base64') 'your string' ```
Hiding a password in a (python) script
157,938
75
2008-10-01T14:37:17Z
6,451,826
17
2011-06-23T09:17:55Z
[ "python", "security" ]
I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. Is there an easy way to obscure this password in the file (just that nobody can read the password when I...
If you are working on a Unix system, take advantage of the netrc module in the standard Python library. It reads passwords from a separate text file (.netrc), which has the format decribed [here](http://www.mavetju.org/unix/netrc.php). Here is a small usage example: ``` import netrc # Define which host in the .netrc...
Hiding a password in a (python) script
157,938
75
2008-10-01T14:37:17Z
22,821,470
10
2014-04-02T19:45:46Z
[ "python", "security" ]
I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. Is there an easy way to obscure this password in the file (just that nobody can read the password when I...
Here is a simple method: 1. Create a python module - let's call it peekaboo.py. 2. In peekaboo.py, include both the password and any code needing that password 3. Create a compiled version - peekaboo.pyc - by importing this module (via python commandline, etc...). 4. Now, delete peekaboo.py. 5. You can now happily imp...
Python module dependency
158,268
15
2008-10-01T15:38:58Z
158,326
7
2008-10-01T15:52:34Z
[ "python", "module", "circular-dependency" ]
Ok I have two modules, each containing a class, the problem is their classes reference each other. Lets say for example I had a room module and a person module containing CRoom and CPerson. The CRoom class contains infomation about the room, and a CPerson list of every one in the room. The CPerson class however some...
Do you actually need to reference the classes at class definition time? ie. ``` class CRoom(object): person = CPerson("a person") ``` Or (more likely), do you just need to use CPerson in the methods of your class (and vice versa). eg: ``` class CRoom(object): def getPerson(self): return CPerson("someone") ...
Python module dependency
158,268
15
2008-10-01T15:38:58Z
158,403
16
2008-10-01T16:11:41Z
[ "python", "module", "circular-dependency" ]
Ok I have two modules, each containing a class, the problem is their classes reference each other. Lets say for example I had a room module and a person module containing CRoom and CPerson. The CRoom class contains infomation about the room, and a CPerson list of every one in the room. The CPerson class however some...
**No need to import CRoom** You don't use `CRoom` in `person.py`, so don't import it. Due to dynamic binding, Python doesn't need to "see all class definitions at compile time". If you actually *do* use `CRoom` in `person.py`, then change `from room import CRoom` to `import room` and use module-qualified form `room.C...
Best way to store and use a large text-file in python
158,546
4
2008-10-01T16:37:08Z
158,753
10
2008-10-01T17:30:41Z
[ "python" ]
I'm creating a networked server for a boggle-clone I wrote in python, which accepts users, solves the boards, and scores the player input. The dictionary file I'm using is 1.8MB (the ENABLE2K dictionary), and I need it to be available to several game solver classes. Right now, I have it so that each class iterates thro...
If you create a dictionary.py module, containing code which reads the file and builds a dictionary, this code will only be executed the first time it is imported. Further imports will return a reference to the existing module instance. As such, your classes can: ``` import dictionary dictionary.words[whatever] ``` w...
Getting MAC Address
159,137
68
2008-10-01T18:51:36Z
159,150
13
2008-10-01T18:55:14Z
[ "python", "windows", "linux", "networking" ]
I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of another ...
netifaces is a good module to use for getting the mac address (and other addresses). It's crossplatform and makes a bit more sense than using socket or uuid. ``` >>> import netifaces >>> netifaces.interfaces() ['lo', 'eth0', 'tun2'] >>> netifaces.ifaddresses('eth0')[netifaces.AF_LINK] [{'addr': '08:00:27:50:f2:51', '...
Getting MAC Address
159,137
68
2008-10-01T18:51:36Z
159,195
92
2008-10-01T19:06:30Z
[ "python", "windows", "linux", "networking" ]
I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of another ...
Python 2.5 includes an uuid implementation which (in at least one version) needs the mac address. You can import the mac finding function into your own code easily: ``` from uuid import getnode as get_mac mac = get_mac() ``` The return value is the mac address as 48 bit integer.
Getting MAC Address
159,137
68
2008-10-01T18:51:36Z
160,821
17
2008-10-02T03:49:54Z
[ "python", "windows", "linux", "networking" ]
I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of another ...
One other thing that you should note is that `uuid.getnode()` can fake the MAC addr by returning a random 48-bit number which may not be what you are expecting. Also, there's no explicit indication that the MAC address has been faked, but you could detect it by calling `getnode()` twice and seeing if the result varies....
Getting MAC Address
159,137
68
2008-10-01T18:51:36Z
4,789,267
57
2011-01-25T01:57:17Z
[ "python", "windows", "linux", "networking" ]
I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of another ...
The pure python solution for this problem under Linux to get the MAC for a specific local interface, originally posted as a comment by vishnubob and improved by on Ben Mackey in [this activestate recipe](http://code.activestate.com/recipes/439094-get-the-ip-address-associated-with-a-network-inter/) ``` #!/usr/bin/pyth...
Getting MAC Address
159,137
68
2008-10-01T18:51:36Z
18,031,954
7
2013-08-03T10:40:10Z
[ "python", "windows", "linux", "networking" ]
I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of another ...
Using my answer from here: <http://stackoverflow.com/a/18031868/2362361> It would be important to know to which iface you want the MAC for since many can exist (bluetooth, several nics, etc.). This does the job when you know the IP of the iface you need the MAC for, using `netifaces` (available in PyPI): ``` import ...
Nginx + fastcgi truncation problem
159,541
10
2008-10-01T20:26:12Z
5,218,788
7
2011-03-07T10:54:59Z
[ "python", "django", "nginx", "fastcgi" ]
I'm running a Django site using the fastcgi interface to nginx. However, some pages are being served truncated (i.e. the page source just stops, sometimes in the middle of a tag). How do I fix this (let me know what extra information is needed, and I'll post it) Details: I'm using flup, and spawning the fastcgi serve...
I had the same exact problem running Nagios on nginx. I stumbled upon your question while googling for an answer, and reading "permission denied" related answers it struck me (and perhaps it will help you) : * Nginx error.log was reporting : 2011/03/07 11:36:02 [crit] 30977#0: \*225952 open() "/var/lib/nginx/fastcg...
What is the naming convention in Python for variable and function names?
159,720
326
2008-10-01T21:01:16Z
159,745
381
2008-10-01T21:05:24Z
[ "python", "variables", "function", "naming-conventions" ]
Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case: ``` // C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() ``` In Python, I have seen the above but I have also seen underscores being used: ``` # python example this_is_my_...
See Python [PEP 8](http://www.python.org/dev/peps/pep-0008/). > Function names should be lowercase, > with words separated by underscores as > necessary to improve readability. > > mixedCase is allowed only in contexts > where that's already the prevailing > style Variables... > Use the function naming rules: > lowe...
What is the naming convention in Python for variable and function names?
159,720
326
2008-10-01T21:01:16Z
159,778
26
2008-10-01T21:12:41Z
[ "python", "variables", "function", "naming-conventions" ]
Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case: ``` // C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() ``` In Python, I have seen the above but I have also seen underscores being used: ``` # python example this_is_my_...
There is [PEP 8](http://www.python.org/dev/peps/pep-0008/), as other answers show, but PEP 8 is only the styleguide for the standard library, and it's only taken as gospel therein. One of the most frequent deviations of PEP 8 for other pieces of code is the variable naming, specifically for methods. There is no single ...
What is the naming convention in Python for variable and function names?
159,720
326
2008-10-01T21:01:16Z
159,798
11
2008-10-01T21:16:21Z
[ "python", "variables", "function", "naming-conventions" ]
Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case: ``` // C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() ``` In Python, I have seen the above but I have also seen underscores being used: ``` # python example this_is_my_...
Most python people prefer underscores, but even I am using python since more than 5 years right now, I still do not like them. They just look ugly to me, but maybe that's all the Java in my head. I simply like CamelCase better since it fits better with the way classes are named, It feels more logical to have `SomeClas...
What is the naming convention in Python for variable and function names?
159,720
326
2008-10-01T21:01:16Z
160,769
9
2008-10-02T03:24:30Z
[ "python", "variables", "function", "naming-conventions" ]
Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case: ``` // C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() ``` In Python, I have seen the above but I have also seen underscores being used: ``` # python example this_is_my_...
Personally I try to use CamelCase for classes, mixedCase methods and functions. Variables are usually underscore separated (when I can remember). This way I can tell at a glance what exactly I'm calling, rather than everything looking the same.
What is the naming convention in Python for variable and function names?
159,720
326
2008-10-01T21:01:16Z
160,830
150
2008-10-02T03:53:12Z
[ "python", "variables", "function", "naming-conventions" ]
Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case: ``` // C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() ``` In Python, I have seen the above but I have also seen underscores being used: ``` # python example this_is_my_...
David Goodger (in "Code Like a Pythonista" [here](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html)) describes the PEP 8 recommendations as follows: * `joined_lower` for functions, methods, attributes, variables * `joined_lower` or `ALL_CAPS` for constants * `StudlyCaps` for classes * `camelCa...
What is the naming convention in Python for variable and function names?
159,720
326
2008-10-01T21:01:16Z
264,226
23
2008-11-05T02:51:29Z
[ "python", "variables", "function", "naming-conventions" ]
Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case: ``` // C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() ``` In Python, I have seen the above but I have also seen underscores being used: ``` # python example this_is_my_...
As mentioned, PEP 8 says to use `lower_case_with_underscores` for variables, methods and functions. I prefer using `lower_case_with_underscores` for variables and `mixedCase` for methods and functions makes the code more explicit and readable. Thus following the [Zen of Python's](http://www.python.org/dev/peps/pep-002...
What is the naming convention in Python for variable and function names?
159,720
326
2008-10-01T21:01:16Z
2,708,015
26
2010-04-25T11:23:57Z
[ "python", "variables", "function", "naming-conventions" ]
Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case: ``` // C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() ``` In Python, I have seen the above but I have also seen underscores being used: ``` # python example this_is_my_...
As the [Style Guide for Python Code](http://www.python.org/dev/peps/pep-0008/) admits, > The naming conventions of Python's > library are a bit of a mess, so we'll > never get this completely consistent Note that this refers just to Python's *standard library*. If they can't get *that* consistent, then there hardly i...
What is the naming convention in Python for variable and function names?
159,720
326
2008-10-01T21:01:16Z
8,423,697
252
2011-12-07T22:44:24Z
[ "python", "variables", "function", "naming-conventions" ]
Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case: ``` // C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() ``` In Python, I have seen the above but I have also seen underscores being used: ``` # python example this_is_my_...
[Google Python Style Guide](https://google.github.io/styleguide/pyguide.html) has the following convention: > module\_name, package\_name, ClassName, method\_name, ExceptionName, > function\_name, GLOBAL\_CONSTANT\_NAME, global\_var\_name, > instance\_var\_name, function\_parameter\_name, local\_var\_name
What is the difference between Ruby and Python versions of"self"?
159,990
6
2008-10-01T22:09:16Z
160,227
7
2008-10-01T23:32:01Z
[ "python", "ruby", "language-features" ]
I've done some Python but have just now starting to use Ruby I could use a good explanation of the difference between "self" in these two languages. **Obvious on first glance:** Self is not a keyword in Python, but there is a "self-like" value no matter what you call it. Python methods receive self as an explici...
Python is designed to support more than just object-oriented programming. Preserving the same interface between methods and functions lets the two styles interoperate more cleanly. Ruby was built from the ground up to be object-oriented. Even the literals are objects (evaluate 1.class and you get Fixnum). The language...
Which is the best way to get a list of running processes in unix with python?
160,245
2
2008-10-01T23:37:06Z
160,375
8
2008-10-02T00:29:39Z
[ "python" ]
I'm trying: ``` import commands print commands.getoutput("ps -u 0") ``` But it doesn't work on os x. os instead of commands gives the same output: USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND nothing more
This works on Mac OS X 10.5.5. Note the capital **-U** option. Perhaps that's been your problem. ``` import subprocess ps = subprocess.Popen("ps -U 0", shell=True, stdout=subprocess.PIPE) print ps.stdout.read() ps.stdout.close() ps.wait() ``` Here's the Python version ``` Python 2.5.2 (r252:60911, Feb 22 2008, 07:57...
What is "lambda binding" in Python?
160,859
9
2008-10-02T04:14:01Z
160,898
12
2008-10-02T04:38:59Z
[ "python", "binding", "lambda" ]
I understand what are lambda functions in Python, but I can't find what is the meaning of "lambda binding" by searching the Python docs. A link to read about it would be great. A trivial explained example would be even better. Thank you.
First, a general definition: > When a program or function statement > is executed, the current values of > formal parameters are saved (on the > stack) and within the scope of the > statement, they are bound to the > values of the actual arguments made in > the call. When the statement is > exited, the original values...
Emulation of lex like functionality in Perl or Python
160,889
4
2008-10-02T04:34:06Z
160,922
8
2008-10-02T04:53:03Z
[ "python", "perl", "parsing", "lex" ]
Here's the deal. Is there a way to have strings tokenized in a line based on multiple regexes? One example: I have to get all href tags, their corresponding text and some other text based on a different regex. So I have 3 expressions and would like to tokenize the line and extract tokens of text matching every expres...
Look at documentation for following modules on [CPAN](http://www.cpan.org/) [HTML::TreeBuilder](http://search.cpan.org/search?query=HTML%3A%3ATreeBuilder&mode=all) [HTML::TableExtract](http://search.cpan.org/author/MSISK/HTML-TableExtract-2.10/lib/HTML/TableExtract.pm) and [Parse::RecDescent](http://search.cpan.org...
Emulation of lex like functionality in Perl or Python
160,889
4
2008-10-02T04:34:06Z
161,146
7
2008-10-02T06:52:06Z
[ "python", "perl", "parsing", "lex" ]
Here's the deal. Is there a way to have strings tokenized in a line based on multiple regexes? One example: I have to get all href tags, their corresponding text and some other text based on a different regex. So I have 3 expressions and would like to tokenize the line and extract tokens of text matching every expres...
If you're specifically after parsing links out of web-pages, then Perl's [WWW::Mechanize](http://search.cpan.org/perldoc?WWW::Mechanize) module will figure things out for you in a very elegant fashion. Here's a sample program that grabs the first page of Stack Overflow and parses out all the links, printing their text ...
Django and Python 2.6
162,808
5
2008-10-02T15:00:00Z
163,163
7
2008-10-02T15:58:41Z
[ "python", "django" ]
I'm just starting to get into Django, and of course as of last night one of the two new Python versions went final (2.6 obviously ;)) so I'm wondering if 2.6 plus Django is ready for actual use or do the Django team need more time to finish with tweaks/cleanup? All the google searches I did were inconclusive, I saw bi...
The impression I get is that 2.6 should work fine with Django 1.0. As found here: <http://simonwillison.net/2008/Oct/2/whatus/>
urllib2 file name
163,009
24
2008-10-02T15:27:04Z
163,095
37
2008-10-02T15:43:12Z
[ "python", "url", "urllib2" ]
If I open a file using urllib2, like so: ``` remotefile = urllib2.urlopen('http://example.com/somefile.zip') ``` Is there an easy way to get the file name other then parsing the original URL? EDIT: changed openfile to urlopen... not sure how that happened. EDIT2: I ended up using: ``` filename = url.split('/')[-1]...
Did you mean [urllib2.urlopen](http://www.python.org/doc/2.5.2/lib/module-urllib2.html#l2h-3928)? You could potentially lift the *intended* filename *if* the server was sending a Content-Disposition header by checking `remotefile.info()['Content-Disposition']`, but as it is I think you'll just have to parse the url. ...
urllib2 file name
163,009
24
2008-10-02T15:27:04Z
163,202
10
2008-10-02T16:06:16Z
[ "python", "url", "urllib2" ]
If I open a file using urllib2, like so: ``` remotefile = urllib2.urlopen('http://example.com/somefile.zip') ``` Is there an easy way to get the file name other then parsing the original URL? EDIT: changed openfile to urlopen... not sure how that happened. EDIT2: I ended up using: ``` filename = url.split('/')[-1]...
If you only want the file name itself, assuming that there's no query variables at the end like <http://example.com/somedir/somefile.zip?foo=bar> then you can use os.path.basename for this: ``` [user@host]$ python Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) Type "help", "copyright", "credits" or "license" for mo...
Python - How do I pass a string into subprocess.Popen (using the stdin argument)?
163,542
175
2008-10-02T17:25:23Z
163,556
21
2008-10-02T17:27:55Z
[ "python", "subprocess", "stdin" ]
If I do the following: ``` import subprocess from cStringIO import StringIO subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0] ``` I get: ``` Traceback (most recent call last): File "<stdin>", line 1, in ? File "/build/toolchain/mac32/pytho...
I figured out this workaround: ``` >>> p = subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=subprocess.PIPE) >>> p.stdin.write('one\ntwo\nthree\nfour\nfive\nsix\n') >>> p.communicate()[0] 'four\nfive\n' >>> p.stdin.close() ``` Is there a better one?
Python - How do I pass a string into subprocess.Popen (using the stdin argument)?
163,542
175
2008-10-02T17:25:23Z
163,870
12
2008-10-02T18:33:23Z
[ "python", "subprocess", "stdin" ]
If I do the following: ``` import subprocess from cStringIO import StringIO subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0] ``` I get: ``` Traceback (most recent call last): File "<stdin>", line 1, in ? File "/build/toolchain/mac32/pytho...
"Apparently a cStringIO.StringIO object doesn't quack close enough to a file duck to suit subprocess.Popen" :-) I'm afraid not. The pipe is a low-level OS concept, so it absolutely requires a file object that is represented by an OS-level file descriptor. Your workaround is the right one.
Python - How do I pass a string into subprocess.Popen (using the stdin argument)?
163,542
175
2008-10-02T17:25:23Z
165,662
194
2008-10-03T04:11:07Z
[ "python", "subprocess", "stdin" ]
If I do the following: ``` import subprocess from cStringIO import StringIO subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0] ``` I get: ``` Traceback (most recent call last): File "<stdin>", line 1, in ? File "/build/toolchain/mac32/pytho...
[`Popen.communicate()`](https://docs.python.org/3/library/subprocess.html?highlight=subprocess#subprocess.Popen.communicate) documentation: > Note that if you want to send data to > the process’s stdin, you need to > create the Popen object with > stdin=PIPE. Similarly, to get anything > other than None in the resul...
Python - How do I pass a string into subprocess.Popen (using the stdin argument)?
163,542
175
2008-10-02T17:25:23Z
10,134,899
7
2012-04-13T03:36:37Z
[ "python", "subprocess", "stdin" ]
If I do the following: ``` import subprocess from cStringIO import StringIO subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0] ``` I get: ``` Traceback (most recent call last): File "<stdin>", line 1, in ? File "/build/toolchain/mac32/pytho...
``` from subprocess import Popen, PIPE from tempfile import SpooledTemporaryFile as tempfile f = tempfile() f.write('one\ntwo\nthree\nfour\nfive\nsix\n') f.seek(0) print Popen(['/bin/grep','f'],stdout=PIPE,stdin=f).stdout.read() f.close() ```
Python - How do I pass a string into subprocess.Popen (using the stdin argument)?
163,542
175
2008-10-02T17:25:23Z
24,982,453
12
2014-07-27T15:29:17Z
[ "python", "subprocess", "stdin" ]
If I do the following: ``` import subprocess from cStringIO import StringIO subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0] ``` I get: ``` Traceback (most recent call last): File "<stdin>", line 1, in ? File "/build/toolchain/mac32/pytho...
I am using python3 and found out that you need to encode your string before you can pass it into stdin: ``` p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=PIPE) out, err = p.communicate(input='one\ntwo\nthree\nfour\nfive\nsix\n'.encode()) print(out) ```
Python - How do I pass a string into subprocess.Popen (using the stdin argument)?
163,542
175
2008-10-02T17:25:23Z
33,482,438
9
2015-11-02T16:34:03Z
[ "python", "subprocess", "stdin" ]
If I do the following: ``` import subprocess from cStringIO import StringIO subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0] ``` I get: ``` Traceback (most recent call last): File "<stdin>", line 1, in ? File "/build/toolchain/mac32/pytho...
I'm a bit surprised nobody suggested creating a pipe, which is in my opinion the far simplest way to pass a string to stdin of a subprocess: ``` read, write = os.pipe() os.write(write, "stdin input here") os.close(write) subprocess.check_call(['your-command'], stdin=read) ```
Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?
163,823
150
2008-10-02T18:26:19Z
163,968
19
2008-10-02T18:53:23Z
[ "python", "django", "django-admin", "modeladmin" ]
I have a Person model that has a foreign key relationship to Book. Book has a number of fields, but I'm most concerned about "author" (a standard CharField). With that being said, in my PersonAdmin model, I'd like to display "book.author" using "list\_display". I've tried all of the obvious methods for doing so (see b...
According to the documentation, you can only display the `__unicode__` representation of a ForeignKey: <http://docs.djangoproject.com/en/dev/ref/contrib/admin/#list-display> Seems odd that it doesn't support the `'book__author'` style format which is used everywhere else in the DB API. Turns out there's [a ticket fo...
Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?
163,823
150
2008-10-02T18:26:19Z
164,631
240
2008-10-02T21:11:56Z
[ "python", "django", "django-admin", "modeladmin" ]
I have a Person model that has a foreign key relationship to Book. Book has a number of fields, but I'm most concerned about "author" (a standard CharField). With that being said, in my PersonAdmin model, I'd like to display "book.author" using "list\_display". I've tried all of the obvious methods for doing so (see b...
As another option, you can do look ups like: ``` class UserAdmin(admin.ModelAdmin): list_display = (..., 'get_author') def get_author(self, obj): return obj.book.author get_author.short_description = 'Author' get_author.admin_order_field = 'book__author' ```
Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?
163,823
150
2008-10-02T18:26:19Z
496,453
9
2009-01-30T17:41:43Z
[ "python", "django", "django-admin", "modeladmin" ]
I have a Person model that has a foreign key relationship to Book. Book has a number of fields, but I'm most concerned about "author" (a standard CharField). With that being said, in my PersonAdmin model, I'd like to display "book.author" using "list\_display". I've tried all of the obvious methods for doing so (see b...
You can show whatever you want in list display by using a callable. It would look like this: ``` def book_author(object): return object.book.author class PersonAdmin(admin.ModelAdmin): list_display = [book_author,] ```
Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?
163,823
150
2008-10-02T18:26:19Z
3,351,431
51
2010-07-28T09:13:55Z
[ "python", "django", "django-admin", "modeladmin" ]
I have a Person model that has a foreign key relationship to Book. Book has a number of fields, but I'm most concerned about "author" (a standard CharField). With that being said, in my PersonAdmin model, I'd like to display "book.author" using "list\_display". I've tried all of the obvious methods for doing so (see b...
Like the rest, I went with callables too. But they have one downside: by default, you can't order on them. Fortunately, there is a solution for that: ``` def author(self): return self.book.author author.admin_order_field = 'book__author' ```
Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?
163,823
150
2008-10-02T18:26:19Z
14,677,451
9
2013-02-03T21:21:58Z
[ "python", "django", "django-admin", "modeladmin" ]
I have a Person model that has a foreign key relationship to Book. Book has a number of fields, but I'm most concerned about "author" (a standard CharField). With that being said, in my PersonAdmin model, I'd like to display "book.author" using "list\_display". I've tried all of the obvious methods for doing so (see b...
I just posted a snippet that makes admin.ModelAdmin support '\_\_' syntax: <http://djangosnippets.org/snippets/2887/> So you can do: ``` class PersonAdmin(RelatedFieldAdmin): list_display = ['book__author',] ``` This is basically just doing the same thing described in the other answers, but it automatically tak...
Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?
163,823
150
2008-10-02T18:26:19Z
23,747,842
52
2014-05-19T21:55:14Z
[ "python", "django", "django-admin", "modeladmin" ]
I have a Person model that has a foreign key relationship to Book. Book has a number of fields, but I'm most concerned about "author" (a standard CharField). With that being said, in my PersonAdmin model, I'd like to display "book.author" using "list\_display". I've tried all of the obvious methods for doing so (see b...
Despite all the great answers above and due to me being new to Django, I was still stuck. Here's my explanation from a very newbie perspective. **models.py** ``` class Author(models.Model): name = models.CharField(max_length=255) class Book(models.Model): author = models.ForeignKey(Author) title = models...
Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?
163,823
150
2008-10-02T18:26:19Z
28,190,954
7
2015-01-28T11:20:40Z
[ "python", "django", "django-admin", "modeladmin" ]
I have a Person model that has a foreign key relationship to Book. Book has a number of fields, but I'm most concerned about "author" (a standard CharField). With that being said, in my PersonAdmin model, I'd like to display "book.author" using "list\_display". I've tried all of the obvious methods for doing so (see b...
Please note that adding the `get_author` function would slow the list\_display in the admin, because showing each person would make a SQL query. To avoid this, you need to modify `get_queryset` method in PersonAdmin, for example: ``` def get_queryset(self, request): return super(PersonAdmin,self).get_queryset(req...
How do I deploy a Python desktop application?
164,137
28
2008-10-02T19:31:51Z
164,291
12
2008-10-02T20:02:01Z
[ "python", "deployment" ]
I have started on a personal python application that runs on the desktop. I am using wxPython as a GUI toolkit. Should there be a demand for this type of application, I would possibly like to commercialize it. I have no knowledge of deploying "real-life" Python applications, though I have used [`py2exe`](http://www.py...
You can distribute the compiled Python bytecode (.pyc files) instead of the source. You can't prevent decompilation in Python (or any other language, really). You could use an obfuscator like [pyobfuscate](http://www.lysator.liu.se/~astrand/projects/pyobfuscate/) to make it more annoying for competitors to decipher you...
Change Django Templates Based on User-Agent
164,427
38
2008-10-02T20:30:09Z
164,507
18
2008-10-02T20:44:38Z
[ "python", "django", "django-templates", "mobile-website", "django-middleware" ]
I've made a Django site, but I've drank the Koolaid and I want to make an *IPhone* version. After putting much thought into I've come up with two options: 1. Make a whole other site, like i.xxxx.com. Tie it into the same database using Django's sites framework. 2. Find some time of middleware that reads the user-agent...
Rather than changing the template directories dynamically you could modify the request and add a value that lets your view know if the user is on an iphone or not. Then wrap render\_to\_response (or whatever you are using for creating HttpResponse objects) to grab the iphone version of the template instead of the stand...
Change Django Templates Based on User-Agent
164,427
38
2008-10-02T20:30:09Z
3,487,254
9
2010-08-15T11:57:53Z
[ "python", "django", "django-templates", "mobile-website", "django-middleware" ]
I've made a Django site, but I've drank the Koolaid and I want to make an *IPhone* version. After putting much thought into I've come up with two options: 1. Make a whole other site, like i.xxxx.com. Tie it into the same database using Django's sites framework. 2. Find some time of middleware that reads the user-agent...
Detect the user agent in middleware, switch the url bindings, profit! How? Django request objects have a .urlconf attribute, which can be set by middleware. From django docs: > Django determines the root URLconf > module to use. Ordinarily, this is the > value of the ROOT\_URLCONF setting, but > if the incoming Http...
Programmatically launching standalone Adobe flashplayer on Linux/X11
164,460
7
2008-10-02T20:36:02Z
165,089
7
2008-10-02T23:44:15Z
[ "python", "linux", "adobe", "x11", "flash-player" ]
The standalone flashplayer takes no arguments other than a .swf file when you launch it from the command line. I need the player to go full screen, no window borders and such. This can be accomplished by hitting ctrl+f once the program has started. I want to do this programmatically as I need it to launch into full scr...
You can use a dedicated application which sends the keystroke to the window manager, which should then pass it to flash, if the window starts as being the active window on the screen. This is quite error prone, though, due to delays between starting flash and when the window will show up. For example, your script coul...
How would I package and sell a Django app?
164,901
30
2008-10-02T22:27:56Z
164,920
11
2008-10-02T22:40:24Z
[ "python", "django", "distribution", "piracy-prevention" ]
Currently I am hosting a Django app I developed myself for my clients, but I am now starting to look at selling it to people for them to host themselves. My question is this: How can I package up and sell a Django app, while protecting its code from pirating or theft? Distributing a bunch of .py files doesn't sound li...
The way I'd go about it is this: 1. Encrypt all of the code 2. Write an installer that contacts the server with the machine's hostname and license file and gets the decryption key, then decrypts the code and compiles it to python bytecode 3. Add (in the installer) a module that checks the machine's hostname and licens...
How would I package and sell a Django app?
164,901
30
2008-10-02T22:27:56Z
164,959
9
2008-10-02T22:54:43Z
[ "python", "django", "distribution", "piracy-prevention" ]
Currently I am hosting a Django app I developed myself for my clients, but I am now starting to look at selling it to people for them to host themselves. My question is this: How can I package up and sell a Django app, while protecting its code from pirating or theft? Distributing a bunch of .py files doesn't sound li...
You could package the whole thing up as an Amazon Machine Instance (AMI), and then have them run your app on [Amazon EC2](http://aws.amazon.com/ec2/). The nice thing about this solution is that Amazon will [take care of billing for you](http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/index.html?paidamis-...
How would I package and sell a Django app?
164,901
30
2008-10-02T22:27:56Z
164,987
48
2008-10-02T23:10:21Z
[ "python", "django", "distribution", "piracy-prevention" ]
Currently I am hosting a Django app I developed myself for my clients, but I am now starting to look at selling it to people for them to host themselves. My question is this: How can I package up and sell a Django app, while protecting its code from pirating or theft? Distributing a bunch of .py files doesn't sound li...
Don't try and obfuscate or encrypt the code - it will never work. I would suggest selling the Django application "as a service" - either host it for them, or sell them the code *and support*. Write up a contract that forbids them from redistributing it. That said, if you were determined to obfuscate the code in some ...
How would I package and sell a Django app?
164,901
30
2008-10-02T22:27:56Z
167,240
7
2008-10-03T14:48:12Z
[ "python", "django", "distribution", "piracy-prevention" ]
Currently I am hosting a Django app I developed myself for my clients, but I am now starting to look at selling it to people for them to host themselves. My question is this: How can I package up and sell a Django app, while protecting its code from pirating or theft? Distributing a bunch of .py files doesn't sound li...
You'll never be able to keep the source code from people who really want it. It's best to come to grips with this fact now, and save yourself the headache later.
How would I package and sell a Django app?
164,901
30
2008-10-02T22:27:56Z
445,887
10
2009-01-15T07:01:38Z
[ "python", "django", "distribution", "piracy-prevention" ]
Currently I am hosting a Django app I developed myself for my clients, but I am now starting to look at selling it to people for them to host themselves. My question is this: How can I package up and sell a Django app, while protecting its code from pirating or theft? Distributing a bunch of .py files doesn't sound li...
"Encrypting" Python source code (or bytecode, or really bytecode for any language that uses it -- not just Python) is like those little JavaScript things some people put on web pages to try to disable the right-hand mouse button, declaring "now you can't steal my images!" The workarounds are trivial, and will not stop...
Detecting Mouse clicks in windows using python
165,495
13
2008-10-03T02:51:44Z
168,996
23
2008-10-03T21:38:15Z
[ "python", "windows", "mouse" ]
How can I detect mouse clicks regardless of the window the mouse is in? Perferabliy in python, but if someone can explain it in any langauge I might be able to figure it out. I found this on microsoft's site: <http://msdn.microsoft.com/en-us/library/ms645533(VS.85).aspx> But I don't see how I can detect or pick up t...
The only way to detect mouse events outside your program is to install a Windows hook using [SetWindowsHookEx](http://msdn.microsoft.com/en-us/library/ms644990(VS.85).aspx). The [pyHook](http://www.cs.unc.edu/Research/assist/developer.shtml) module encapsulates the nitty-gritty details. Here's a sample that will print ...
Python object attributes - methodology for access
165,883
22
2008-10-03T06:18:37Z
165,911
20
2008-10-03T06:35:37Z
[ "python", "oop", "object", "attributes" ]
Suppose I have a class with some attributes. How is it best (in the Pythonic-OOP) sense to access these attributes ? Just like `obj.attr` ? Or perhaps write get accessors ? What are the accepted naming styles for such things ? **Edit:** Can you elaborate on the best-practices of naming attributes with a single or doub...
The generally accepted way of doing things is just using simple attributes, like so ``` >>> class MyClass: ... myAttribute = 0 ... >>> c = MyClass() >>> c.myAttribute 0 >>> c.myAttribute = 1 >>> c.myAttribute 1 ``` If you do find yourself needing to be able to write getters and setters, then what you want to lo...
Python object attributes - methodology for access
165,883
22
2008-10-03T06:18:37Z
166,073
7
2008-10-03T09:23:40Z
[ "python", "oop", "object", "attributes" ]
Suppose I have a class with some attributes. How is it best (in the Pythonic-OOP) sense to access these attributes ? Just like `obj.attr` ? Or perhaps write get accessors ? What are the accepted naming styles for such things ? **Edit:** Can you elaborate on the best-practices of naming attributes with a single or doub...
> Edit: Can you elaborate on the best-practices of naming attributes with a single or double leading underscore ? I see in most modules that a single underscore is used. Single underscore doesn't mean anything special to python, it is just best practice, to tell "hey you probably don't want to access this unless you k...
Python object attributes - methodology for access
165,883
22
2008-10-03T06:18:37Z
166,098
51
2008-10-03T09:37:51Z
[ "python", "oop", "object", "attributes" ]
Suppose I have a class with some attributes. How is it best (in the Pythonic-OOP) sense to access these attributes ? Just like `obj.attr` ? Or perhaps write get accessors ? What are the accepted naming styles for such things ? **Edit:** Can you elaborate on the best-practices of naming attributes with a single or doub...
With regards to the single and double-leading underscores: both indicate the same concept of 'privateness'. That is to say, people will know the attribute (be it a method or a 'normal' data attribute or anything else) is not part of the public API of the object. People will know that to touch it directly is to invite d...
Sleeping in a batch file
166,044
129
2008-10-03T09:10:29Z
166,058
14
2008-10-03T09:15:39Z
[ "python", "batch-file" ]
When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it ...
`SLEEP.exe` is included in most Resource Kits e.g. [The Windows Server 2003 Resource Kit](http://www.microsoft.com/downloads/details.aspx?familyid=9d467a69-57ff-4ae7-96ee-b18c4790cffd&displaylang=en) which can be installed on Windows XP too. ``` Usage: sleep time-to-sleep-in-seconds sleep [-m] time-to-sl...
Sleeping in a batch file
166,044
129
2008-10-03T09:10:29Z
166,093
14
2008-10-03T09:35:43Z
[ "python", "batch-file" ]
When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it ...
I faced a similar problem, but I just knocked up a very short C++ console application to do the same thing. Just run *MySleep.exe 1000* - perhaps easier than downloading/installing the whole resource kit. ``` #include <tchar.h> #include <stdio.h> #include "Windows.h" int _tmain(int argc, _TCHAR* argv[]) { if (arg...
Sleeping in a batch file
166,044
129
2008-10-03T09:10:29Z
166,290
16
2008-10-03T10:42:19Z
[ "python", "batch-file" ]
When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it ...
If you have Python installed, or don't mind installing it (it has other uses too :), just create the following **sleep.py** script and add it somewhere in your PATH: ``` import time, sys time.sleep(float(sys.argv[1])) ``` It will allow sub-second pauses (e.g. 1.5 sec, 0.1 etc), should you have such a need. If you wa...
Sleeping in a batch file
166,044
129
2008-10-03T09:10:29Z
1,304,768
7
2009-08-20T08:28:55Z
[ "python", "batch-file" ]
When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it ...
You can use ping: ``` ping 127.0.0.1 -n 11 -w 1000 >nul: 2>nul: ``` will wait 10 seconds. The reason you have to use 11 is because the first ping goes out immediately, not after one second. The number should always be one more than the number of seconds you want to wait. Keep in mind that the purpose of the `-w` is...