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
Print the full numpy array
1,987,694
146
2010-01-01T01:51:46Z
1,988,024
155
2010-01-01T06:26:05Z
[ "python", "arrays", "numpy" ]
When I print a numpy array, I get a truncated representation, but I want the full array. Is there any way to do this? **Examples:** ``` >>> numpy.arange(10000) array([ 0, 1, 2, ..., 9997, 9998, 9999]) >>> numpy.arange(10000).reshape(250,40) array([[ 0, 1, 2, ..., 37, 38, 39], [ 40, 41...
To clarify on Reed's reply ``` import numpy numpy.set_printoptions(threshold=numpy.nan) ``` Note that the reply as given above works with an initial 'from numpy import \*', which is not advisable. This also works for me ``` numpy.set_printoptions(threshold='nan') ``` For full documentation, see <http://docs.scipy.o...
Print the full numpy array
1,987,694
146
2010-01-01T01:51:46Z
24,542,498
21
2014-07-02T23:08:50Z
[ "python", "arrays", "numpy" ]
When I print a numpy array, I get a truncated representation, but I want the full array. Is there any way to do this? **Examples:** ``` >>> numpy.arange(10000) array([ 0, 1, 2, ..., 9997, 9998, 9999]) >>> numpy.arange(10000).reshape(250,40) array([[ 0, 1, 2, ..., 37, 38, 39], [ 40, 41...
Here is a one-off way to do this, which is useful if you don't want to change your default settings: ``` def fullprint(*args, **kwargs): from pprint import pprint import numpy opt = numpy.get_printoptions() numpy.set_printoptions(threshold='nan') pprint(*args, **kwargs) numpy.set_printoptions(**opt) ```
Print the full numpy array
1,987,694
146
2010-01-01T01:51:46Z
26,018,905
38
2014-09-24T14:01:51Z
[ "python", "arrays", "numpy" ]
When I print a numpy array, I get a truncated representation, but I want the full array. Is there any way to do this? **Examples:** ``` >>> numpy.arange(10000) array([ 0, 1, 2, ..., 9997, 9998, 9999]) >>> numpy.arange(10000).reshape(250,40) array([[ 0, 1, 2, ..., 37, 38, 39], [ 40, 41...
``` import numpy as np np.set_printoptions(threshold=np.inf) ``` I suggest using `np.inf` instead of `np.nan` which is suggested by others. They both work for your purpose, but by setting the threshold to "infinity" it is obvious to everybody reading your code what you mean. Having a threshold of "not a number" seems ...
Print the full numpy array
1,987,694
146
2010-01-01T01:51:46Z
29,825,258
10
2015-04-23T13:40:50Z
[ "python", "arrays", "numpy" ]
When I print a numpy array, I get a truncated representation, but I want the full array. Is there any way to do this? **Examples:** ``` >>> numpy.arange(10000) array([ 0, 1, 2, ..., 9997, 9998, 9999]) >>> numpy.arange(10000).reshape(250,40) array([[ 0, 1, 2, ..., 37, 38, 39], [ 40, 41...
The previous answers are the correct ones, but as a weeker alternative you can transform into a list: ``` >>> numpy.arange(100).reshape(25,4).tolist() [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23], [24, 25, 26, 27], [28, 29, 30, 31], [32, 33, 34, 35], [36, 37, 38, 3...
Gracefully handling "MySQL has gone away"
1,987,701
17
2010-01-01T01:56:24Z
1,987,756
12
2010-01-01T02:46:49Z
[ "python", "mysql" ]
I'm writing a small database adapter in Python, mostly for fun. I'm trying to get the code to gracefully recover from a situation where the MySQL connection "goes away," aka `wait_timeout` is exceeded. I've set `wait_timeout` at `10` so I can try this. Here's my code: ``` def select(self, query, params=[]): t...
Can't see from the code, but my guess would be that the `db._get_cxn()` method is doing some kind of connection pooling and returning the existing connection object instead of making a new one. Is there not a call you can make on `db` to flush the existing useless connection? (And should you really be calling an intern...
Why can @decorator not decorate a staticmethod or a classmethod?
1,987,919
16
2010-01-01T05:06:03Z
1,989,025
17
2010-01-01T16:53:56Z
[ "python", "decorator" ]
Why can `decorator` not decorate a staticmethod or a classmethod? ``` from decorator import decorator @decorator def print_function_name(function, *args): print '%s was called.' % function.func_name return function(*args) class My_class(object): @print_function_name @classmethod def get_dir(cls):...
It works when `@classmathod` and `@staticmethod` are the top-most decorators: ``` from decorator import decorator @decorator def print_function_name(function, *args): print '%s was called.' % function.func_name return function(*args) class My_class(object): @classmethod @print_function_name def g...
Why can @decorator not decorate a staticmethod or a classmethod?
1,987,919
16
2010-01-01T05:06:03Z
6,208,458
14
2011-06-01T22:23:45Z
[ "python", "decorator" ]
Why can `decorator` not decorate a staticmethod or a classmethod? ``` from decorator import decorator @decorator def print_function_name(function, *args): print '%s was called.' % function.func_name return function(*args) class My_class(object): @print_function_name @classmethod def get_dir(cls):...
`classmethod` and `staticmethod` return [descriptor objects](https://docs.python.org/2/howto/descriptor.html), not functions. Most decorators are not designed to accept descriptors. Normally, then, you must apply `classmethod` and `staticmethod` last when using multiple decorators. And since decorators are applied in ...
Why django contains a lot of '__init__.py'?
1,988,149
3
2010-01-01T07:53:08Z
1,988,152
7
2010-01-01T07:57:11Z
[ "python", "django", "module" ]
Many directories in a django project contain a `__init__.py` and I think it will be used as initialization for something. Where is this `__init__.py` used?
Your question is not clear. What exactly are you asking? The file `__init__.py` is there so your folder can be defined as [a package](http://www.network-theory.co.uk/docs/pytut/Packages.html), which lets you do things like: ``` from myapp.models import Something ```
Why django contains a lot of '__init__.py'?
1,988,149
3
2010-01-01T07:53:08Z
1,989,096
10
2010-01-01T17:24:06Z
[ "python", "django", "module" ]
Many directories in a django project contain a `__init__.py` and I think it will be used as initialization for something. Where is this `__init__.py` used?
Python doesn't take every subdirectory of every directory in `sys.path` to necessarily be a *package*: only those with a file called `__init__.py`. Consider the following shell session: ``` $ mkdir adir $ echo 'print "hello world"' > adir/helo.py $ python -c 'import adir.helo' Traceback (most recent call last): File...
exception not getting caught when not in the right package in python
1,988,475
4
2010-01-01T12:33:52Z
1,988,648
7
2010-01-01T13:53:32Z
[ "python", "exception", "package" ]
EDIT: OK, I managed to isolate the bug and the exact, complete code to to reproduce it. But it appears either something that's by design, or a bug in python. Create two sibling packages: `admin` & `General`, each with it's own `__init__.py`, of course. In the package `admin` put the file 'test.py' with the following c...
``` import admin.RunStoppedException ``` This is an ambiguous relative import. Do you mean `RunStoppedException` from the `admin` top-level module? Or from `mypackage.admin` when you're in a package? If your current working directory (which is added to the module search path) happens to be inside the package, it could...
How do I get datetime from date object python?
1,988,599
3
2010-01-01T13:34:40Z
1,988,608
9
2010-01-01T13:38:14Z
[ "python", "datetime" ]
How do I get datetime from date object python? I think of ``` import datetime as dt today = dt.date.today() date_time = dt.datetime(today.year, today.month, today.day) ``` Any easier solution?
There are a few ways to do this: ``` mydatetime = datetime.datetime(d.year, d.month, d.day) ``` or ``` mydatetime = datetime.combine(d, datetime.time()) ``` or ``` mydatetime = datetime.datetime.fromordinal(d.toordinal()) ``` I think the first is the most commonly used.
What is memoization and how can I use it in Python?
1,988,804
215
2010-01-01T14:55:48Z
1,988,826
214
2010-01-01T15:05:05Z
[ "python", "memoization" ]
I just started Python and I've got no idea what [memoization](http://en.wikipedia.org/wiki/Memoization) is and how to use it. Also, may I have a simplified example?
Memoization effectively refers to remembering ("memoization" -> "memorandum" -> to be remembered) results of method calls based on the method inputs and then returning the remembered result rather than computing the result again. You can think of it as a cache for method results. For further details, see page 387 for t...
What is memoization and how can I use it in Python?
1,988,804
215
2010-01-01T14:55:48Z
1,988,828
14
2010-01-01T15:05:56Z
[ "python", "memoization" ]
I just started Python and I've got no idea what [memoization](http://en.wikipedia.org/wiki/Memoization) is and how to use it. Also, may I have a simplified example?
Memoization is keeping the results of expensive calculations and returning the cached result rather than continuously recalculating it. Here's an example: ``` def doSomeExpensiveCalculation(self, input): if input not in self.cache: <do expensive calculation> self.cache[input] = result return s...
What is memoization and how can I use it in Python?
1,988,804
215
2010-01-01T14:55:48Z
1,991,818
51
2010-01-02T14:55:06Z
[ "python", "memoization" ]
I just started Python and I've got no idea what [memoization](http://en.wikipedia.org/wiki/Memoization) is and how to use it. Also, may I have a simplified example?
The other answers cover what it is quite well. I'm not repeating that. Just some points that might be useful to you. Usually, memoisation is an operation you can apply on any function that computes something (expensive) and returns a value. Because of this, it's often implemented as a [decorator](http://www.python.org...
What is memoization and how can I use it in Python?
1,988,804
215
2010-01-01T14:55:48Z
14,731,729
98
2013-02-06T14:43:14Z
[ "python", "memoization" ]
I just started Python and I've got no idea what [memoization](http://en.wikipedia.org/wiki/Memoization) is and how to use it. Also, may I have a simplified example?
New to Python 3.2 is [`functools.lru_cache`](http://docs.python.org/3/library/functools.html). By default, it only caches the 128 most recently used calls, but you can set the `maxsize` to `None` to indicate that the cache should never expire: ``` import functools @functools.lru_cache(maxsize=None) def fib(num): ...
What is memoization and how can I use it in Python?
1,988,804
215
2010-01-01T14:55:48Z
26,769,816
7
2014-11-06T00:35:16Z
[ "python", "memoization" ]
I just started Python and I've got no idea what [memoization](http://en.wikipedia.org/wiki/Memoization) is and how to use it. Also, may I have a simplified example?
Let's not forget the built-in `hasattr` function, for those who want to hand-craft. That way you can keep the mem cache inside the function definition (as opposed to a global). ``` def fact(n): if not hasattr(fact, 'mem'): fact.mem = {1: 1} if not n in fact.mem: fact.mem[n] = n * fact(n - 1) ...
Alternatives to keeping large lists in memory (python)
1,989,251
10
2010-01-01T18:31:57Z
1,989,278
8
2010-01-01T18:42:11Z
[ "python", "file", "list", "memory-management", "32bit-64bit" ]
If I have a list(or array, dictionary....) in python that could exceed the available memory address space, (32 bit python) what are the options and there relative speeds? (other than not making a list that large) Let me emphasize "could". The list could exceed the memory but I have know way of knowing before hand. If i...
There are probably dozens of ways to store your list data in a file instead of in memory. How you choose to do it will depend entirely on what sort of operations you need to perform on the data. Do you need random access to the Nth element? Do you need to iterate over all elements? Will you be searching for elements th...
Alternatives to keeping large lists in memory (python)
1,989,251
10
2010-01-01T18:31:57Z
1,989,434
12
2010-01-01T19:53:36Z
[ "python", "file", "list", "memory-management", "32bit-64bit" ]
If I have a list(or array, dictionary....) in python that could exceed the available memory address space, (32 bit python) what are the options and there relative speeds? (other than not making a list that large) Let me emphasize "could". The list could exceed the memory but I have know way of knowing before hand. If i...
If your "numbers" are simple-enough ones (signed or unsigned integers of up to 4 bytes each, or floats of 4 or 8 bytes each), I recommend the standard library [array](http://docs.python.org/library/array.html?highlight=array#module-array) module as the best way to keep a few millions of them in memory (the "tip" of you...
My own OCR-program in Python
1,989,987
24
2010-01-01T23:14:50Z
1,990,918
7
2010-01-02T07:52:32Z
[ "python", "arrays", "artificial-intelligence", "ocr" ]
I am still a beginner but I want to write a character-recognition-program. This program isn't ready yet. And I edited a lot, therefor the comments may not match exactly. I will use the 8-connectivity for the connected component labeling. ``` from PIL import Image import numpy as np im = Image.open("D:\\Python26\\PYTH...
OCR is very, very hard. Even with computer-generated characters, it's quite challenging if you don't know the font and font size in advance. Even if you're matching characters exactly, I would not call it a "beginning" programming project; it's quite subtle. If you want to recognize scanned, or handwritten characters,...
My own OCR-program in Python
1,989,987
24
2010-01-01T23:14:50Z
1,990,992
31
2010-01-02T08:34:23Z
[ "python", "arrays", "artificial-intelligence", "ocr" ]
I am still a beginner but I want to write a character-recognition-program. This program isn't ready yet. And I edited a lot, therefor the comments may not match exactly. I will use the 8-connectivity for the connected component labeling. ``` from PIL import Image import numpy as np im = Image.open("D:\\Python26\\PYTH...
OCR is not an easy task indeed. That's why text CAPTCHAs still work :) To talk only about the letter extraction and not the pattern recognition, the technique you are using to separate the letters is called [**Connected Component Labeling**](http://en.wikipedia.org/wiki/Connected_component_labeling). Since you are ask...
Django: signal when user logs in?
1,990,502
50
2010-01-02T03:19:49Z
1,990,511
11
2010-01-02T03:25:48Z
[ "python", "django", "login", "user", "signals" ]
In my Django app, I need to start running a few periodic background jobs when a user logs in and stop running them when the user logs out, so I am looking for an elegant way to 1. get notified of a user login/logout 2. query user login status From my perspective, the ideal solution would be 1. a signal sent by each ...
One option might be to wrap Django's login/logout views with your own. For example: ``` from django.contrib.auth.views import login, logout def my_login(request, *args, **kwargs): response = login(request, *args, **kwargs) #fire a signal, or equivalent return response def my_logout(request, *args, **kwar...
Django: signal when user logs in?
1,990,502
50
2010-01-02T03:19:49Z
6,109,366
98
2011-05-24T10:58:50Z
[ "python", "django", "login", "user", "signals" ]
In my Django app, I need to start running a few periodic background jobs when a user logs in and stop running them when the user logs out, so I am looking for an elegant way to 1. get notified of a user login/logout 2. query user login status From my perspective, the ideal solution would be 1. a signal sent by each ...
You can use a signal like this (I put mine in models.py) ``` from django.contrib.auth.signals import user_logged_in def do_stuff(sender, user, request, **kwargs): whatever... user_logged_in.connect(do_stuff) ``` See django docs: <https://docs.djangoproject.com/en/dev/ref/contrib/auth/#module-django.con...
How can I schedule a Task to execute at a specific time using celery?
1,990,531
13
2010-01-02T03:37:16Z
1,990,599
20
2010-01-02T04:24:01Z
[ "python", "django", "scheduled-tasks", "celery" ]
I've looked into `PeriodicTask`, but the examples only cover making it recur. I'm looking for something more like `cron`'s ability to say "execute this task every Monday at 1 a.m."
Use ``` YourTask.apply_async(args=[some, args, here], eta=when) ``` And at the end of your task, reschedule it to the next time it should run.
How can I schedule a Task to execute at a specific time using celery?
1,990,531
13
2010-01-02T03:37:16Z
2,116,048
19
2010-01-22T08:54:04Z
[ "python", "django", "scheduled-tasks", "celery" ]
I've looked into `PeriodicTask`, but the examples only cover making it recur. I'm looking for something more like `cron`'s ability to say "execute this task every Monday at 1 a.m."
The recently released version 1.0.3 supports this now, thanks to Patrick Altman! Example: ``` from celery.task.schedules import crontab from celery.decorators import periodic_task @periodic_task(run_every=crontab(hour=7, minute=30, day_of_week="mon")) def every_monday_morning(): print("This runs every Monday mor...
In Python, what does dict.pop(a,b) mean?
1,990,802
38
2010-01-02T06:40:52Z
1,990,818
59
2010-01-02T06:49:51Z
[ "python", "dictionary" ]
``` class a(object): data={'a':'aaa','b':'bbb','c':'ccc'} def pop(self, key, *args): return self.data.pop(key, *args)#what is this mean. b=a() print b.pop('a',{'b':'bbb'}) print b.data ``` `self.data.pop(key, *args)` ←------ why is there a second argument?
The `pop` method of dicts (like `self.data`, i.e. `{'a':'aaa','b':'bbb','c':'ccc'}`, here) takes two arguments -- see [the docs](http://docs.python.org/library/stdtypes.html?highlight=dict.pop#dict.pop) The second argument, `default`, is what `pop` returns if the first argument, `key`, is absent. (If you call `pop` wi...
In Python, what does dict.pop(a,b) mean?
1,990,802
38
2010-01-02T06:40:52Z
1,990,821
13
2010-01-02T06:50:50Z
[ "python", "dictionary" ]
``` class a(object): data={'a':'aaa','b':'bbb','c':'ccc'} def pop(self, key, *args): return self.data.pop(key, *args)#what is this mean. b=a() print b.pop('a',{'b':'bbb'}) print b.data ``` `self.data.pop(key, *args)` ←------ why is there a second argument?
So many questions here. I see at least two, maybe three: * What does pop(a,b) do?/Why are there a second argument? * What is `*args` being used for? --- The first question is trivially answered in the [Python Standard Library](http://docs.python.org/library/stdtypes.html#mapping-types-dict) reference: > pop(key[, d...
Convert a curl POST request to Python only using standard libary
1,990,976
20
2010-01-02T08:27:23Z
1,991,001
23
2010-01-02T08:37:16Z
[ "python", "json", "curl" ]
I would like to convert this curl command to something that I can use in Python for an existing script. ``` curl -u 7898678:X -H 'Content-Type: application/json' \ -d '{"message":{"body":"TEXT"}}' http://sample.com/36576/speak.json ``` TEXT is what i would like to replace with a message generated by the rest of the s...
> I would like this to work with the standard library if possible. The standard library provides [**`urllib`**](http://docs.python.org/library/urllib.html) and **[`httplib`](http://docs.python.org/library/httplib.html)** for working with URLs: ``` >>> import httplib, urllib >>> params = urllib.urlencode({'apple': 1, ...
Convert a curl POST request to Python only using standard libary
1,990,976
20
2010-01-02T08:27:23Z
1,992,894
12
2010-01-02T21:19:03Z
[ "python", "json", "curl" ]
I would like to convert this curl command to something that I can use in Python for an existing script. ``` curl -u 7898678:X -H 'Content-Type: application/json' \ -d '{"message":{"body":"TEXT"}}' http://sample.com/36576/speak.json ``` TEXT is what i would like to replace with a message generated by the rest of the s...
While there are ways to handle [authentication in urllib2](http://www.voidspace.org.uk/python/articles/authentication.shtml), if you're doing Basic Authorization (which means effectively sending the username and password in clear text) then you can do all of what you want with a urllib2.Request and urllib2.urlopen: ``...
Why file writing does not happen when it is suppose to happen in the program flow?
1,991,815
2
2010-01-02T14:53:42Z
1,991,819
8
2010-01-02T14:55:33Z
[ "python" ]
This is not a new problem for me. From C to PERL to Python on Windows Mobile, Windows XP and other Windows versions this problem persists and f\*\*ks my nerves. Now in my latest script it again happens. To be more concrete: I have coded in Python a trivial script. Now the script writes correctly to the file when run f...
Remember what your mom taught you: always flush() (in python, `file_object.flush()` followed by `os.fsync(file_object.fileno())`)
How do I open all files of a certain type in Python and process them?
1,992,657
4
2010-01-02T20:03:26Z
1,992,684
7
2010-01-02T20:12:56Z
[ "python" ]
I'm trying to figure out how to make python go through a directory full of csv files, process each of the files and spit out a text file with a trimmed list of values. In this example, I'm iterating through a CSV with lots of different types of columns but all I really want are the first name, last name, and keyword. ...
The best way is probably to use the shell's globbing ability, or alternatively the glob module of Python. ## Shell (Linux, Unix) Shell: ``` python myapp.py folder/*.csv ``` myapp.py: ``` import sys for filename in sys.argv[1:]: with open(filename) as f: # do something with f ``` ## Windows (Or no she...
python qt raise syntax error
1,992,739
2
2010-01-02T20:32:27Z
1,992,783
8
2010-01-02T20:44:38Z
[ "python", "qt", "qt4", "pyqt4" ]
I have a top level widget that is producing a syntax error in python. raise() on line 15. This is using the python Qt bindings. I know that raise is a python reserved word. I am looking for how to call the Qt "raise()" function with the python bindings. ``` #!/usr/bin/python # simple.py import sys from PyQt4 import...
"raise" is a keyword (reserved word) in Python. So, you can't use it. And PyQt4 certainly doesn't use it as you think, because, well, it's a keyword, so no extension can. It's like you can't use "from" for a variable name (pet peeve: Python doesn't have variables, but I digress...) As a hint, it's also highlighted by ...
How can I force cherrypy to accept a variable number of GET parameters?
1,993,604
12
2010-01-03T01:33:47Z
1,993,801
28
2010-01-03T03:00:23Z
[ "python", "cherrypy" ]
for instance, say I have my cherrypy index module set up like this ``` >>> import cherrypy >>> class test: def index(self, var = None): if var: print var else: print "nothing" index.exposed = True >>> cherrypy.quickstart(test()) ``` If I send mo...
``` def index(self, var=None, **params): ``` or ``` def index(self, **params): ``` 'var2' will be a key in the params dict. In the second example, so will 'var'. Note the other answers which reference the \*args syntax won't work in this case, because CherryPy passes query params as keyword arguments, not positiona...
PNG optimisation tools
1,993,678
10
2010-01-03T02:03:28Z
2,014,051
13
2010-01-06T15:37:40Z
[ "php", "python", "optimization", "png" ]
A while back I used a PNG optimisation service called (I think) "smush it". You fed it a weblink and it returned a zip of all the PNG images with their filesizes nicely, well, smushed... I want to implement a similar optimisation feature as part of my website's image upload process; does anyone know of a pre-existing ...
Execute with PHP this command line tools ``` pngcrush -rem gAMA -rem cHRM -rem iCCP -rem sRGB -brute -l 9 -max -reduce -m 0 -q IMAGE optipng -o7 -q pngout.png pngout pngout.png -q -y -k0 -s0 advpng -z -4 pngout.png > /dev/null ``` * [pngcrush](http://pmt.sourceforge.net/pngcrush) * [OptiPNG](http://optipng.so...
Expanding tuples into arguments
1,993,727
163
2010-01-03T02:22:49Z
1,993,732
302
2010-01-03T02:24:05Z
[ "python", "tuples", "argument-passing" ]
Is there a way to expand a Python tuple into a function - as actual parameters? For example, here `expand()` does the magic: ``` tuple = (1, "foo", "bar") def myfun(number, str1, str2): return (number * 2, str1 + str2, str2 + str1) myfun(expand(tuple)) # (2, "foobar", "barfoo") ``` I know one could define `myf...
`myfun(*tuple)` does **exactly** what you request. Side issue: **don't** use as your identifiers builtin type names such as `tuple`, `list`, `file`, `set`, and so forth -- it's horrible practice and it *will* come back and byte you when you least expect it, so just get into the habit of actively *avoiding* hiding buil...
Expanding tuples into arguments
1,993,727
163
2010-01-03T02:22:49Z
1,993,740
10
2010-01-03T02:28:28Z
[ "python", "tuples", "argument-passing" ]
Is there a way to expand a Python tuple into a function - as actual parameters? For example, here `expand()` does the magic: ``` tuple = (1, "foo", "bar") def myfun(number, str1, str2): return (number * 2, str1 + str2, str2 + str1) myfun(expand(tuple)) # (2, "foobar", "barfoo") ``` I know one could define `myf...
Take a look at [the Python tutorial](http://docs.python.org/tutorial/controlflow.html#more-on-defining-functions) section 4.7.3 and 4.7.4. It talks about passing tuples os arguments. I would also consider using named parameters (and passing a dictionary) over a tuple and passing a sequence. I find the use of positiona...
Expanding tuples into arguments
1,993,727
163
2010-01-03T02:22:49Z
29,138,472
11
2015-03-19T06:31:30Z
[ "python", "tuples", "argument-passing" ]
Is there a way to expand a Python tuple into a function - as actual parameters? For example, here `expand()` does the magic: ``` tuple = (1, "foo", "bar") def myfun(number, str1, str2): return (number * 2, str1 + str2, str2 + str1) myfun(expand(tuple)) # (2, "foobar", "barfoo") ``` I know one could define `myf...
Note that you can also expand part of argument list: ``` myfun(1, *("foo", "bar")) ```
Map list onto dictionary
1,993,840
9
2010-01-03T03:18:13Z
1,993,848
13
2010-01-03T03:23:45Z
[ "python", "list", "functional-programming", "hashtable" ]
Is there a way to map a list onto a dictionary? What I want to do is give it a function that will return the name of a key, and the value will be the original value. For example; ``` somefunction(lambda a: a[0], ["hello", "world"]) => {"h":"hello", "w":"world"} ``` (This isn't a specific example that I want to do, I ...
I don't think a standard function exists that does exactly that, but it's very easy to construct one using the dict builtin and a comprehension: ``` def somefunction(keyFunction, values): return dict((keyFunction(v), v) for v in values) print somefunction(lambda a: a[0], ["hello", "world"]) ``` Output: ``` {'h'...
Map list onto dictionary
1,993,840
9
2010-01-03T03:18:13Z
1,994,012
15
2010-01-03T04:45:12Z
[ "python", "list", "functional-programming", "hashtable" ]
Is there a way to map a list onto a dictionary? What I want to do is give it a function that will return the name of a key, and the value will be the original value. For example; ``` somefunction(lambda a: a[0], ["hello", "world"]) => {"h":"hello", "w":"world"} ``` (This isn't a specific example that I want to do, I ...
In Python 3 you can use this dictionary comprehension syntax: ``` def foo(somelist): return {x[0]:x for x in somelist} ```
How safe is expression evaluation using eval?
1,994,071
3
2010-01-03T05:23:19Z
1,994,145
7
2010-01-03T06:14:40Z
[ "python", "security", "eval" ]
I am building a website where I have a need that user should be able to evaluate some expression based from the value in DB tables, instead of using tools like pyparsing etc, I am thinking of using python itself, and have come up with a solution which is sufficient for my purpose. I am basically using eval to evaluate ...
It's completely unsafe to use `eval`, even with built-ins emptied and blocked -- the attacker can start with a literal, get its `__class__`, etc, etc, up to `object`, its `__subclasses__`, and so forth... basically, Python introspection is just too strong to stand up to a skilled, determined attacker. [`ast.literal_ev...
python, and unicode stderr
1,994,157
2
2010-01-03T06:21:21Z
2,001,767
8
2010-01-04T19:54:37Z
[ "python", "unicode", "stderr" ]
I used an anonymous pipe to capture all stdout,and stderr then print into a richedit, it's ok when i use wsprintf ,but the python using multibyte char that really annoy me. how can I convert all these output to unicode? **UPDATE 2010-01-03:** Thank you for the reply, but it seems the `str.encode()` only worked with `...
First, please remember that on Windows console may not fully support Unicode. The example below does make python output to `stderr` and `stdout` using **UTF-8**. If you want you could change it to other encodings. ``` #!/usr/bin/python # -*- coding: UTF-8 -*- import codecs, sys reload(sys) sys.setdefaultencoding('u...
Copy file or directory in Python
1,994,488
71
2010-01-03T10:06:42Z
1,994,840
88
2010-01-03T12:35:25Z
[ "python" ]
Python seems to have functions for copying files (e.g. shutil.copy) and functions for copying directories (e.g. shutil.copytree) but I haven't found any function that handles both. Sure, it's trivial to check whether you want to copy a file or a directory, but it seems like a strange omission. Is there really no stand...
I suggest you first call `shutil.copytree`, and if an exception is thrown, then retry with `shutil.copy`. ``` import shutil, errno def copyanything(src, dst): try: shutil.copytree(src, dst) except OSError as exc: # python >2.5 if exc.errno == errno.ENOTDIR: shutil.copy(src, dst) ...
Fast way to read filename from directory?
1,994,549
2
2010-01-03T10:29:55Z
1,994,557
10
2010-01-03T10:31:59Z
[ "python", "path" ]
Given a local directory structure of `/foo/bar`, and assuming that a given path contains exactly one file (filename and content does not matter), what is a reasonably fast way to get the filename of that single file (NOT the file content)?
1st element of [`os.listdir()`](http://docs.python.org/library/os.html#os.listdir) ``` import os os.listdir('/foo/bar')[0] ```
Which programming languages can I use on Android Dalvik?
1,994,703
54
2010-01-03T11:35:32Z
1,994,892
24
2010-01-03T12:57:48Z
[ "java", "python", "android", "scala", "dalvik" ]
In theory, Dalvik executes any virtual machine byte code, created for example with the compilers of * AspectJ * ColdFusion * Clojure * Groovy * JavaFX Script * JRuby * Jython * Rhino * Scala Are there already working versions of bytecode compilers for Dalvik available for other languages than Java?
Scala works very well. I'm programming my Android application projects in Scala ([Website written in Chinese with some screenshot](http://bone.twbbs.org.tw/maidroid/MaidroidReminder), [source code @ GitHub](http://github.com/brianhsu/Maidroid/tree/master/MaidroidReminder/)), and it is pretty easy to setup the evnvirom...
Which programming languages can I use on Android Dalvik?
1,994,703
54
2010-01-03T11:35:32Z
3,323,834
59
2010-07-24T04:37:22Z
[ "java", "python", "android", "scala", "dalvik" ]
In theory, Dalvik executes any virtual machine byte code, created for example with the compilers of * AspectJ * ColdFusion * Clojure * Groovy * JavaFX Script * JRuby * Jython * Rhino * Scala Are there already working versions of bytecode compilers for Dalvik available for other languages than Java?
* At launch, `Java` was the only officially supported programming language for building distributable third-party Android software. * Android Native Development Kit (Android NDK) which will allow developers to build Android software components with `C` and `C++`. * In addition to delivering support for native code, Goo...
Getting a large number (but not all) Wikipedia pages
1,995,008
4
2010-01-03T13:46:59Z
1,995,015
23
2010-01-03T13:49:43Z
[ "python", "algorithm", "wikipedia" ]
For a [NLP](http://en.wikipedia.org/wiki/Natural_language_processing) project of mine, I want to download a large number of pages (say, 10000) at random from Wikipedia. Without downloading the entire XML dump, this is what I can think of: 1. Open a Wikipedia page 2. Parse the HTML for links in a Breadth First Search f...
``` for i = 1 to 10000 get "http://en.wikipedia.org/wiki/Special:Random" ```
Getting a large number (but not all) Wikipedia pages
1,995,008
4
2010-01-03T13:46:59Z
1,995,026
20
2010-01-03T13:52:34Z
[ "python", "algorithm", "wikipedia" ]
For a [NLP](http://en.wikipedia.org/wiki/Natural_language_processing) project of mine, I want to download a large number of pages (say, 10000) at random from Wikipedia. Without downloading the entire XML dump, this is what I can think of: 1. Open a Wikipedia page 2. Parse the HTML for links in a Breadth First Search f...
Wikipedia has an [API](http://en.wikipedia.org/w/api.php). With this API you can get any random article in a given namespace: ``` http://en.wikipedia.org/w/api.php?action=query&list=random&rnnamespace=0&rnlimit=5 ``` and for each article you call also get the wiki text: ``` http://en.wikipedia.org/w/api.php?action=q...
Creating an FTP client with Python
1,995,046
3
2010-01-03T13:59:45Z
1,995,065
7
2010-01-03T14:05:59Z
[ "python", "ftp" ]
I've always thought about creating my own ftp client ever since I've started using the Internet. And now that I'm studying Python, I'm thinking about creating one as an exercises/personal project. I'm wondering, * What libraries do you guys suggest? Will `ftplib` suffice? Or would you suggest another library(preferab...
It sounds like you want to make a program that has a GUI. May I recommend using **PyQt** for that part of your application? **ftplib** should be fine for your FTP support, and you can find documentation [right here](http://docs.python.org/3.1/library/ftplib.html). Alternatively for FTP support, you can use the **QFtp*...
Deleting all files in a directory with Python
1,995,373
102
2010-01-03T15:58:20Z
1,995,397
179
2010-01-03T16:02:54Z
[ "python", "file-io" ]
I want to delete all files with the extension `.bak` in a directory. How can I do that in Python?
Via [`os.listdir`](https://docs.python.org/2/library/os.html#os.listdir) and [`os.remove`](https://docs.python.org/2/library/os.html#os.remove): ``` import os filelist = [ f for f in os.listdir(".") if f.endswith(".bak") ] for f in filelist: os.remove(f) ``` Or via [`glob.glob`](https://docs.python.org/3/library...
Deleting all files in a directory with Python
1,995,373
102
2010-01-03T15:58:20Z
1,995,410
21
2010-01-03T16:06:33Z
[ "python", "file-io" ]
I want to delete all files with the extension `.bak` in a directory. How can I do that in Python?
Use `os.chdir` to change directory . Use `glob.glob` to generate a list of file names which end it '.bak'. The elements of the list are just strings. Then you could use `os.unlink` to remove the files. (PS. `os.unlink` and `os.remove` are synonyms for the same function.) ``` #!/usr/bin/env python import glob import o...
Python: generator expression vs. yield
1,995,418
68
2010-01-03T16:09:26Z
1,995,425
7
2010-01-03T16:13:13Z
[ "python", "yield", "generator" ]
In Python, is there any difference between creating a generator object through a **generator expression** versus using the **yield** statement? Using *yield*: ``` def Generator(x, y): for i in xrange(x): for j in xrange(y): yield(i, j) ``` Using *generator expression*: ``` def Generator(x, y...
Using `yield` is nice if the expression is more complicated than just nested loops. Among other things you can return a special first or special last value. Consider: ``` def Generator(x): for i in xrange(x): yield(i) yield(None) ```
Python: generator expression vs. yield
1,995,418
68
2010-01-03T16:09:26Z
1,995,427
32
2010-01-03T16:13:33Z
[ "python", "yield", "generator" ]
In Python, is there any difference between creating a generator object through a **generator expression** versus using the **yield** statement? Using *yield*: ``` def Generator(x, y): for i in xrange(x): for j in xrange(y): yield(i, j) ``` Using *generator expression*: ``` def Generator(x, y...
In this example, not really. But `yield` can be used for more complex constructs - [for example](http://eli.thegreenplace.net/2009/08/29/co-routines-as-an-alternative-to-state-machines/) it can accept values from the caller as well and modify the flow as a result. Read [PEP 342](http://www.python.org/dev/peps/pep-0342/...
Python: generator expression vs. yield
1,995,418
68
2010-01-03T16:09:26Z
1,995,465
15
2010-01-03T16:30:39Z
[ "python", "yield", "generator" ]
In Python, is there any difference between creating a generator object through a **generator expression** versus using the **yield** statement? Using *yield*: ``` def Generator(x, y): for i in xrange(x): for j in xrange(y): yield(i, j) ``` Using *generator expression*: ``` def Generator(x, y...
There is no difference for the kind of simple loops that you can fit into a generator expression. However yield can be used to create generators that do much more complex processing. Here is a simple example for generating the fibonacci sequence: ``` >>> def fibgen(): ... a = b = 1 ... while 1: ... yield ...
Python: generator expression vs. yield
1,995,418
68
2010-01-03T16:09:26Z
1,995,585
60
2010-01-03T17:17:12Z
[ "python", "yield", "generator" ]
In Python, is there any difference between creating a generator object through a **generator expression** versus using the **yield** statement? Using *yield*: ``` def Generator(x, y): for i in xrange(x): for j in xrange(y): yield(i, j) ``` Using *generator expression*: ``` def Generator(x, y...
There are only slight differences in the two. You can use the `dis` module to examine this sort of thing for yourself. **Edit:** My first version decompiled the generator expression created at module-scope in the interactive prompt. That's slightly different from the OP's version with it used inside a function. I've m...
Python: generator expression vs. yield
1,995,418
68
2010-01-03T16:09:26Z
2,047,130
7
2010-01-12T06:26:29Z
[ "python", "yield", "generator" ]
In Python, is there any difference between creating a generator object through a **generator expression** versus using the **yield** statement? Using *yield*: ``` def Generator(x, y): for i in xrange(x): for j in xrange(y): yield(i, j) ``` Using *generator expression*: ``` def Generator(x, y...
In usage, note a distinction between a generator object vs a generator function. A generator object is use-once-only, in contrast to a generator function, which can be reused each time you call it again, because it returns a fresh generator object. Generator expressions are in practice usually used "raw", without wra...
How can I turn 000000000001 into 1?
1,995,602
4
2010-01-03T17:26:13Z
1,995,609
11
2010-01-03T17:29:26Z
[ "python", "parsing", "integer" ]
I need to turn a formatted integer into a regular integer: * 000000000001 needs to be turned into 1 * 000000000053 needs to be turned into 53 * 000000965948 needs to be turned into 965948 And so on. It seems that a simple `int(000000000015)` results in the number 13. I understand there is some weird stuff behind the...
Numbers starting with `0` are considered [octal](http://en.wikipedia.org/wiki/Octal). ``` >>> 07 7 >>> 08 File "<stdin>", line 1 08 ^ SyntaxError: invalid token ``` You can wrap your zero-padded number into a string, then it should work. ``` >>> int("08") 8 ``` `int()` takes an optional argument, which is...
How can I turn 000000000001 into 1?
1,995,602
4
2010-01-03T17:26:13Z
1,995,616
8
2010-01-03T17:30:54Z
[ "python", "parsing", "integer" ]
I need to turn a formatted integer into a regular integer: * 000000000001 needs to be turned into 1 * 000000000053 needs to be turned into 53 * 000000965948 needs to be turned into 965948 And so on. It seems that a simple `int(000000000015)` results in the number 13. I understand there is some weird stuff behind the...
The leading zeroes are considered octal. I am assuming that you are converting the string "000000013", not literal 000000013, so you should be able to convert these to base 10 integer by `int("000000013",10)` If the "harm has already been done", and they are literals, that have already been converted to octal literals...
How can I format a decimal to always show 2 decimal places?
1,995,615
91
2010-01-03T17:30:44Z
1,995,632
103
2010-01-03T17:35:29Z
[ "python", "string-formatting" ]
I want to display: `49` as `49.00` and: `54.9` as `54.90` Regardless of the length of the decimal or whether there are are any decimal places, I would like to display a `Decimal` with 2 decimal places, and I'd like to do it in an efficient way. The purpose is to display money values. eg, `4898489.00`
The [String Formatting Operations](https://docs.python.org/2/library/stdtypes.html#string-formatting) section of the Python documentation contains the answer you're looking for. In short: ``` "%0.2f" % (num,) ``` Some examples: ``` >>> "%0.2f" % 10 '10.00' >>> "%0.2f" % 1000 '1000.00' >>> "%0.2f" % 10.1 '10.10' >>> ...
How can I format a decimal to always show 2 decimal places?
1,995,615
91
2010-01-03T17:30:44Z
1,995,634
21
2010-01-03T17:35:59Z
[ "python", "string-formatting" ]
I want to display: `49` as `49.00` and: `54.9` as `54.90` Regardless of the length of the decimal or whether there are are any decimal places, I would like to display a `Decimal` with 2 decimal places, and I'd like to do it in an efficient way. The purpose is to display money values. eg, `4898489.00`
You can use the [string formatting operator](https://docs.python.org/2/library/stdtypes.html#string-formatting "string formatting operator") as so: ``` num = 49 x = "%.2f" % num # x is now the string "49.00" ``` I'm not sure what you mean by "efficient" -- this is almost certainly *not* the bottleneck of your applic...
How can I format a decimal to always show 2 decimal places?
1,995,615
91
2010-01-03T17:30:44Z
1,995,846
55
2010-01-03T18:43:52Z
[ "python", "string-formatting" ]
I want to display: `49` as `49.00` and: `54.9` as `54.90` Regardless of the length of the decimal or whether there are are any decimal places, I would like to display a `Decimal` with 2 decimal places, and I'd like to do it in an efficient way. The purpose is to display money values. eg, `4898489.00`
I suppose you're probably using the [`Decimal()`](https://docs.python.org/2/library/decimal.html#decimal-objects) objects from the [`decimal`](https://docs.python.org/2/library/decimal.html) module? (If you need exactly two digits of precision beyond the decimal point with arbitrarily large numbers, you definitely shou...
How can I format a decimal to always show 2 decimal places?
1,995,615
91
2010-01-03T17:30:44Z
8,940,627
198
2012-01-20T11:20:54Z
[ "python", "string-formatting" ]
I want to display: `49` as `49.00` and: `54.9` as `54.90` Regardless of the length of the decimal or whether there are are any decimal places, I would like to display a `Decimal` with 2 decimal places, and I'd like to do it in an efficient way. The purpose is to display money values. eg, `4898489.00`
You should use the [new format specifications](https://docs.python.org/2/library/string.html#format-specification-mini-language) to define how your value should be represented: ``` >>> from math import pi # pi ~ 3.141592653589793 >>> '{0:.2f}'.format(pi) '3.14' ``` The documentation can be a bit obtuse at times, so ...
How can I format a decimal to always show 2 decimal places?
1,995,615
91
2010-01-03T17:30:44Z
34,916,765
8
2016-01-21T06:26:41Z
[ "python", "string-formatting" ]
I want to display: `49` as `49.00` and: `54.9` as `54.90` Regardless of the length of the decimal or whether there are are any decimal places, I would like to display a `Decimal` with 2 decimal places, and I'd like to do it in an efficient way. The purpose is to display money values. eg, `4898489.00`
.format is a more readable way to handle variable formatting: ``` '{:.{prec}f}'.format(26.034, prec=2) ```
How are exceptions implemented under the hood?
1,995,734
56
2010-01-03T18:06:17Z
1,995,748
17
2010-01-03T18:11:41Z
[ "c++", "python", "c", "exception" ]
Just about everyone uses them, but many, including me simply take it for granted that they just work. I am looking for high-quality material. Languages I use are: Java, C, C#, Python, C++, so these are of most interest to me. Now, C++ is probably a good place to start since you can throw anything in that language. A...
In his book *C Interfaces and Implementations: Techniques for Creating Reusable Software*, D. R. Hanson provides a nice implementation of exceptions in pure C using a set of macros and `setjmp/longjmp`. He provides TRY/RAISE/EXCEPT/FINALLY macros that can emulate pretty much everything C++ exceptions do and more. The ...
How are exceptions implemented under the hood?
1,995,734
56
2010-01-03T18:06:17Z
1,995,762
7
2010-01-03T18:14:19Z
[ "c++", "python", "c", "exception" ]
Just about everyone uses them, but many, including me simply take it for granted that they just work. I am looking for high-quality material. Languages I use are: Java, C, C#, Python, C++, so these are of most interest to me. Now, C++ is probably a good place to start since you can throw anything in that language. A...
C/C++ compilers use the underlying OS facilities for exception handling. Frameworks like .Net or Java also rely, in the VM, on the OS facilities. In Windows for instance, the real heavy lifting is done by SEH, the Structured Exception Handling infrastructure. You should absolutely read the old reference article: [A Cra...
How are exceptions implemented under the hood?
1,995,734
56
2010-01-03T18:06:17Z
1,995,778
20
2010-01-03T18:18:44Z
[ "c++", "python", "c", "exception" ]
Just about everyone uses them, but many, including me simply take it for granted that they just work. I am looking for high-quality material. Languages I use are: Java, C, C#, Python, C++, so these are of most interest to me. Now, C++ is probably a good place to start since you can throw anything in that language. A...
Here is a common way C++ exceptions are implemented: <http://www.codesourcery.com/public/cxx-abi/abi-eh.html> It is for the Itanium architecture, but the implementation described here is used in other architectures as well. Note that it is a long document, since C++ exceptions are complicated. Here is a good descri...
How are exceptions implemented under the hood?
1,995,734
56
2010-01-03T18:06:17Z
1,995,979
33
2010-01-03T19:24:44Z
[ "c++", "python", "c", "exception" ]
Just about everyone uses them, but many, including me simply take it for granted that they just work. I am looking for high-quality material. Languages I use are: Java, C, C#, Python, C++, so these are of most interest to me. Now, C++ is probably a good place to start since you can throw anything in that language. A...
Exceptions are just a specific example of a more general case of advanced non-local flow control constructs. Other examples are: * *notifications* (a generalization of exceptions, originally from some old Lisp object system, now implemented in e.g. CommonLisp and Ioke), * *continuations* (a more structured form of `GO...
applying image decoration (border) in Python (programatically)
1,995,772
4
2010-01-03T18:16:41Z
1,996,250
7
2010-01-03T20:49:58Z
[ "python", "image", "image-processing" ]
I am looking for a way to create a border in python.Is there any library in Python which we can import to create a border. Note that I do not want to use any image masks to create this effect (e.g. I don't want to use any image editing package like GIMP to create a border image mask) . Here is what I am looking for: ...
Look at the [ImageOps](http://www.pythonware.com/library/pil/handbook/imageops.htm) module within the PIL. ``` import Image import ImageOps x = Image.open('test.png') y = ImageOps.expand(x,border=5,fill='red') y.save('test2.png') ```
Find out 20th, 30th, nth prime number. (I'm getting 20th but not 30th?) [Python]
1,995,890
6
2010-01-03T18:57:36Z
1,996,092
8
2010-01-03T19:54:41Z
[ "python", "primes" ]
The question is to find the 1000th prime number. I wrote the following python code for this. The problem is, I get the right answer for the 10th , 20th prime but after that each increment of 10 leaves me one off the mark. I can't catch the bug here :( ``` count=1 #to keep count of prime numbers primes=() ...
There is a nice [Sieve of Eratosthenes](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) generator implementation in test\_generators.py: ``` def intsfrom(i): while 1: yield i i += 1 def firstn(g, n): return [g.next() for i in range(n)] def exclude_multiples(n, ints): for i in int...
Wildcard matching a string in Python regex search
1,996,482
4
2010-01-03T21:55:48Z
1,996,499
7
2010-01-03T22:02:11Z
[ "python", "regex" ]
I thought I would write some quick code to download the number of "fans" a Facebook page has. For some reason, despite a fair number of iterations I've tried, I can't get the following code to pick out the number of fans in the HTML. None of the other solutions I found on the web correctly match the regex in this case...
``` import urllib import re fbhandle = urllib.urlopen('http://www.facebook.com/Microsoft') pattern = "6 of(.*)fans" #this wild card doesnt appear to work? compiled = re.compile(pattern) ms = compiled.search(fbhandle.read()) print ms.group(1).strip() fbhandle.close() ``` You needed to use `re.search()` instead. Using...
Wildcard matching a string in Python regex search
1,996,482
4
2010-01-03T21:55:48Z
1,997,016
8
2010-01-04T01:03:01Z
[ "python", "regex" ]
I thought I would write some quick code to download the number of "fans" a Facebook page has. For some reason, despite a fair number of iterations I've tried, I can't get the following code to pick out the number of fans in the HTML. None of the other solutions I found on the web correctly match the regex in this case...
Evan Fosmark already gave a good answer. This is just more info. You have this line: ``` pattern = "6 of(.*)fans" ``` In general, this isn't a good regular expression. If the input text was: "6 of 99 fans in the whole galaxy of fans" Then the match group (the stuff inside the parentheses) would be: " 99 fans in t...
Python string function isidentifier()
1,996,517
2
2010-01-03T22:07:05Z
1,996,522
9
2010-01-03T22:09:02Z
[ "python", "string" ]
I'm working through a Python 3 book and came across the string function isidentifier(). The text description is "s.isidentifier() : Returns True if s is non empty and is a valid identifier". I tested it in the Python Shell like this: ``` >>> s = 'test' >>> s.isidentifier() True >>> 'blah'.isidentifier() True ``` I wo...
> Returns True if s is non empty and is a **valid** identifier. What they mean is that s *could* be valid as an identifier. It doesn't imply that it is an identifier that's in use. Your first example is showing the same thing: 'test' (what `isidentifier` is actually checking) is not the name of a variable either. I t...
Retrieving the output of subprocess.call()
1,996,518
121
2010-01-03T22:07:05Z
1,996,540
81
2010-01-03T22:13:40Z
[ "python", "pipe", "subprocess", "stringio" ]
How can I get the output of a process run using subprocess.call()? Passing a StringIO.StringIO object to stdout gives this error: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 444, in call r...
Output from `subprocess.call()` should only be redirected to files. You should use `subprocess.Popen()` instead. Then you can pass `subprocess.PIPE` for the stderr, stdout, and/or stdin parameters and read from the pipes by using the `communicate()` method: ``` from subprocess import Popen, PIPE p = Popen(['program'...
Retrieving the output of subprocess.call()
1,996,518
121
2010-01-03T22:07:05Z
3,247,271
22
2010-07-14T14:42:34Z
[ "python", "pipe", "subprocess", "stringio" ]
How can I get the output of a process run using subprocess.call()? Passing a StringIO.StringIO object to stdout gives this error: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 444, in call r...
I recently just figured out how to do this, and here's some example code from a current project of mine: ``` #Getting the random picture. #First find all pictures: import shlex, subprocess cmd = 'find ../Pictures/ -regex ".*\(JPG\|NEF\|jpg\)" ' #cmd = raw_input("shell:") args = shlex.split(cmd) output,error = subproce...
Retrieving the output of subprocess.call()
1,996,518
121
2010-01-03T22:07:05Z
8,700,414
115
2012-01-02T11:45:57Z
[ "python", "pipe", "subprocess", "stringio" ]
How can I get the output of a process run using subprocess.call()? Passing a StringIO.StringIO object to stdout gives this error: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 444, in call r...
If you have Python version >= 2.7, you can use [subprocess.check\_output](http://docs.python.org/library/subprocess.html#subprocess.check_output) which basically does exactly what you want (it returns standard output as string). As commented below you can find sample code and a more detailed explanation in [this other...
Retrieving the output of subprocess.call()
1,996,518
121
2010-01-03T22:07:05Z
21,000,308
26
2014-01-08T15:50:06Z
[ "python", "pipe", "subprocess", "stringio" ]
How can I get the output of a process run using subprocess.call()? Passing a StringIO.StringIO object to stdout gives this error: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 444, in call r...
I have the following solution. It captures the exit code, the stdout, and the stderr too of the executed external command: ``` import shlex from subprocess import Popen, PIPE def get_exitcode_stdout_stderr(cmd): """ Execute the external command and get its exitcode, stdout and stderr. """ args = shlex...
Retrieving the output of subprocess.call()
1,996,518
121
2010-01-03T22:07:05Z
34,873,354
7
2016-01-19T09:44:30Z
[ "python", "pipe", "subprocess", "stringio" ]
How can I get the output of a process run using subprocess.call()? Passing a StringIO.StringIO object to stdout gives this error: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 444, in call r...
For python 3.5+ it is recommended that you use the [run function from the subprocess module](https://docs.python.org/3/library/subprocess.html#subprocess.run). This returns a `CompletedProcess` object, from which you can easily obtain the output as well as return code. ``` from subprocess import PIPE, run command = [...
How can I get the depth of a jpg file?
1,996,577
4
2010-01-03T22:24:09Z
1,996,609
7
2010-01-03T22:35:40Z
[ "python", "jpeg", "imaging" ]
I want to retrieve the bit depth for a jpeg file using Python. Using the Python Imaging Library: ``` import Image data = Image.open('file.jpg') print data.depth ``` However, this gives me a depth of 8 for an obviously 24-bit image. Am I doing something wrong? Is there some way to do it with pure Python code? Thanks...
I don't see the `depth` attribute documented anywhere in the [Python Imaging Library handbook](http://www.pythonware.com/library/pil/handbook/index.htm). However, it looks like only a limited number of [modes](http://www.pythonware.com/library/pil/handbook/concepts.htm) are supported. You could use something like this:...
How to get something to appear on every page in Django?
1,997,109
3
2010-01-04T01:38:00Z
1,997,127
16
2010-01-04T01:43:48Z
[ "python", "django" ]
I'm curious as to the best-practise way to handle having something appear on every page, or on a number of pages without having to assign the data manually to every page like so: ``` # views.py def page0(request): return render_to_response( "core/index.html", { "locality": getCityForm(...
You want a [context processor](http://www.b-list.org/weblog/2006/jun/14/django-tips-template-context-processors/). The data they generate is included in every context created as a `RequestContext`. They are perfect for this. Combined with base templates that show common things, you can get rid of lots of need for copy...
Find which python modules are being imported
1,997,449
33
2010-01-04T04:01:56Z
1,997,461
29
2010-01-04T04:07:10Z
[ "python", "package" ]
What's an easy way of finding all the python modules from a particular package that are being used in an application?
`sys.modules` is a dictionary mapping module names to modules. You can examine its keys to see imported modules.
Find which python modules are being imported
1,997,449
33
2010-01-04T04:01:56Z
1,997,465
27
2010-01-04T04:09:47Z
[ "python", "package" ]
What's an easy way of finding all the python modules from a particular package that are being used in an application?
You could use `python -v`, which will emit messages about *every* imported module: ``` $ echo 'print "hello world"' > helo.py $ python -v helo.py # installing zipimport hook import zipimport # builtin # installed zipimport hook # /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site.pyc matches /...
Faster method of reading screen pixel in Python than PIL?
1,997,678
7
2010-01-04T05:41:27Z
1,997,875
11
2010-01-04T06:45:54Z
[ "python", "windows", "winapi", "directx", "python-imaging-library" ]
Currently I'm using a pixel reader via AutoItv3 to perform some actions in a program that is running direct X; A game. Right now the program works fine but as an exercise I've been rewriting it in python. Right now I can do: ``` import ImageGrab # Part of PIL image = ImageGrab.grab() #Define an area to capture. ...
This is the PIL's grabscreen source, Its does not accept any parameters, and Its grab the whole screen and convert it to bitmap. ``` PyImaging_GrabScreenWin32(PyObject* self, PyObject* args) { int width, height; HBITMAP bitmap; BITMAPCOREHEADER core; HDC screen, screen_copy; PyObject* buffer; ...
Faster method of reading screen pixel in Python than PIL?
1,997,678
7
2010-01-04T05:41:27Z
1,998,663
7
2010-01-04T10:25:21Z
[ "python", "windows", "winapi", "directx", "python-imaging-library" ]
Currently I'm using a pixel reader via AutoItv3 to perform some actions in a program that is running direct X; A game. Right now the program works fine but as an exercise I've been rewriting it in python. Right now I can do: ``` import ImageGrab # Part of PIL image = ImageGrab.grab() #Define an area to capture. ...
Comment on S.Mark's solution: user32 library is already loaded by windll into windll.user32, so instead of the dc = ... line you can do: ``` def getpixel(x,y): return gdi.GetPixel(windll.user32.GetDC(0),x,y) ``` ...or preferably: ``` dc= windll.user32.GetDC(0) ```
Alternative pygame resources
1,997,679
3
2010-01-04T05:41:35Z
1,997,724
16
2010-01-04T05:54:31Z
[ "python", "pygame" ]
I have been trying to access the pygame website for a few weeks now, and I can't get to it. I doubt it's down, so I have to conclude that it's blocked because I am in China. I have no idea why. Anyways, I want the pygame documentation, but all the download links I fond lead back to pygame.org (which I does not even beg...
I'll upload the pygame source here <http://www.cse.unsw.edu.au/~cma/pygame-1.9.1release.zip> Unzip it and there's a folder called 'docs' all the documentation is in there.
Pygame error: display surface quit: Why?
1,997,710
2
2010-01-04T05:49:03Z
4,317,744
9
2010-11-30T19:37:39Z
[ "python", "pygame", "documentation" ]
Sorry if this question is dumb, but I am writing from China and for some unfathomable reason a lot of websites having to do with pygame are blocked. I can't access pygame.org, I have not been able to download the docs or even look at message boards having to do with pygame! WEIRD! Anyways, I am a pygame newb and I nee...
I had similar problem and discovered that Surface objects don't like to be deepcopied. When I used copy.deepcopy() on such object and then accessed the copy, I got that strange error message (without calling pygame.quit()). Maybe you experience similar behavior?
Python's mechanize proxy support
1,997,894
9
2010-01-04T06:51:05Z
1,997,950
30
2010-01-04T07:11:59Z
[ "python", "mechanize" ]
I have a question about python mechanize's proxy support. I'm making some web client script, and I would like to insert proxy support function into my script. For example, if I have: ``` params = urllib.urlencode({'id':id, 'passwd':pw}) rq = mechanize.Request('http://www.example.com', params) rs = mechanize.urlopen(...
I'm not sure whether that help or not but you can set proxy settings on [mechanize](http://wwwsearch.sourceforge.net/mechanize/) proxy browser. ``` br = Browser() # Explicitly configure proxies (Browser will attempt to set good defaults). # Note the userinfo ("joe:password@") and port number (":3128") are optional. br...
Python's mechanize proxy support
1,997,894
9
2010-01-04T06:51:05Z
2,519,023
9
2010-03-25T20:14:16Z
[ "python", "mechanize" ]
I have a question about python mechanize's proxy support. I'm making some web client script, and I would like to insert proxy support function into my script. For example, if I have: ``` params = urllib.urlencode({'id':id, 'passwd':pw}) rq = mechanize.Request('http://www.example.com', params) rs = mechanize.urlopen(...
You use mechanize.Request.set\_proxy(host, type) (at least as of 0.1.11) assuming an http proxy running at localhost:8888 ``` req = mechanize.Request("http://www.google.com") req.set_proxy("localhost:8888","http") mechanize.urlopen(req) ``` Should work.
Is it safe to use user input for Python's regular expressions?
1,998,104
14
2010-01-04T07:58:14Z
1,998,507
17
2010-01-04T09:48:05Z
[ "python", "regex", "user-input", "sanitize" ]
I would like to let my users use regular expressions for some features. I'm curious what the implications are of passing user input to re.compile(). I assume there is no way for a user to give me a string that could let them execute arbitrary code. The dangers I have thought of are: 1. The user could pass input that r...
I have worked on a program that allows users to enter their own regex and you are right - they can (and do) enter regex that can take a long time to finish - sometimes longer than than the lifetime of the universe. What is worse, while processing a regex Python holds the GIL, so it will not only hang the thread that is...
wiki/docbook/latex documentation template system
1,998,677
6
2010-01-04T10:28:17Z
1,998,811
7
2010-01-04T10:52:35Z
[ "python", "html", "latex", "documentation-generation", "docbook" ]
I'm searching for a documentation template system or rather will be creating one. It should support the following features: * Create output in PDF and HTML * Support for large & complicated (LaTeX) formulas * References between documents * Bibliographies * Templates will be filled by a Python script I've tried LaTeX ...
We use sphinx: <http://sphinx.pocoo.org> It does almost all of that. Your python script or your users or whomever (I can't follow the question) can create content using [RST markup](http://docutils.sourceforge.net/rst.html) (which is perhaps the easiest of markup languages). You run it through Sphinx and you get HTML...
Why does it print funny characters? unicode problem?
1,998,967
2
2010-01-04T11:26:35Z
1,998,976
8
2010-01-04T11:29:26Z
[ "python", "django", "unicode", "encoding" ]
The user entered the word ``` éclair ``` into the search box. ``` Showing results 1 - 10 of about 140 for �air. ``` Why does it show the weird question mark? I'm using Django to display it: ``` Showing results 1 - 10 of about 140 for {{query|safe}} ```
It's an encoding problem. Most likely your form or the output page is not UTF-8 encoded. This article is *very* good reading on the issue: [The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)](http://www.joelonsoftware.com/articles/Unicode.html)...
Create single python executable module
1,999,129
6
2010-01-04T12:02:23Z
1,999,402
10
2010-01-04T13:02:00Z
[ "python", "linux", "winapi", "executable" ]
Guys, I have much python code in modules which are resides in several python packages and now I need to create single python executable module or file which will include all these files, so it will be working on windows and on linux servers. What are possible solutions and how this can be done?
For windows use [py2exe](http://www.py2exe.org/) , for linux use [pyinstaller](http://www.pyinstaller.org/) and for Mac use [py2app](http://svn.pythonmac.org/py2app/py2app/trunk/doc/index.html) Using these tools you can have a `setup.py` which based on os will build the final binary. I have tried all three and they w...
Creating equivalent classes in Python?
1,999,551
3
2010-01-04T13:30:43Z
1,999,575
10
2010-01-04T13:36:47Z
[ "python" ]
I played around with overloading or masking classes in Python. Do the following code examples create equivalent classes? ``` class CustASample(object): def __init__(self): self.__class__.__name__ = "Sample" def doSomething(self): dummy = 1 ``` and ``` class Sample(object): def doSomethin...
No, they are still different. ``` a = CustASample() b = Sample() a.__class__ is b.__class__ -> False ``` Here's how you could do it: ``` class A(object): def __init__(self): self.__class__ = B class B(object): def bark(self): print "Wuff!" a = A() b = B() a.__class__ is b.__class__ -> True ...
How to print context content in the template?
1,999,811
3
2010-01-04T14:22:58Z
1,999,998
7
2010-01-04T14:53:08Z
[ "python", "django" ]
How can I print or iterate over all the variables available in the context from the template code? I know about `{% debug %}` but it contains too much information. I'd just like to print variable names available in the current context. Is there a way to do this without writing custom tag?
Use the [Django debug toolbar](https://github.com/django-debug-toolbar/django-debug-toolbar) - gives you this on the Templates tab, along a whole range of other useful debugging information.
Does Django need an IDE?
2,000,631
9
2010-01-04T16:39:16Z
2,001,956
8
2010-01-04T20:21:12Z
[ "python", "django" ]
My company is evaluating the possibility of developing a specialized IDE for Django. So we would like to ask Django users: * Do you feel the need for a specialized IDE for Django? * Would you be willing to pay for it, or would you only consider free a open-source product? * What Django-specific features are you missi...
I would pay a reasonable amount for a Django-tailored IDE or plug-in. I don't know what I mean by reasonable, but maye it helps to know that I would not pay more than $75, and I would only pay the $75 if the tool was really awesome. Now, Django specific features: * Seamless integration with Google Apps (get me the ...
How to create dynamical scoped variables in Python?
2,001,138
10
2010-01-04T18:09:52Z
2,001,797
10
2010-01-04T19:57:32Z
[ "python", "variables", "lisp", "scope", "dynamic-scope" ]
I am translating some code from lisp to Python. In lisp, you can have a let construct with the variables introduced declared as special and thus having dynamic scope. (See <http://en.wikipedia.org/wiki/Dynamic_scope#Dynamic_scoping>) How can I do likewise in Python? It seems the language does not support this directl...
I feel Justice is plain right in his reasoning here. On the other hand -- I can't resist implementing proof of concept for still another programing paradigm "unnatural" to Python -- I simply love doing this. :-) So, I created a class whose objects'attributes are scopped just like you require (and can be created dynam...
How to create dynamical scoped variables in Python?
2,001,138
10
2010-01-04T18:09:52Z
2,002,140
9
2010-01-04T20:49:34Z
[ "python", "variables", "lisp", "scope", "dynamic-scope" ]
I am translating some code from lisp to Python. In lisp, you can have a let construct with the variables introduced declared as special and thus having dynamic scope. (See <http://en.wikipedia.org/wiki/Dynamic_scope#Dynamic_scoping>) How can I do likewise in Python? It seems the language does not support this directl...
Here's something that works a bit like Lisp's special variables, but fits a little better into Python. ``` _stack = [] class _EnvBlock(object): def __init__(self, kwargs): self.kwargs = kwargs def __enter__(self): _stack.append(self.kwargs) def __exit__(self, t, v, tb): _stack.pop(...
Converting PDF to images automatically
2,002,055
19
2010-01-04T20:33:43Z
2,002,785
7
2010-01-04T22:37:48Z
[ "python", "pdf", "image" ]
So the state I'm in released a bunch of data in PDF form, but to make matters worse, most (all?) of the PDFs appear to be letters typed in Office, printed/fax, and then scanned (our government at its best eh?). At first I thought I was crazy, but then I started seeing numerous pdfs that are 'tilted', like someone didn'...
If the PDFs are truly scanned images, then you shouldn't convert the PDF to an image, you should extract the image from the PDF. Most likely, all of the data in the PDF is essentially one giant image, wrapped in PDF verbosity to make it readable in Acrobat. You should try the simple expedient of simply finding the ima...
How to debug Jinja2 template?
2,002,357
17
2010-01-04T21:27:36Z
2,005,000
14
2010-01-05T09:12:00Z
[ "python", "django", "jinja2" ]
I am using jinja2 template system into django. It is really fast and I like it a lot. Nevertheless, I have some problem to debug templates : If I make some errors into a template (bad tag, bad filtername, bad end of block...), I do not have at all information about this error. For example, In a django view, I write th...
After doing some more test, I found the answer : By doing the same template test, directly under python, without using django, debug messages are present. So it comes from django. The fix is in settings.py : One have to set DEBUG to True AND set TEMPLATE\_DEBUG to False.
How can I add an additional row and column to an array?
2,002,415
5
2010-01-04T21:37:45Z
2,002,432
15
2010-01-04T21:41:51Z
[ "python" ]
I need to add a column and and a row to an existing numpy array at a position defined as I can. forgiveness for my regular English.
I assume your column and rows are just a list of lists? That is, you have the following? ``` L = [[1,2,3], [4,5,6]] ``` To add another row, use the append method of a list. ``` L.append([7,8,9]) ``` giving ``` L = [[1,2,3], [4,5,6], [7,8,9]] ``` To add another column, you would have to loop over e...
Why does Django admin try to encode strings into ASCII rather than Unicode? Or is this error something different than it looks like?
2,002,460
3
2010-01-04T21:45:58Z
2,002,574
7
2010-01-04T22:00:23Z
[ "python", "django", "unicode", "encoding", "django-admin" ]
I've got the following error: > TemplateSyntaxError at > /admin/results\_cop/copsegmentresult/ > > Caught an exception while rendering: > ('ascii', 'ISU European Figure Skating > Championships 2009: Senior Ladies > Ladies: Short Program - 2. Susanna > P\xc3\x96YKI\xc3\x96', 98, 99, > 'ordinal not in range(128)') The ...
I'm guessing you're asking Django to render a byte string. No `u` at the start of this: ``` 'ISU European Figure Skating Championships 2009: Senior Ladies Ladies: Short Program - 2. Susanna P\xc3\x96YKI\xc3\x96' ``` So Django is probably trying to encode it to the page's encoding, presumably UTF-8. But byte strings c...
Apps won't show in Django admin
2,002,549
4
2010-01-04T21:57:00Z
2,002,593
7
2010-01-04T22:04:11Z
[ "python", "django", "django-admin", "pinax" ]
I've read all the other threads but I still don't get why my apps are not showing up in Django admin. Everything else works fine. My apps are in settings.py I have admin.autodiscover in my root urls.py file ``` from django.conf.urls.defaults import * from django.conf import settings from django.views.generic.simple...
Do you have your apps in the INSTALLED\_APPS section in settings.py? Make sure it has your apps listed there. My section reads ``` INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.admin', 'django.contrib.sites', 'squick.items', 'cowsite.search', 'cowsi...
Best way to save complex Python data structures across program sessions (pickle, json, xml, database, other)
2,003,693
10
2010-01-05T01:57:23Z
2,003,704
15
2010-01-05T01:59:19Z
[ "python", "json", "sqlite", "pickle" ]
Looking for advice on the best technique for saving complex Python data structures across program sessions. Here's a list of techniques I've come up with so far: * pickle/cpickle * json * jsonpickle * xml * database (like SQLite) Pickle is the easiest and fastest technique, but my understanding is that there is no g...
You have a misconception about pickles: they are guaranteed to work across Python versions. You simply have to choose a protocol version that is supported by all the Python versions you care about. The technique you left out is marshal, which is not guaranteed to work across Python versions (and btw, is how .pyc files...