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
Python: How to find the slope of a graph drawn using matplotlib?
2,244,386
9
2010-02-11T12:33:32Z
2,244,447
14
2010-02-11T12:46:03Z
[ "python" ]
Here is my code: ``` import matplotlib.pyplot as plt plt.loglog(length,time,'--') ``` where length and time are lists. How do I find the slope of this graph?
If you have matplotlib then you must also have numpy installed since it is a dependency. Therefore, you could use [numpy.polyfit](http://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html#numpy.polyfit) to find the slope: ``` import matplotlib.pyplot as plt import numpy as np length = np.random.random(10...
Comparing list item values to other items in other list in Python
2,244,443
3
2010-02-11T12:44:57Z
2,244,459
8
2010-02-11T12:48:17Z
[ "python", "plone", "zope" ]
I want to compare the values in one list to the values in a second list and return all those that are in the first list but not in the second i.e. ``` list1 = ['one','two','three','four','five'] list2 = ['one','two','four'] ``` would return 'three' and 'five'. I have only a little experience with python, so this may...
`set(list1).difference(set(list2))`
RSS feed parser library in Python
2,244,836
32
2010-02-11T13:57:29Z
2,245,384
10
2010-02-11T15:16:48Z
[ "python", "rss", "feedparser" ]
I am looking for a good library in python that will help me parse RSS feeds. Has anyone used feedparser? Any feedback?
**Feedparser is very powerful, configurable and sooo easy to use. A very friendly learning curve, if at all.** **Example** Programatically determine how many answers your question has: ``` easy_install feedparser python -c 'import feedparser; print len(feedparser.parse("http://bit.ly/c785aj")["entries"])' ```
RSS feed parser library in Python
2,244,836
32
2010-02-11T13:57:29Z
2,245,392
47
2010-02-11T15:18:02Z
[ "python", "rss", "feedparser" ]
I am looking for a good library in python that will help me parse RSS feeds. Has anyone used feedparser? Any feedback?
Using feedparser is a much better option than rolling your own with minidom or BeautifulSoup. * It normalizes the differences between all versions of RSS and Atom so you don't have to have different code for each type. * It's good about detecting different date formats and other variations in feeds. * It automatically...
how to measure execution time of functions (automatically) in Python
2,245,161
21
2010-02-11T14:44:40Z
2,245,224
8
2010-02-11T14:53:27Z
[ "python", "oop" ]
I need to have a *base class* which I will use to inherit other classes which I would like to measure execution time of its functions. So **intead of** having something like this: ``` class Worker(): def doSomething(self): start = time.time() ... do something elapsed = (time.time() - start...
Have you checked the **["profile" module](http://effbot.org/librarybook/profile.htm)**? I.e. are you sure you need to implement your own custom framework instead of using the default profiling mechanism for the language? You could also google for "python hotshot" for a similar solution.
how to measure execution time of functions (automatically) in Python
2,245,161
21
2010-02-11T14:44:40Z
2,245,290
38
2010-02-11T15:02:49Z
[ "python", "oop" ]
I need to have a *base class* which I will use to inherit other classes which I would like to measure execution time of its functions. So **intead of** having something like this: ``` class Worker(): def doSomething(self): start = time.time() ... do something elapsed = (time.time() - start...
One way to do this would be with a decorator [(PEP for decorators)](http://www.python.org/dev/peps/pep-0318/) [(first of a series of tutorial articles on decorators)](http://www.artima.com/weblogs/viewpost.jsp?thread=240808). Here's an example that does what you want. ``` from functools import wraps from time import t...
Python: Read configuration file with multiple lines per key
2,245,761
8
2010-02-11T16:06:43Z
2,246,344
9
2010-02-11T17:41:21Z
[ "python", "configuration-files", "text-parsing", "sql" ]
I am writing a small DB test suite, which reads configuration files with queries and expected results, e.g.: ``` query = "SELECT * from cities WHERE name='Unknown';" count = 0 level = 1 name = "Check for cities whose name should be null" suggested_fix = "UPDATE cities SET name=NULL WHE...
The Python standard library module **[ConfigParser](http://docs.python.org/library/configparser.html)** supports this by default. The configuration file has to be in a standard format: ``` [Long Section] short: this is a normal line long: this value continues in the next line ``` The configuration file above could be...
Python: Read configuration file with multiple lines per key
2,245,761
8
2010-02-11T16:06:43Z
2,251,072
7
2010-02-12T10:25:21Z
[ "python", "configuration-files", "text-parsing", "sql" ]
I am writing a small DB test suite, which reads configuration files with queries and expected results, e.g.: ``` query = "SELECT * from cities WHERE name='Unknown';" count = 0 level = 1 name = "Check for cities whose name should be null" suggested_fix = "UPDATE cities SET name=NULL WHE...
This is almost exactly the use-case that made us switch to [YAML](http://www.yaml.org/) ([Wikipedia](http://en.wikipedia.org/wiki/YAML), [python implementation](http://pyyaml.org/), [documentation](http://pyyaml.org/wiki/PyYAMLDocumentation); you might want to look at [JSON](http://www.json.org/) as an alternative). YA...
is there a simple to get group names of a user in django
2,245,895
17
2010-02-11T16:29:31Z
2,245,908
37
2010-02-11T16:31:39Z
[ "python", "django", "django-admin" ]
I tried following Code with the help of the **django.contrib.auth.User** and **django.contrib.auth.Group** ``` for g in request.user.groups: l.append(g.name) ``` But that failed and I received following **Error**: ``` TypeError at / 'ManyRelatedManager' object is not iterable Request Method: GET Request URL: ...
``` for g in request.user.groups.all(): l.append(g.name) ``` or with recent django ``` l = request.user.groups.values_list('name',flat=True) ```
How to go from list of words to a list of distinct letters in Python
2,245,903
3
2010-02-11T16:30:14Z
2,246,067
13
2010-02-11T16:53:04Z
[ "python", "filter", "distinct", "list-comprehension", "letters" ]
Using Python, I'm trying to convert a sentence of words into a flat list of all distinct letters in that sentence. Here's my current code: ``` words = 'She sells seashells by the seashore' ltr = [] # Convert the string that is "words" to a list of its component words word_list = [x.strip().lower() for x in words.sp...
Sets provide a simple, efficient solution. ``` words = 'She sells seashells by the seashore' unique_letters = set(words.lower()) unique_letters.discard(' ') # If there was a space, remove it. ```
Python Fabric: How to answer to keyboard input?
2,246,256
21
2010-02-11T17:26:14Z
2,246,395
12
2010-02-11T17:47:37Z
[ "python", "automation", "fabric" ]
I would like to automate the response for some question prompted by some programs, like mysql prompting for a password, or apt asking for a 'yes' or ... when I want to rebuild my haystack index with a ./manage.py rebuild\_index. For MySQL, I can use the --password= switch, and I'm sure that apt has a 'quiet' like opti...
Why can't you just use [pipes](http://en.wikipedia.org/wiki/Pipeline_%28Unix%29)? For example, for an automated auto accept, just use [`yes`](http://en.wikipedia.org/wiki/Yes_%28Unix%29), that just outputs a neverending stream of `y`. ``` yes | rm *.txt ``` ![](http://upload.wikimedia.org/wikipedia/en/thumb/f/f6/Pip...
Python Fabric: How to answer to keyboard input?
2,246,256
21
2010-02-11T17:26:14Z
2,246,416
31
2010-02-11T17:50:29Z
[ "python", "automation", "fabric" ]
I would like to automate the response for some question prompted by some programs, like mysql prompting for a password, or apt asking for a 'yes' or ... when I want to rebuild my haystack index with a ./manage.py rebuild\_index. For MySQL, I can use the --password= switch, and I'm sure that apt has a 'quiet' like opti...
If you are looking for a user to confirm an operation, use the confrim method. ``` if fabric.contrib.console.confirm("You tests failed do you want to continue?"): #continue processing ``` Or if you are looking for a way to get input from the user, use the prompt method. ``` password = fabric.operations.prompt("Wha...
Django, template context processors
2,246,725
57
2010-02-11T18:34:03Z
2,246,742
50
2010-02-11T18:35:40Z
[ "python", "django", "django-templates" ]
I have a weird problem, I want to add a global query using context processors. This is how I did it by [following](http://www.b-list.org/weblog/2006/jun/14/django-tips-template-context-processors/): made a processor.py in my app as such: ``` from myproject.myapp.models import Foo def foos(request): return {'foos...
When you specify this: ``` TEMPLATE_CONTEXT_PROCESSORS = ('myapp.processor.foos',) ``` In your settings file, you are overriding the Django's [default context processors](https://docs.djangoproject.com/en/1.9/ref/settings/#template-context-processors). In order to *extend* the list, you need to include the default on...
Django, template context processors
2,246,725
57
2010-02-11T18:34:03Z
9,233,283
170
2012-02-10T19:02:22Z
[ "python", "django", "django-templates" ]
I have a weird problem, I want to add a global query using context processors. This is how I did it by [following](http://www.b-list.org/weblog/2006/jun/14/django-tips-template-context-processors/): made a processor.py in my app as such: ``` from myproject.myapp.models import Foo def foos(request): return {'foos...
You need to add the default values of TEMPLATE\_CONTEXT\_PROCESSORS. However, instead of hard-coding those values, which will be tied to a specific version of Django, you can append your context processor to the default values by the following: ``` from django.conf import global_settings TEMPLATE_CONTEXT_PROCESSORS = ...
How can I filter a pcap file by specific protocol using python?
2,247,140
10
2010-02-11T19:31:32Z
2,248,149
9
2010-02-11T22:12:51Z
[ "python", "filter", "pcap", "scapy" ]
I have some pcap files and I want to filter by protocol, i.e., if I want to filter by HTTP protocol, anything but HTTP packets will remain in the pcap file. There is a tool called [openDPI](http://www.opendpi.org/), and it's perfect for what I need, but there is no wrapper for python language. Does anyone knows any p...
maybe this can help [Scapy](http://www.secdev.org/projects/scapy/)?
How can I filter a pcap file by specific protocol using python?
2,247,140
10
2010-02-11T19:31:32Z
4,564,628
11
2010-12-30T17:09:52Z
[ "python", "filter", "pcap", "scapy" ]
I have some pcap files and I want to filter by protocol, i.e., if I want to filter by HTTP protocol, anything but HTTP packets will remain in the pcap file. There is a tool called [openDPI](http://www.opendpi.org/), and it's perfect for what I need, but there is no wrapper for python language. Does anyone knows any p...
A quick example using Scapy, since I just wrote one: ``` pkts = rdpcap('packets.pcap') ports = [80, 25] filtered = (pkt for pkt in pkts if TCP in pkt and (pkt[TCP].sport in ports or pkt[TCP].dport in ports)) wrpcap('filtered.pcap', filtered) ``` That will filter out packets that are neither HTTP nor SMTP. If ...
How can I filter a pcap file by specific protocol using python?
2,247,140
10
2010-02-11T19:31:32Z
6,630,608
13
2011-07-08T21:17:23Z
[ "python", "filter", "pcap", "scapy" ]
I have some pcap files and I want to filter by protocol, i.e., if I want to filter by HTTP protocol, anything but HTTP packets will remain in the pcap file. There is a tool called [openDPI](http://www.opendpi.org/), and it's perfect for what I need, but there is no wrapper for python language. Does anyone knows any p...
I know this is a super-old question, but I just ran across it thought I'd provide ***my*** answer. This is a problem I've encountered several times over the years, and I keep finding myself falling back to [dpkt](http://code.google.com/p/dpkt/). Originally from the very capable [dugsong](http://monkey.org/~dugsong/), d...
Python returning the wrong length of string when using special characters
2,247,205
7
2010-02-11T19:40:36Z
2,247,236
16
2010-02-11T19:47:05Z
[ "python", "character-encoding" ]
I have a string ë́aúlt that I want to get the length of a manipulate based on character positions and so on. The problem is that the first ë́ is being counted twice, or I guess ë is in position 0 and ´ is in position 1. Is there any possible way in Python to have a character like ë́ be represented as 1? I'm ...
UTF-8 is an unicode encoding which uses more than one byte for special characters. If you don't want the length of the encoded string, simple decode it and use `len()` on the `unicode` object (and not the `str` object!). Here are some examples: ``` >>> # creates a str literal (with utf-8 encoding, if this was >>> # s...
python bisect, it is possible to work with descending sorted lists?
2,247,394
13
2010-02-11T20:13:23Z
2,247,433
8
2010-02-11T20:18:16Z
[ "python" ]
How can I use bisect module on lists that are sorted descending? eg. ``` import bisect x = [1.0,2.0,3.0,4.0] # normal, ascending bisect.insort(x,2.5) # --> x is [1.0, 2.0, 2.5, 3.0, 4.0] ok, works fine for ascending list # however x = [1.0,2.0,3.0,4.0] x.reverse() # --> x is [4.0, 3.0, 2.0, 1.0] ...
Probably the easiest thing is to borrow the code from the library and make your own version ``` def reverse_insort(a, x, lo=0, hi=None): """Insert item x in list a, and keep it reverse-sorted assuming a is reverse-sorted. If x is already in a, insert it to the right of the rightmost x. Optional args ...
Python best way to check for existing key
2,247,412
9
2010-02-11T20:15:27Z
2,247,462
22
2010-02-11T20:22:29Z
[ "python" ]
Which is the more efficient/faster/better way to check if a key exists? ``` if 'subject' in request.POST: subject = request.POST['subject'] else: // handle error ``` OR ``` try: subject = request.POST['subject'] except KeyError: // handle error ```
The latter (`try/except`) form is generally the better form. `try` blocks are very cheap but catching an exception can be more expensive. A containment check on a dict tends to be cheap, but not cheaper than nothing. I suspect there will be a balance of efficiency depending on how often `'subject'` is really there. Ho...
Python String Method Conundrum
2,247,600
3
2010-02-11T20:46:46Z
2,247,616
8
2010-02-11T20:50:31Z
[ "python", "string", "methods" ]
The following code is supposed to print MyWords after removing SpamWords[0]. However; instead of returning "yes" it instead returns "None". Why is it returning "None"? ``` MyWords = "Spam yes" SpamWords = ["SPAM"] SpamCheckRange = 0 print ((MyWords.upper()).split()).remove(SpamWords[SpamCheckRange]) ```
Because `remove` is a method that changes the mutable list object it's called on, and returns `None`. ``` l= MyWords.upper().split() l.remove(SpamWords[SpamCheckRange]) # l is ['YES'] ``` Perhaps you want: ``` >>> [word for word in MyWords.split() if word.upper() not in SpamWords] ['yes'] ```
Anyone benchmarked virtual machine performance for build servers?
2,247,755
3
2010-02-11T21:15:24Z
2,248,041
7
2010-02-11T21:58:59Z
[ "c++", "python", "build", "automation", "vmware" ]
We have been trying to use virtual machines for build servers. Our build servers are all running WinXP32 and we are hosting them on VMWare Server 2.0 running on Ubuntu 9.10. We build a mix of C, C++, python packages, and other various deployment tasks (installers, 7z files, archives, etc). The management using VMWare h...
Disk IO is definitely a problem here, you just can't do any significant amount of disk IO activity when you're backing it up with a single spindle. The 32MB cache on a single SATA drive is going to be saturated just by your Host and a couple of Guest OS's ticking over. If you look at the disk queue length counter in yo...
render users' equations in Python
2,247,757
7
2010-02-11T21:15:36Z
2,247,771
8
2010-02-11T21:18:28Z
[ "python", "wxpython", "matplotlib", "equation" ]
I am a **very** new/inexperienced Python programmer. I teach maths and am trying to create a GUI graph-plotting package suitable for schoolchildren. As well as plotting a graph, I would ideally like to render the equation a user enters [eg. `y = (x^2)/3`] in a nicely formatted style - ideally updating in real-time as ...
You could look at how [Lybniz](http://lybniz2.sourceforge.net/index.html) does it. Or you could use Lybniz. Just saying.
Python equivalent to Java's JNLP Web Start?
2,248,921
12
2010-02-12T00:52:18Z
2,307,881
7
2010-02-21T23:21:20Z
[ "python", "jnlp" ]
Is there any way to achieve the same functionality in Python, i.e., launching a script from a browser and automatically updating it from a central server location?
Run your app on Jython and use Java Web Start? From a comment below, <http://blog.pyproject.ninja/posts/2016-03-31-web-start-on-jython.html>, provides a complete example. Note that Jython is not Python- some stuff does not work, and notably Jython is only Python-2.7 compatible.
Grouping Python tuple list
2,249,036
12
2010-02-12T01:19:21Z
2,249,060
16
2010-02-12T01:26:41Z
[ "grouping", "python" ]
I have a list of (label, count) tuples like this: ``` [('grape', 100), ('grape', 3), ('apple', 15), ('apple', 10), ('apple', 4), ('banana', 3)] ``` From that I want to sum all values with the same label (same labels always adjacent) and return a list in the same label order: ``` [('grape', 103), ('apple', 29), ('ban...
`itertools.groupby` can do what you want: ``` import itertools import operator L = [('grape', 100), ('grape', 3), ('apple', 15), ('apple', 10), ('apple', 4), ('banana', 3)] def accumulate(l): it = itertools.groupby(l, operator.itemgetter(0)) for key, subiter in it: yield key, sum(item[1] for item...
`if __name__ == '__main__'` equivalent in Ruby
2,249,310
77
2010-02-12T02:30:27Z
2,249,332
104
2010-02-12T02:36:16Z
[ "python", "ruby", "main" ]
I am new to Ruby. I'm looking to import functions from a module that contains a tool I want to continue using separately. In Python I would simply do this: ``` def a(): ... def b(): ... if __name__ == '__main__': a() b() ``` This allows me to run the program or import it as a module to use `a()` and/o...
From the Ruby I've seen out in the wild (granted, not a ton), this is not a standard Ruby design pattern. Modules and scripts are supposed to stay separate, so I wouldn't be surprised if there isn't really a good, clean way of doing this. **EDIT:** [Found it.](http://gimbo.org.uk/blog/2006/04/18/scripts-in-ruby-a-la-p...
Can we get the following flexibility in Python as In Perl
2,249,419
4
2010-02-12T03:04:15Z
2,249,426
7
2010-02-12T03:06:53Z
[ "python", "perl" ]
Sorry. I am not trying to start any flame. My scripting experience is from Perl, and I am pretty new in Python. I just want to check whether I can have the same degree of flexibility as in Python. In Python : ``` page = form.getvalue("page") str = 'This is string : ' + str(int(page) + 1) ``` In Perl : ``` $str = '...
No, since Python is strongly typed. If you keep `page` as an int you can do the following: ``` s = 'This is string : %d' % (page + 1,) ```
How to generate data model from sql schema in Django?
2,249,489
19
2010-02-12T03:24:22Z
2,249,559
28
2010-02-12T03:50:01Z
[ "python", "database", "django" ]
Our website uses a PHP front-end and a PostgreSQL database. We don't have a back-end at the moment except phpPgAdmin. The database admin has to type data into phpPgAmin manually, which is error-prone and tedious. We want to use Django to build a back-end. The database has a few dozen of tables already there. Is it pos...
Yes it is possible, using the [inspectdb](http://docs.djangoproject.com/en/dev/ref/django-admin/#inspectdb) command: ``` python manage.py inspectdb ``` or ``` python manage.py inspectdb > models.py ``` to get them in into the file This will look at the database configured in your `settings.py` and outputs model cl...
how to get the same day of next month of a given day in python using datetime
2,249,956
20
2010-02-12T05:59:54Z
2,249,988
18
2010-02-12T06:12:41Z
[ "python", "datetime", "date" ]
i know using datetime.timedelta i can get the date of some days away form given date ``` daysafter = datetime.date.today() + datetime.timedelta(days=5) ``` but seems no datetime.timedelta(months=1) !Thanks for any help!
Of course there isn't -- if today's January 31, what would be "the same day of the next month"?! Obviously there is no *right* solution, since February 31 does not exist, and the `datetime` module does **not** play at "guess what the user posing this impossible problem without a right solution thinks (wrongly) is the o...
how to get the same day of next month of a given day in python using datetime
2,249,956
20
2010-02-12T05:59:54Z
2,251,203
46
2010-02-12T10:48:22Z
[ "python", "datetime", "date" ]
i know using datetime.timedelta i can get the date of some days away form given date ``` daysafter = datetime.date.today() + datetime.timedelta(days=5) ``` but seems no datetime.timedelta(months=1) !Thanks for any help!
Use [`dateutil`](http://labix.org/python-dateutil) module. It has [relative time deltas](http://labix.org/python-dateutil#head-ba5ffd4df8111d1b83fc194b97ebecf837add454): ``` import datetime from dateutil import relativedelta nextmonth = datetime.date.today() + relativedelta.relativedelta(months=1) ``` Beautiful.
Left inverse in numpy or scipy?
2,250,403
9
2010-02-12T08:14:32Z
2,250,418
8
2010-02-12T08:20:10Z
[ "python", "matlab", "numpy", "linear-algebra", "matrix-inverse" ]
I am trying to obtain the left inverse of a non-square matrix in python using either numpy or scipy. How can I translate the following Matlab code to Python? ``` >> A = [0,1; 0,1; 1,0] A = 0 1 0 1 1 0 >> y = [2;2;1] y = 2 2 1 >> A\y ans = 1.0000 2.0000 ``` Is ...
Use `linalg.lstsq(A,y)` since `A` is not square. See [here](http://www.scipy.org/NumPy_for_Matlab_Users) for details. You can use `linalg.solve(A,y)` if `A` is square, but not in your case.
Python: find a list within members of another list(in order)
2,250,633
12
2010-02-12T09:06:30Z
2,250,918
11
2010-02-12T09:56:41Z
[ "list", "python" ]
If I have this: ``` a='abcdefghij' b='de' ``` Then this finds b in a: ``` b in a => True ``` Is there a way of doing an similar thing with lists? Like this: ``` a=list('abcdefghij') b=list('de') b in a => False ``` The 'False' result is understandable - because its rightly looking for an element 'de', rather tha...
I suspect there are more pythonic ways of doing it, but at least it gets the job done: ``` l=list('abcdefgh') pat=list('de') print pat in l # Returns False print any(l[i:i+len(pat)]==pat for i in xrange(len(l)-len(pat)+1)) ```
Python: find a list within members of another list(in order)
2,250,633
12
2010-02-12T09:06:30Z
2,251,638
7
2010-02-12T12:07:36Z
[ "list", "python" ]
If I have this: ``` a='abcdefghij' b='de' ``` Then this finds b in a: ``` b in a => True ``` Is there a way of doing an similar thing with lists? Like this: ``` a=list('abcdefghij') b=list('de') b in a => False ``` The 'False' result is understandable - because its rightly looking for an element 'de', rather tha...
I think this will be faster - It uses C implementation `list.index` to search for the first element, and goes from there on. ``` def find_sublist(sub, bigger): if not bigger: return -1 if not sub: return 0 first, rest = sub[0], sub[1:] pos = 0 try: while True: po...
sphinx (python) pdf generator
2,251,450
11
2010-02-12T11:33:16Z
2,252,547
8
2010-02-12T14:45:43Z
[ "python", "pdf", "documentation", "pdf-generation", "python-sphinx" ]
I use [sphinx python documentation generator](http://sphinx.pocoo.org/). Creating pdf documents are very easy and simple but.... i have one problem. All generated pdf documents have english words like "chapter", "release", "part". Is it possible change it? How set another words or remove it?
Sphinx generates LaTeX files, and then uses LaTeX to generate the PDF. So yes, you can, but it typically involves learning LaTeX and changing the LaTeX macros. I did a quick search and couldn't find any place where the "Chapter" was defined, so it's probably defined in the Bjarne chapter heading style (which is the def...
sphinx (python) pdf generator
2,251,450
11
2010-02-12T11:33:16Z
5,246,570
11
2011-03-09T13:37:16Z
[ "python", "pdf", "documentation", "pdf-generation", "python-sphinx" ]
I use [sphinx python documentation generator](http://sphinx.pocoo.org/). Creating pdf documents are very easy and simple but.... i have one problem. All generated pdf documents have english words like "chapter", "release", "part". Is it possible change it? How set another words or remove it?
In your `conf.py`, there is the following paragraph (around line 57 in a `conf.py` created by `sphinx-quickstart`): ``` # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None ``` In my case, I changed it to: ``` language = nl # bug! ``` ...
How to test a folder for new files using python
2,251,751
2
2010-02-12T12:29:15Z
2,251,820
8
2010-02-12T12:43:28Z
[ "python", "file", "directory" ]
Hello How would you go about testing to see if 2 folders contain the same files, and then to be able to manipulate ONLY the file which is new. ``` A = listdir('C:/') B = listdir('D:/') If A==B ``` ... I know this could be used to test if directories are different but is there a better way? And if A and B are the sa...
<http://docs.python.org/library/filecmp.html> <http://docs.python.org/library/filecmp.html#the-dircmp-class> ``` import filecmp compare = filecmp.dircmp( "C:/", "D:/" ) for f in compare.left_only: print "C: new", f for f in compare.right_only: print "D: new", f ```
Python, IMAP and GMail. Mark messages as SEEN
2,251,977
6
2010-02-12T13:16:56Z
3,140,319
12
2010-06-29T11:48:42Z
[ "python", "email", "gmail", "imap" ]
I have a python script that has to fetch unseen messages, process it, and mark as seen (or read) I do this after login in: ``` typ, data = self.server.imap_server.search(None, '(UNSEEN)') for num in data[0].split(): print "Mensage " + str(num) + " mark" self.server.imap_server.store(num, '+FL...
``` import imaplib obj = imaplib.IMAP4_SSL('imap.gmail.com', '993') obj.login('user', 'password') obj.select('Inbox') <--- it will select inbox typ ,data = obj.search(None,'UnSeen') obj.store(data[0].replace(' ',','),'+FLAGS','\Seen') ```
Efficent way to bulk insert with get_or_create() in Django (SQL, Python, Django)
2,252,530
15
2010-02-12T14:44:30Z
2,254,452
8
2010-02-12T19:13:53Z
[ "python", "django", "bulkinsert" ]
Is there a more efficent way for doing this? ``` for item in item_list: e, new = Entry.objects.get_or_create( field1 = item.field1, field2 = item.field2, ) ```
You can't do decent bulk insertions with get\_or\_create (or even create), and there's no API for doing this easily. If your table is simple enough that creating rows with raw SQL isn't too much of a pain, it's not too hard; something like: ``` INSERT INTO site_entry (field1, field2) ( SELECT i.field1, i.fie...
How to create PDF files in Python
2,252,726
104
2010-02-12T15:12:44Z
2,252,752
11
2010-02-12T15:16:18Z
[ "python", "pdf" ]
I'm working on a project which takes some images from user and then creates a PDF file which contains all of these images. Is there any way or any tool to do this in Python? E.g. to create a PDF file (or eps, ps) from image1 + image 2 + image 3 -> PDF file?
You can try [this](http://www.devshed.com/c/a/Python/Python-for-PDF-Generation/)(Python-for-PDF-Generation) or you can try [PyQt](http://www.riverbankcomputing.co.uk/news), which has support for printing to pdf. **Python for PDF Generation** The Portable Document Format (PDF) lets you create documents that l...
How to create PDF files in Python
2,252,726
104
2010-02-12T15:12:44Z
2,252,756
43
2010-02-12T15:16:46Z
[ "python", "pdf" ]
I'm working on a project which takes some images from user and then creates a PDF file which contains all of these images. Is there any way or any tool to do this in Python? E.g. to create a PDF file (or eps, ps) from image1 + image 2 + image 3 -> PDF file?
I suggest [pyPdf](https://github.com/mstamy2/PyPDF2). It works really nice. I also wrote a blog post some while ago, you can find it [here](http://ssscripting.wordpress.com/2009/08/16/get-your-job-done-faster-with-pypdf/).
How to create PDF files in Python
2,252,726
104
2010-02-12T15:12:44Z
16,632,518
61
2013-05-19T07:56:25Z
[ "python", "pdf" ]
I'm working on a project which takes some images from user and then creates a PDF file which contains all of these images. Is there any way or any tool to do this in Python? E.g. to create a PDF file (or eps, ps) from image1 + image 2 + image 3 -> PDF file?
Here is my experience after following the hints on this page. 1. pyPDF can't embed images into files. It can only split and merge. (Source: Ctrl+F through its [documentation page](http://pybrary.net/pyPdf/pythondoc-pyPdf.pdf.html)) Which is great, but not if you have images that are not already embedded in a PDF. 2...
Passing param to DB .execute for WHERE IN... INT list
2,253,494
7
2010-02-12T16:50:20Z
2,253,879
7
2010-02-12T17:48:51Z
[ "python", "postgresql" ]
With Python's DB API spec you can pass an argument of parameters to the execute() method. Part of my statement is a WHERE IN clause and I've been using a tuple to populate the IN. For example: ``` params = ((3, 2, 1), ) stmt = "SELECT * FROM table WHERE id IN %s" db.execute(stmt, params) ``` But when I run into a sit...
Edit: Please, as @rspeer mentions in a comment, do take precautions to protect yourself from SQL injection attack. Testing with [pg8000](http://pybrary.net/pg8000/index.html) (a DB-API 2.0 compatible Pure-Python interface to the PostgreSQL database engine): This is the recommended way to pass multiple parameters to a...
Sharing scripts that require a virtualenv to be activated
2,253,712
24
2010-02-12T17:22:58Z
2,255,961
71
2010-02-13T00:21:43Z
[ "python", "virtualenv" ]
I have virtualenv and virtualenvwrapper installed on a shared Linux server with default settings (virtualenvs are in ~/.virtualenvs). I have several Python scripts that can only be run when the correct virtualenv is activated. Now I want to **share** those scripts with other users on the server, but without requiring ...
Use the following magic(5) at the start of the script. ``` #!/usr/bin/env python ``` Change which virtualenv is active and it'll use the python from that virtualenv. Deactivate the virtualenv, it still runs.
Python strange exception. Have I found my first Python bug or is this a noob mistake?
2,253,816
18
2010-02-12T17:39:38Z
2,253,824
32
2010-02-12T17:41:40Z
[ "python" ]
Let me start by saying, I also get the same error whey defining `__init__` and running `super()`'s `__init__`. I only simplified it down to this custom method to see if the error still happened. ``` import HTMLParser class Spider(HTMLParser): """ Just a subclass. """ ``` This alone in a module raises the...
And the answer is that I'm a complete noob. This is a module, not a class, but I'll leave this up here in case other noobs run into the same problem. Solution: ``` from HTMLParser import HTMLParser ``` Each time I think I'm starting to become a pro, something like this happens :(
What does `**` mean in the expression `dict(d1, **d2)`?
2,255,878
22
2010-02-12T23:57:13Z
2,255,886
8
2010-02-12T23:59:48Z
[ "python", "syntax", "dictionary", "operators", "set-operations" ]
I am intrigued by the following python expression: ``` d3 = dict(d1, **d2) ``` The task is to merge 2 dictionaries into a third one, and the above expression accomplishes the task just fine. I am interested in the \*\* operator and what exactly is it doing to the expression. I thought that \*\* was the power operator...
In Python, any function can accept multiple arguments with \*; or multiple [**keyword arguments**](http://docs.python.org/tutorial/controlflow.html#keyword-arguments) with \*\*. Receiving-side example: ``` >>> def fn(**kwargs): ... for kwarg in kwargs: ... print kwarg ... >>> fn(a=1,b=2,c=3) a c b ``` Calli...
What does `**` mean in the expression `dict(d1, **d2)`?
2,255,878
22
2010-02-12T23:57:13Z
2,255,892
25
2010-02-13T00:00:29Z
[ "python", "syntax", "dictionary", "operators", "set-operations" ]
I am intrigued by the following python expression: ``` d3 = dict(d1, **d2) ``` The task is to merge 2 dictionaries into a third one, and the above expression accomplishes the task just fine. I am interested in the \*\* operator and what exactly is it doing to the expression. I thought that \*\* was the power operator...
`**` in argument lists has a special meaning, as covered in [section 4.7 of the tutorial](http://docs.python.org/tutorial/controlflow.html#more-on-defining-functions). The dictionary (or dictionary-like) object passed with `**kwargs` is expanded into keyword arguments to the callable, much like `*args` is expanded into...
How do I interact with MATLAB from Python?
2,255,942
19
2010-02-13T00:12:37Z
2,255,958
10
2010-02-13T00:20:02Z
[ "python", "matlab", "ctypes" ]
A friend asked me about creating a small web interface that accepts some inputs, sends them to MATLAB for number crunching and outputs the results. I'm a Python/Django developer by trade, so I can handle the web interface, but I am clueless when it comes to MATLAB. Specifically: * I'd **really** like to avoid hosting ...
Take a look at [mlabwrap](http://mlabwrap.sourceforge.net/) which allows you to call Matlab via a python API
How do I interact with MATLAB from Python?
2,255,942
19
2010-02-13T00:12:37Z
11,467,773
11
2012-07-13T09:30:39Z
[ "python", "matlab", "ctypes" ]
A friend asked me about creating a small web interface that accepts some inputs, sends them to MATLAB for number crunching and outputs the results. I'm a Python/Django developer by trade, so I can handle the web interface, but I am clueless when it comes to MATLAB. Specifically: * I'd **really** like to avoid hosting ...
There is a [python-matlab bridge](https://github.com/jaderberg/python-matlab-bridge) which is unique in the sense that Matlab runs in the background as a server so you don't have the startup cost each time you call a Matlab function. it's as easy as downloading and the following code: ``` from pymatbridge import Matl...
Extending a PIL decoder
2,257,318
9
2010-02-13T11:33:30Z
2,258,223
7
2010-02-13T16:18:14Z
[ "python", "python-imaging-library" ]
I have a file which contains a single image of a specific format at a specific offset. I can already get a file-like for the embedded image which supports `read()`, `seek()`, and `tell()`. I want to take advantage of an existing PIL decoder to handle the embedded image, but be able to treat the entire file as an "image...
The relevant chapter of the docs is [this one](http://effbot.org/imagingbook/decoder.htm) and I think it's fairly clear: if for example you want to decode image files in the new `.zap`-format, you write a `ZapImagePlugin.py` module which must perform a couple things: * have a `class ZapImageFile(ImageFile.ImageFile):`...
Random string generation with upper case letters and digits in Python
2,257,441
674
2010-02-13T12:23:58Z
2,257,449
1,438
2010-02-13T12:26:22Z
[ "python", "string", "random" ]
I want to generate a string of size N. It should be made up of numbers and uppercase English letters such as: * 6U1S75 * 4Z4UKK * U911K4 How can I achieve this in a [pythonic](https://en.wikipedia.org/wiki/Python_%28programming_language%29#Features_and_philosophy) way?
**Answer in one line:** ``` ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N)) ``` **A more secure version; see <http://stackoverflow.com/a/23728630/2213647>:** ``` ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N)) ``` **In details, with a ...
Random string generation with upper case letters and digits in Python
2,257,441
674
2010-02-13T12:23:58Z
2,257,492
13
2010-02-13T12:35:24Z
[ "python", "string", "random" ]
I want to generate a string of size N. It should be made up of numbers and uppercase English letters such as: * 6U1S75 * 4Z4UKK * U911K4 How can I achieve this in a [pythonic](https://en.wikipedia.org/wiki/Python_%28programming_language%29#Features_and_philosophy) way?
Taking the answer from Ignacio, this works with Python 2.6: ``` import random import string N=6 print ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N)) ``` Example output: > JQUBT2
Random string generation with upper case letters and digits in Python
2,257,441
674
2010-02-13T12:23:58Z
2,257,522
34
2010-02-13T12:44:48Z
[ "python", "string", "random" ]
I want to generate a string of size N. It should be made up of numbers and uppercase English letters such as: * 6U1S75 * 4Z4UKK * U911K4 How can I achieve this in a [pythonic](https://en.wikipedia.org/wiki/Python_%28programming_language%29#Features_and_philosophy) way?
A simpler, faster but slightly less random way is to use `random.sample` instead of choosing each letter separately, If n-repetitions are allowed, enlarge your random basis by n times e.g. ``` import random import string char_set = string.ascii_uppercase + string.digits print ''.join(random.sample(char_set*6, 6)) ```...
Random string generation with upper case letters and digits in Python
2,257,441
674
2010-02-13T12:23:58Z
9,236,278
8
2012-02-10T23:27:19Z
[ "python", "string", "random" ]
I want to generate a string of size N. It should be made up of numbers and uppercase English letters such as: * 6U1S75 * 4Z4UKK * U911K4 How can I achieve this in a [pythonic](https://en.wikipedia.org/wiki/Python_%28programming_language%29#Features_and_philosophy) way?
I thought no one had answered this yet lol! But hey, here's my own go at it: ``` import random def random_alphanumeric(limit): #ascii alphabet of all alphanumerals r = (range(48, 58) + range(65, 91) + range(97, 123)) random.shuffle(r) return reduce(lambda i, s: i + chr(s), r[:random.randint(0, len(r))...
Random string generation with upper case letters and digits in Python
2,257,441
674
2010-02-13T12:23:58Z
12,399,465
8
2012-09-13T04:32:14Z
[ "python", "string", "random" ]
I want to generate a string of size N. It should be made up of numbers and uppercase English letters such as: * 6U1S75 * 4Z4UKK * U911K4 How can I achieve this in a [pythonic](https://en.wikipedia.org/wiki/Python_%28programming_language%29#Features_and_philosophy) way?
If you need a random string rather than a **pseudo random** one, you should use [`os.urandom`](http://docs.python.org/2/library/os.html#os.urandom) as the source ``` from os import urandom from itertools import islice, imap, repeat import string def rand_string(length=5): chars = set(string.ascii_uppercase + stri...
Random string generation with upper case letters and digits in Python
2,257,441
674
2010-02-13T12:23:58Z
17,323,913
85
2013-06-26T15:11:13Z
[ "python", "string", "random" ]
I want to generate a string of size N. It should be made up of numbers and uppercase English letters such as: * 6U1S75 * 4Z4UKK * U911K4 How can I achieve this in a [pythonic](https://en.wikipedia.org/wiki/Python_%28programming_language%29#Features_and_philosophy) way?
# Simply use Python's builtin uuid: If UUIDs are okay for your purposes, use the built-in [uuid](http://docs.python.org/2/library/uuid.html) package. ## One Line Solution: `import uuid; str(uuid.uuid4().get_hex().upper()[0:6])` ## In Depth Version: Example: ``` import uuid uuid.uuid4() #uuid4 => full random uuid ...
Random string generation with upper case letters and digits in Python
2,257,441
674
2010-02-13T12:23:58Z
23,728,630
268
2014-05-19T01:41:56Z
[ "python", "string", "random" ]
I want to generate a string of size N. It should be made up of numbers and uppercase English letters such as: * 6U1S75 * 4Z4UKK * U911K4 How can I achieve this in a [pythonic](https://en.wikipedia.org/wiki/Python_%28programming_language%29#Features_and_philosophy) way?
This Stack Overflow quesion is the current top Google result for "random string Python". The current top answer is: ``` ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N)) ``` This is an excellent method, but the [PRNG](http://en.wikipedia.org/wiki/Pseudorandom_number_generator) in random...
Random string generation with upper case letters and digits in Python
2,257,441
674
2010-02-13T12:23:58Z
25,505,105
13
2014-08-26T11:47:33Z
[ "python", "string", "random" ]
I want to generate a string of size N. It should be made up of numbers and uppercase English letters such as: * 6U1S75 * 4Z4UKK * U911K4 How can I achieve this in a [pythonic](https://en.wikipedia.org/wiki/Python_%28programming_language%29#Features_and_philosophy) way?
A faster, easier and more flexible way to do this is to use the `strgen` module (`pip install StringGenerator`). Generate a 6-character random string with upper case letters and digits: ``` >>> from strgen import StringGenerator as SG >>> SG("[\u\d]{6}").render() u'YZI2CI' ``` Get a unique list: ``` >>> SG("[\l\d]{...
Random string generation with upper case letters and digits in Python
2,257,441
674
2010-02-13T12:23:58Z
34,017,605
13
2015-12-01T10:04:48Z
[ "python", "string", "random" ]
I want to generate a string of size N. It should be made up of numbers and uppercase English letters such as: * 6U1S75 * 4Z4UKK * U911K4 How can I achieve this in a [pythonic](https://en.wikipedia.org/wiki/Python_%28programming_language%29#Features_and_philosophy) way?
``` import uuid str = uuid.uuid4().hex ``` `str` is a random value like `'cea8b32e00934aaea8c005a35d85a5c0'` ``` uppercase_str = str.upper() ``` `uppercase_str` is `'CEA8B32E00934AAEA8C005A35D85A5C0'`
installing pygobject on mac for Python 2.6
2,257,771
4
2010-02-13T13:59:50Z
2,924,615
8
2010-05-27T20:24:30Z
[ "python", "osx", "pygobject" ]
Does anyone know how to install PyGObject on Mac OSX for Python 2.6. The current distribution available on darwinports is using Python2.4. I want a package using Python2.6 Alternatively, has anyone tried installing it from sources on a Mac?
If you have [Macports](http://www.macports.org/) you can simply do ``` port install py26-gobject ``` With [Homebrew](http://brew.sh/) it would be: ``` brew install pygobject ```
Why do I get "expected an indented block" when I try to run my Python script?
2,257,947
6
2010-02-13T14:59:16Z
2,257,965
11
2010-02-13T15:02:29Z
[ "python", "indentation" ]
I have an error which says "expected an indented block" Could you please guide me on how to deal with this error. Thank you:) Code example: ``` for ch in f: ( translatedToken = english_hindi_dict[ch] ) if (ch in english_hindi_dict) else (translatedToken = ch) ```
Python is a language that relies heavily on indentation to decide program structure unlike C and some other languages that use braces for this purpose. When you have a statement like: ``` if true: pass ``` it will complain because there's no indented statement for the `if`. You would need to fix it to be: ``` if tr...
Why do I get "expected an indented block" when I try to run my Python script?
2,257,947
6
2010-02-13T14:59:16Z
2,257,966
14
2010-02-13T15:02:31Z
[ "python", "indentation" ]
I have an error which says "expected an indented block" Could you please guide me on how to deal with this error. Thank you:) Code example: ``` for ch in f: ( translatedToken = english_hindi_dict[ch] ) if (ch in english_hindi_dict) else (translatedToken = ch) ```
You are probably mixing tabs with spaces. It *looks* indented but it really isn't. --- Your code gives me a different error: ``` for ch in f: \ ( translatedToken = english_hindi_dict[ch] ) \ if (ch in english_hindi_dict) else (translatedToken = ch...
Why do I get "expected an indented block" when I try to run my Python script?
2,257,947
6
2010-02-13T14:59:16Z
2,257,982
13
2010-02-13T15:08:02Z
[ "python", "indentation" ]
I have an error which says "expected an indented block" Could you please guide me on how to deal with this error. Thank you:) Code example: ``` for ch in f: ( translatedToken = english_hindi_dict[ch] ) if (ch in english_hindi_dict) else (translatedToken = ch) ```
*Editing answer to match the code example.* ``` for ch in f: ( translatedToken = english_hindi_dict[ch] ) if (ch in english_hindi_dict) else (translatedToken = ch) ``` is just not valid Python. First, readability count. Your code is hard to read and so, is hard to debug. What's "ch" and "f" ? What's more, you can do...
How do I implement a simple cross platform Python daemon?
2,258,079
19
2010-02-13T15:38:12Z
2,258,107
10
2010-02-13T15:44:37Z
[ "python", "cross-platform", "daemon" ]
I would like to have my Python program run in the background as a daemon, on either Windows or Unix. I see that the [python-daemon package](http://pypi.python.org/pypi/python-daemon/) is for Unix only; is there an alternative for cross platform? If possible, I would like to keep the code as simple as I can.
In Windows it's called a "service" and you could implement it pretty easily e.g. with the win32serviceutil module, part of [pywin32](http://sourceforge.net/projects/pywin32/). Unfortunately the two "mental models" -- service vs daemon -- are very different in detail, even though they serve similar purposes, and I know ...
How to add an HTML class to a Django form's help_text?
2,259,137
9
2010-02-13T21:33:00Z
2,259,632
7
2010-02-14T00:07:25Z
[ "python", "django" ]
I have a simple form ``` class MyForm(forms.Form): ... fieldname = forms.CharField(help_text="Some help text") ``` I can then display this form with django's handy `{{ form.as_ul }}` if I like, now I need to stylise the help\_text and I have no idea how. Django doesn't appear to wrap that string in anything t...
There's only that much you can customize in UI from form options. The more flexible way to approach a problem is to create your own form template then and reuse it instead of `{{ form.as_something }}`. Read these topics from Django documentation: * [Customizing form templates](https://docs.djangoproject.com/en/dev/top...
How to add an HTML class to a Django form's help_text?
2,259,137
9
2010-02-13T21:33:00Z
13,999,496
10
2012-12-22T02:16:50Z
[ "python", "django" ]
I have a simple form ``` class MyForm(forms.Form): ... fieldname = forms.CharField(help_text="Some help text") ``` I can then display this form with django's handy `{{ form.as_ul }}` if I like, now I need to stylise the help\_text and I have no idea how. Django doesn't appear to wrap that string in anything t...
A more convenient way to do this is to: ``` from django.utils.safestring import mark_safe ``` and then: ``` field = models.TextField(help_text=mark_safe("some<br>html")) ```
How are booleans formatted in Strings in Python?
2,259,228
81
2010-02-13T22:02:11Z
2,259,245
39
2010-02-13T22:06:22Z
[ "python", "boolean", "string-formatting" ]
I see I can't do: ``` "%b %b" % (True, False) ``` in Python. I guessed `%b` for b(oolean). Is there something like this?
If you want `True False` use: ``` "%s %s" % (True, False) ``` because `str(True)` is `'True'` and `str(False)` is `'False'`. or if you want `1 0` use: ``` "%i %i" % (True, False) ``` because `int(True)` is `1` and `int(False)` is `0`.
How are booleans formatted in Strings in Python?
2,259,228
81
2010-02-13T22:02:11Z
2,259,250
119
2010-02-13T22:07:31Z
[ "python", "boolean", "string-formatting" ]
I see I can't do: ``` "%b %b" % (True, False) ``` in Python. I guessed `%b` for b(oolean). Is there something like this?
``` >>> print "%r, %r" % (True, False) True, False ``` This is not specific to boolean values - `%r` calls the `__repr__` method on the argument. `%s` (for `str`) should also work.
Pickle or json?
2,259,270
49
2010-02-13T22:12:56Z
2,259,313
34
2010-02-13T22:22:51Z
[ "python", "json", "pickle" ]
I need to save to disk a little `dict` object which keys are `str`s and values are `int`s **and then recover it**. Something like this: ``` {'juanjo': 2, 'pedro':99, 'other': 333} ``` What is the best option and why? Serialize it with `pickle` or with `simplejson`? I am using Python 2.6.
If you do not have any interoperability requirements (e.g. you are just going to use the data with Python) and a binary format is fine, go with [cPickle](http://python.org/doc/2.5/lib/module-cPickle.html) which gives you really fast Python object serialization. If you want interoperability or you want a text format to...
Pickle or json?
2,259,270
49
2010-02-13T22:12:56Z
2,259,351
52
2010-02-13T22:33:07Z
[ "python", "json", "pickle" ]
I need to save to disk a little `dict` object which keys are `str`s and values are `int`s **and then recover it**. Something like this: ``` {'juanjo': 2, 'pedro':99, 'other': 333} ``` What is the best option and why? Serialize it with `pickle` or with `simplejson`? I am using Python 2.6.
I prefer JSON over pickle for my serialization. Unpickling can run arbitrary code, and using `pickle` to transfer data between programs or store data between sessions is a security hole. JSON does not introduce a security hole and is standardized, so the data can be accessed by programs in different languages if you ev...
Pickle or json?
2,259,270
49
2010-02-13T22:12:56Z
2,259,424
8
2010-02-13T22:55:10Z
[ "python", "json", "pickle" ]
I need to save to disk a little `dict` object which keys are `str`s and values are `int`s **and then recover it**. Something like this: ``` {'juanjo': 2, 'pedro':99, 'other': 333} ``` What is the best option and why? Serialize it with `pickle` or with `simplejson`? I am using Python 2.6.
JSON or pickle? How about JSON *and* pickle! You can use `jsonpickle`. It easy to use and the file on disk is readable because it's JSON. <http://jsonpickle.github.com/>
Pickle or json?
2,259,270
49
2010-02-13T22:12:56Z
6,215,929
28
2011-06-02T14:30:41Z
[ "python", "json", "pickle" ]
I need to save to disk a little `dict` object which keys are `str`s and values are `int`s **and then recover it**. Something like this: ``` {'juanjo': 2, 'pedro':99, 'other': 333} ``` What is the best option and why? Serialize it with `pickle` or with `simplejson`? I am using Python 2.6.
You might also find this interesting, with some charts to compare: <http://kovshenin.com/archives/pickle-vs-json-which-is-faster/>
Basic Financial Library for Python
2,259,379
8
2010-02-13T22:40:24Z
3,562,561
12
2010-08-25T02:57:51Z
[ "python", "finance" ]
I am looking for a financial library for Python that will enable me to do a discounted cash flow analysis. I have looked around and found the QuantLib, which is overkill for what I want to do. I just need a small library that I can use to input a series of cash flows and have it output a net present value and internal ...
Just for completeness, since I'm late: numpy has some functions for (very) basic financial calculations. numpy, scipy could also be used, to do the calculations from the basic formulas as in R. net present value of cashflow ``` >>> cashflow = 2*np.ones(6) >>> cashflow[-1] +=100 >>> cashflow array([ 2., 2., 2....
load python code at runtime
2,259,427
14
2010-02-13T22:57:06Z
2,259,618
7
2010-02-14T00:00:42Z
[ "python", "runtime", "python-import" ]
I would like to load a `.py` file at runtime. This `.py` file is basically a config file with the following format: ``` var1=value var2=value predicate_function=func line : <return true or false> ``` Once this file is loaded, I would like to be able to access `var1`, `var2` and `predicate_function`. For each line...
To access another Python module, you *import it*. `execfile` has been mentioned by a couple people, but it is messy and dangerous. `execfile` clutters your namespace, possibly even messing up the code you are running. When you want to access another Python source file, use the `import` statement. Even better would be ...
load python code at runtime
2,259,427
14
2010-02-13T22:57:06Z
2,260,611
7
2010-02-14T09:18:46Z
[ "python", "runtime", "python-import" ]
I would like to load a `.py` file at runtime. This `.py` file is basically a config file with the following format: ``` var1=value var2=value predicate_function=func line : <return true or false> ``` Once this file is loaded, I would like to be able to access `var1`, `var2` and `predicate_function`. For each line...
If the imported module is on the regular search path, you can use [`__import__`](http://docs.python.org/library/functions.html?highlight=__import__#__import__). If you need to load the module from an arbitrary path in the filesystem, use [`imp.load_module`](http://docs.python.org/library/imp.html?highlight=__import__#...
load python code at runtime
2,259,427
14
2010-02-13T22:57:06Z
2,260,630
9
2010-02-14T09:24:21Z
[ "python", "runtime", "python-import" ]
I would like to load a `.py` file at runtime. This `.py` file is basically a config file with the following format: ``` var1=value var2=value predicate_function=func line : <return true or false> ``` Once this file is loaded, I would like to be able to access `var1`, `var2` and `predicate_function`. For each line...
You just need to be able to dynamically specify the imports and then dynamically get at the variables. Let's say your config file is bar.py and looks like this: ``` x = 3 y = 4 def f(x): return (x<4) ``` Then your code should look like this: ``` import sys # somehow modnames should be a list of strings that are th...
load python code at runtime
2,259,427
14
2010-02-13T22:57:06Z
2,260,677
11
2010-02-14T09:47:18Z
[ "python", "runtime", "python-import" ]
I would like to load a `.py` file at runtime. This `.py` file is basically a config file with the following format: ``` var1=value var2=value predicate_function=func line : <return true or false> ``` Once this file is loaded, I would like to be able to access `var1`, `var2` and `predicate_function`. For each line...
As written in the [python official documentation](http://docs.python.org/library/functions.html#__import__), if you just want to import a module by name, you can look it up in the `sys.modules` dictionary after using `__import__`. Supposing your configuration is in `myproject.mymodule`, you would do like that : ``` m...
How to know the path of the running script in Python?
2,259,503
3
2010-02-13T23:18:24Z
2,259,516
7
2010-02-13T23:22:01Z
[ "python", "path" ]
My script.py creates a temporary file in the same dir as the script. When running it: ``` python script.py ``` it works just file but it doesn't work when you run: ``` python /path/to/script.py ``` That's because I'm using a relative path to my temp file in script.py rather than an absolute one. The problem is th...
Per the great [Dive Into Python](http://www.faqs.org/docs/diveintopython/regression_path.html): ``` import sys, os print 'sys.argv[0] =', sys.argv[0] 1 pathname = os.path.dirname(sys.argv[0]) 2 print 'path =', pathname print 'full path =', os.path.abspath(pathname) ```
How to know the path of the running script in Python?
2,259,503
3
2010-02-13T23:18:24Z
2,259,533
7
2010-02-13T23:27:12Z
[ "python", "path" ]
My script.py creates a temporary file in the same dir as the script. When running it: ``` python script.py ``` it works just file but it doesn't work when you run: ``` python /path/to/script.py ``` That's because I'm using a relative path to my temp file in script.py rather than an absolute one. The problem is th...
The two current answers reflect the ambiguity of your question. When you've run `python /path/to/script.py`, where do you want your tempfile? In the current directory (`./tempfile.txt`) or in `/path/to/tempfile.txt`? If the former, you can simply use the relative path (or, for weird and arcane purposes, get the absol...
How to make Django template engine to render in memory templates?
2,259,743
8
2010-02-14T00:52:02Z
2,259,754
12
2010-02-14T00:57:18Z
[ "python", "django", "google-app-engine", "templates", "django-templates" ]
I am storing my templates in the database and I don't have any path to provide for the `template.render` method. Is there any exposed method which accepts the template as a string? Is there any workaround?
[Instantiate `Template`](http://docs.djangoproject.com/en/dev/ref/templates/api/#using-the-template-system) with the string to use as a template.
How to make Django template engine to render in memory templates?
2,259,743
8
2010-02-14T00:52:02Z
25,007,609
11
2014-07-29T03:00:26Z
[ "python", "django", "google-app-engine", "templates", "django-templates" ]
I am storing my templates in the database and I don't have any path to provide for the `template.render` method. Is there any exposed method which accepts the template as a string? Is there any workaround?
Based on the [the docs](https://docs.djangoproject.com/en/dev/ref/templates/api/#overview) for using the template system: ``` from django.template import Template, Context t = Template("My name is {{ my_name }}.") c = Context({"my_name": "Adrian"}) t.render(c) ```
Simple Python Regex Find pattern
2,260,105
8
2010-02-14T04:08:53Z
2,260,117
12
2010-02-14T04:13:10Z
[ "python", "regex" ]
I have a sentence. I want to find all occurrences of a word that start with a specific character in that sentence. I am very new to programming and Python, but from the little I know, this sounds like a Regex question. What is the pattern match code that will let me find all words that match my pattern? Many thanks i...
``` import re print re.findall(r'\bv\w+', thesentence) ``` will print every word in the sentence that starts with `'v'`, for example. Using the `split` method of strings, as another answer suggests, would not identify *words*, but space-separated chunks that may include punctuation. This `re`-based solution *does* id...
How to clear the Entry widget after a button is pressed in Tkinter?
2,260,235
11
2010-02-14T05:35:45Z
2,260,355
13
2010-02-14T06:42:33Z
[ "python", "user-interface", "widget", "tkinter" ]
I'm trying to clear the `Entry` widget after the user presses a button using Tkinter. I tried using `ent.delete(0, END)`, but I got an error saying that strings don't have the attribute *delete*. Here is my code, where I'm getting error on `real.delete(0, END)`: ``` secret = randrange(1,100) print(secret) def res(re...
After poking around a bit through the [Introduction to Tkinter](http://www.pythonware.com/library/tkinter/introduction/), I came up with the code below, which doesn't do anything except display a text field and clear it when the `"Clear text"` button is pushed: ``` import tkinter as tk class App(tk.Frame): def __...
How to access the local Django webserver from outside world
2,260,727
110
2010-02-14T10:18:57Z
2,260,745
191
2010-02-14T10:30:09Z
[ "python", "django" ]
I followed the instructions [here](http://magazine.redhat.com/2008/06/05/installingconfiguringcaching-django-on-your-linux-server/) to run Django using the built-in webserver and was able to successfully run it using `python manage.py runserver`. If I access 127.0.0.1:port locally from the webserver, I get the Django p...
You have to run the development server such that it [listens on the interface](https://docs.djangoproject.com/en/dev/ref/django-admin/#django-admin-option---addrport) to your network. E.g. ``` python manage.py runserver 0.0.0.0:8000 ``` listens on **every** interface on port 8000. It doesn't matter whether you acce...
How to access the local Django webserver from outside world
2,260,727
110
2010-02-14T10:18:57Z
2,260,765
10
2010-02-14T10:40:10Z
[ "python", "django" ]
I followed the instructions [here](http://magazine.redhat.com/2008/06/05/installingconfiguringcaching-django-on-your-linux-server/) to run Django using the built-in webserver and was able to successfully run it using `python manage.py runserver`. If I access 127.0.0.1:port locally from the webserver, I get the Django p...
Pick one or more from: * Your application isn't successfully listening on the intended IP:PORT + Because you haven't configured it successfully + Because the user doesn't have permission to * Your application is listening successfully on the intended IP:PORT, but clients can't reach it because + The server local...
Weird problem with input encoding in IPython
2,260,815
13
2010-02-14T10:58:37Z
2,260,840
12
2010-02-14T11:11:48Z
[ "python", "windows", "filesystems", "locale", "ipython" ]
I'm running python 2.6 with latest IPython on Windows XP SP3, and I have two questions. First one of my problems is, when under IPython, I cannot input Unicode strings directly, and, as a result, cannot open files with non-latin names. Let me demonstrate. Under usual python this works: ``` >>> sys.getdefaultencoding()...
Yes. Typing Unicode at the console is always problematic and generally best avoided, but [IPython is particularly broke](http://projects.scipy.org/ipython/ipython/ticket/239). It converts characters you type on its console as if they were encoded in ISO-8859-1, regardless of the actual encoding you're giving it. For n...
How can I resize the root window in Tkinter?
2,261,011
8
2010-02-14T12:20:04Z
2,261,082
20
2010-02-14T12:44:47Z
[ "python", "tkinter" ]
``` from Tkinter import * import socket, sys from PIL import Image, ImageTk root = Tk() root.title("Whois Tool") root.resizable(0, 0) text = Text() text1 = Text() image = Image.open("hacker2.png") photo = ImageTk.PhotoImage(image) label = Label(root, image=photo) label.pack() text1.config(width=15, height=1) text...
For a 500x500 window you would use ``` root.geometry("500x500") ``` As for image resizing, I do not believe Tkinter supports it. You would have to use a library such as [PIL](http://www.pythonware.com/products/pil/) to resize the image to the window resolution. -*[example resize code](http://www.daniweb.com/code/snip...
AMQP C++ implementation
2,261,347
8
2010-02-14T14:13:37Z
2,274,646
8
2010-02-16T16:56:18Z
[ "c++", "python", "amqp" ]
We are writing C++ code which needs messaging. Is there a free/open-source and stable AMQP server available that has equally stable C++ client library with it. We also need to provide Python interface of our code to users (idea is to do maximum stuff in C++ and expose the API in Python). What can be best way to achiev...
For future reference, take a look at [Apache Qpid](http://qpid.apache.org) - it has a C++ client library and is very good. The problem for your use-case is that Rabbit implements AMQP 0-8 and the Qpid C++ client talks AMQP 0-10.
Python equivalent of C code from Bit Twiddling Hacks?
2,261,671
3
2010-02-14T16:01:09Z
2,262,234
7
2010-02-14T18:29:17Z
[ "python", "c" ]
I have a bit counting method that I am trying to make as fast as possible. I want to try the algorithm below from [Bit Twiddling Hacks](http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel), but I don't know C. What is 'type T' and what is the python equivalent of (T)~(T)0/3? > A generalization of ...
T is a integer type, which I'm assuming is unsigned. Since this is C, it'll be fixed width, probably (but not necessarily) one of 8, 16, 32, 64 or 128. The fragment `(T)~(T)0` that appears repeatedly in that code sample just gives the value 2\*\*N-1, where N is the width of the type T. I suspect that the code may requi...
boost::python Export Custom Exception
2,261,858
19
2010-02-14T16:47:17Z
2,262,650
23
2010-02-14T20:33:58Z
[ "c++", "python", "exception", "boost-python" ]
I am currently writing a C++ extension for Python using Boost.Python. A function in this extension may generate an exception containing information about the error (beyond just a human-readable string describing what happened). I was hoping I could export this exception to Python so I could catch it and do something wi...
The solution is to create your exception class like any normal C++ class ``` class MyCPPException : public std::exception {...} ``` The trick is that all boost::python::class\_ instances hold a reference to the object's type which is accessible through their ptr() function. You can get this as you register the class ...
How to install Python ssl module on Windows?
2,261,866
19
2010-02-14T16:48:50Z
2,261,977
15
2010-02-14T17:24:52Z
[ "python", "google-app-engine", "ssl", "installation", "python-2.5" ]
The Google App Engine Launcher tells me: > WARNING appengine\_rpc.py:399 ssl module not found. > Without the ssl module, the identity of the remote host cannot be verified, and > connections may NOT be secure. To fix this, please install the ssl module from > <http://pypi.python.org/pypi/ssl> . I downloaded the packa...
Grab the [openssl](http://gnuwin32.sourceforge.net/packages/openssl.htm) and [libgw32c](http://gnuwin32.sourceforge.net/packages/libgw32c.htm) packages from the gnuwin32 project (download the "Developer files"!) and extract them where you installed gnuwin32 - or if you don't have gnuwin32 tools yet, you can extract it ...
How to install Python ssl module on Windows?
2,261,866
19
2010-02-14T16:48:50Z
2,888,786
9
2010-05-22T16:06:08Z
[ "python", "google-app-engine", "ssl", "installation", "python-2.5" ]
The Google App Engine Launcher tells me: > WARNING appengine\_rpc.py:399 ssl module not found. > Without the ssl module, the identity of the remote host cannot be verified, and > connections may NOT be secure. To fix this, please install the ssl module from > <http://pypi.python.org/pypi/ssl> . I downloaded the packa...
I had to use the following modification of AndiDog's approach: ``` setup.py build -cmingw32 setup.py install --skip-build ``` Without the --skip-build option, the install would try to build again and complain about MSVC again: ``` error: Python was built with Visual Studio 2003; extensions must be built with a compi...
What's the difference between "while 1" and "while True"?
2,261,987
18
2010-02-14T17:28:42Z
2,262,069
7
2010-02-14T17:47:32Z
[ "python", "while-loop", "infinite-loop" ]
I've seen two ways to create an infinite loop in Python: 1. ``` while 1: do_something() ``` 2. ``` while True: do_something() ``` Is there any difference between these? Is one more pythonic than the other?
The most pythonic way will always be the most readable. Use `while True:`
What's the difference between "while 1" and "while True"?
2,261,987
18
2010-02-14T17:28:42Z
2,262,162
36
2010-02-14T18:08:33Z
[ "python", "while-loop", "infinite-loop" ]
I've seen two ways to create an infinite loop in Python: 1. ``` while 1: do_something() ``` 2. ``` while True: do_something() ``` Is there any difference between these? Is one more pythonic than the other?
Fundamentally it doesn't matter, such minutiae doesn't really affect whether something is 'pythonic' or not. If you're interested in trivia however, there are some differences. 1. The [builtin boolean type didn't exist till Python 2.3](http://www.python.org/doc/2.3.5/whatsnew/section-bool.html) so code that was inten...
RGB Int to RGB - Python
2,262,100
11
2010-02-14T17:54:30Z
2,262,117
12
2010-02-14T17:59:08Z
[ "python", "integer", "rgb" ]
How can I convert an RGB integer to the corresponding RGB tuple `(R,G,B)`? Seems simple enough, but I can't find anything on google. I know that for every RGB `(r,g,b)` you have the integer `n = r256^2 + g256 + b`, how can I solve the reverse in Python, IE given an `n`, I need the `r`,`g`,`b` values.
From a RGB integer: ``` Blue = RGBint mod 256 Green = RGBint / 256 mod 256 Red = RGBint / 256 / 256 mod 256 ``` This can be pretty simply implemented once you know how to get it. :) Upd: Added python function. Not sure if there's a better way to do it, but this works on Python 3 and 2.4 ``` def rgb_int2tuple(rgb...
RGB Int to RGB - Python
2,262,100
11
2010-02-14T17:54:30Z
2,262,152
32
2010-02-14T18:06:30Z
[ "python", "integer", "rgb" ]
How can I convert an RGB integer to the corresponding RGB tuple `(R,G,B)`? Seems simple enough, but I can't find anything on google. I know that for every RGB `(r,g,b)` you have the integer `n = r256^2 + g256 + b`, how can I solve the reverse in Python, IE given an `n`, I need the `r`,`g`,`b` values.
I'm not a Python expert by all means, but as far as I know it has the same operators as C. If so this should work and it should also be a lot quicker than using modulo and division. ``` Blue = RGBint & 255 Green = (RGBint >> 8) & 255 Red = (RGBint >> 16) & 255 ``` What it does it to mask out the lowest byte in ea...
RGB Int to RGB - Python
2,262,100
11
2010-02-14T17:54:30Z
4,296,274
8
2010-11-28T10:05:09Z
[ "python", "integer", "rgb" ]
How can I convert an RGB integer to the corresponding RGB tuple `(R,G,B)`? Seems simple enough, but I can't find anything on google. I know that for every RGB `(r,g,b)` you have the integer `n = r256^2 + g256 + b`, how can I solve the reverse in Python, IE given an `n`, I need the `r`,`g`,`b` values.
``` >>> import struct >>> str='aabbcc' >>> struct.unpack('BBB',str.decode('hex')) (170, 187, 204) ``` and ``` >>> rgb = (50,100,150) >>> struct.pack('BBB',*rgb).encode('hex') '326496' ```
Is there a built-in or more Pythonic way to try to parse a string to an integer
2,262,333
33
2010-02-14T19:01:31Z
2,262,377
7
2010-02-14T19:11:00Z
[ "python", "parsing", "integer" ]
I had to write the following function to fail gracefully when trying to parse a string to an integer. I would imagine Python has something built in to do this, but I can't find it. If not, is there a more Pythonic way of doing this that doesn't require a separate function? ``` def try_parse_int(s, base=10, val=None): ...
No, it is already perfect. The `val` parameter could be better named default, though. Documented in the official docs simply as [int(x) -- x converted to integer](http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex)
Is there a built-in or more Pythonic way to try to parse a string to an integer
2,262,333
33
2010-02-14T19:01:31Z
2,262,387
19
2010-02-14T19:15:20Z
[ "python", "parsing", "integer" ]
I had to write the following function to fail gracefully when trying to parse a string to an integer. I would imagine Python has something built in to do this, but I can't find it. If not, is there a more Pythonic way of doing this that doesn't require a separate function? ``` def try_parse_int(s, base=10, val=None): ...
That's the pythonic way. In python, it's customary to use EAFP style - Easier to Ask Forgiveness than Permission. That means you'd try first, and then clean up the mess if necessary.
Is there a built-in or more Pythonic way to try to parse a string to an integer
2,262,333
33
2010-02-14T19:01:31Z
2,262,424
30
2010-02-14T19:26:55Z
[ "python", "parsing", "integer" ]
I had to write the following function to fail gracefully when trying to parse a string to an integer. I would imagine Python has something built in to do this, but I can't find it. If not, is there a more Pythonic way of doing this that doesn't require a separate function? ``` def try_parse_int(s, base=10, val=None): ...
This is a pretty regular scenario so I've written an "ignore\_exception" decorator that works for all kinds of functions which through excpetions instead of failing gracefully: ``` def ignore_exception(IgnoreException=Exception,DefaultVal=None): """ Decorator for ignoring exception from a function e.g. @igno...
Is there a built-in or more Pythonic way to try to parse a string to an integer
2,262,333
33
2010-02-14T19:01:31Z
9,591,248
10
2012-03-06T20:22:39Z
[ "python", "parsing", "integer" ]
I had to write the following function to fail gracefully when trying to parse a string to an integer. I would imagine Python has something built in to do this, but I can't find it. If not, is there a more Pythonic way of doing this that doesn't require a separate function? ``` def try_parse_int(s, base=10, val=None): ...
``` def intTryParse(value): try: return int(value), True except ValueError: return value, False ```