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
Turn off buffering
8,416,586
10
2011-12-07T14:05:07Z
8,419,160
11
2011-12-07T16:51:38Z
[ "python", "linux", "bash", "buffering" ]
Where is the buffer in this following ... and how do I turn it off? I am writing out to stdout in a python program like so: ``` for line in sys.stdin: print line ``` There is some buffering going on here: ``` tail -f data.txt | grep -e APL | python -u Interpret.py ``` I tried the following to shake off possibl...
`file.readlines()` and `for line in file` have internal buffering which is not affected by `-u` option (see [-u option note](http://docs.python.org/using/cmdline.html?highlight=buffering#cmdoption-u)). Use ``` while True: l=sys.stdin.readline() sys.stdout.write(l) ``` instead. By the way, `sys.stdout` is line-...
Checking whether a string contains some characters in python
8,417,488
3
2011-12-07T15:05:52Z
8,417,575
8
2011-12-07T15:12:00Z
[ "python" ]
I want to check if a string only contains A-Z and a-z and 0-9 and underscore and dash (\_ -) Any other special signs like !"#\% should not be contained How can I write the regular expression? and use `match` or ? My strings look like these: QOIWU\_W QWLJ2-1
Yes, `re.match` seems like a good match (pardon the pun). As for the regular expression, how about something like this: `'[A-Za-z0-9-_]*'`?
Python cannot find dateutil.relativedelta
8,418,636
21
2011-12-07T16:19:27Z
12,883,196
36
2012-10-14T14:33:43Z
[ "python", "install", "yum", "python-dateutil" ]
I am trying to run a program using `paster serve` but I keep getting the error: ``` ImportError: No module named dateutil.relativedelta ``` I am running python version 2.6.7 and `dateutil` version 1.5, so it should be installed. Has anyone got any ideas as to why this would happen? I am importing using ``` from da...
I also ran into this issue, the simple solution I ended up using was to add --upgrade to the end of the command. This forced it to install it even though python thought it was installed. This resolved the issue. So if you have this issue, try the following: ``` sudo pip install python-dateutil --upgrade ``` It can't...
Python defaultdict and lambda
8,419,401
26
2011-12-07T17:06:43Z
8,419,427
26
2011-12-07T17:08:11Z
[ "python", "collections", "defaultdict" ]
In someone else's code I read the following two lines: ``` x = defaultdict(lambda: 0) y = defaultdict(lambda: defaultdict(lambda: 0)) ``` As the argument of defaultdict is a default factory, I think the first line means that when I call x[k] for a nonexistent key k (such as a statement like v=x[k]), the key-value pai...
> I think the first line means that when I call `x[k]` for a nonexistent key `k` (such as a statement like `v=x[k]`), the key-value pair `(k,0)` will be automatically added to the dictionary, as if the statement `x[k]=0` is first executed. That's right. This is more idiomatically written ``` x = defaultdict(int) ``` ...
Difference between two dates?
8,419,564
38
2011-12-07T17:17:20Z
8,419,655
85
2011-12-07T17:22:50Z
[ "python", "date" ]
Im programming with PYTHON... I have two diferent dates...and I want to know the difference (in days) between them. The format of the date is YYYY-MM-DD To explain myself in a better way... I have a function that can ADD or SUBSTRACT a given number and get the date....for example: ``` def addonDays(a,x): ret = t...
Use `-` to get the difference between two `datetime` objects and take the `days` member. ``` from datetime import datetime def days_between(d1, d2): d1 = datetime.strptime(d1, "%Y-%m-%d") d2 = datetime.strptime(d2, "%Y-%m-%d") return abs((d2 - d1).days) ```
Difference between two dates?
8,419,564
38
2011-12-07T17:17:20Z
18,795,211
10
2013-09-13T21:03:55Z
[ "python", "date" ]
Im programming with PYTHON... I have two diferent dates...and I want to know the difference (in days) between them. The format of the date is YYYY-MM-DD To explain myself in a better way... I have a function that can ADD or SUBSTRACT a given number and get the date....for example: ``` def addonDays(a,x): ret = t...
Another short solution: ``` from datetime import date def diff_dates(date1, date2): return abs(date2-date1).days def main(): d1 = date(2013,1,1) d2 = date(2013,9,13) result1 = diff_dates(d2, d1) print '{} days between {} and {}'.format(result1, d1, d2) print ("Happy programmer's day!") main(...
Naming Loops in Python
8,419,796
10
2011-12-07T17:32:25Z
8,419,846
7
2011-12-07T17:35:48Z
[ "python", "for-loop", "label", "break" ]
I recently read [this question](http://stackoverflow.com/questions/886955/breaking-out-of-nested-loops-in-java/886979#886979) which had a solution about labeling loops in Java. I am wondering if such a loop-naming system exists in Python. I have been in a situation multiple times where I do need to break out of an out...
There was a proposal to include named loops in python [PEP3136](http://www.python.org/dev/peps/pep-3136/), however, it was rejected with an explanation [here](http://mail.python.org/pipermail/python-3000/2007-July/008663.html). The rejection was mostly due to the rare number of circumstances where code readability woul...
Naming Loops in Python
8,419,796
10
2011-12-07T17:32:25Z
8,420,092
7
2011-12-07T17:53:25Z
[ "python", "for-loop", "label", "break" ]
I recently read [this question](http://stackoverflow.com/questions/886955/breaking-out-of-nested-loops-in-java/886979#886979) which had a solution about labeling loops in Java. I am wondering if such a loop-naming system exists in Python. I have been in a situation multiple times where I do need to break out of an out...
Though there are reasons to include named looped in language construct you can easily avoid it in python without loss of readability. An implementation of the referred example in python ``` >>> try: for i in xrange(0,5): for j in xrange(0,6): if i*j > 6: print "Breaking" ...
Remove single quotes from python list item
8,419,817
3
2011-12-07T17:34:02Z
8,419,853
15
2011-12-07T17:36:04Z
[ "python", "list" ]
Actually quite simple question: I've a python list like: ``` ['1','2','3','4'] ``` Just wondering how can I strip those single quotes? I want `[1,2,3,4]`
Currently all of the values in your list are strings, and you want them to integers, here are the two most straightforward ways to do this: ``` map(int, your_list) ``` and ``` [int(value) for value in your_list] ``` See the documentation on [map()](http://docs.python.org/library/functions.html#map) and [list compre...
Is there a gi.repository documentation for python?
8,420,108
29
2011-12-07T17:54:46Z
8,420,320
17
2011-12-07T18:12:40Z
[ "python", "gtk", "pygtk", "gtk3" ]
I'm looking for a `gi.repository` module documentation and I can't find anything on the internet. All I found is documentation of new Gtk3 libraries for C, or old [PyGtk 2.0 Reference Manual](http://www.pygtk.org/docs/pygtk/) I'm looking for something like [PyGtk 2.0 Reference Manual](http://www.pygtk.org/docs/pygtk/)...
I think you're looking for [this](http://python-gtk-3-tutorial.readthedocs.org/en/latest/index.html). It's a work in progress, but basically is a tutorial for Gtk3 in python. I doesn't really cover any other thing aside from Gtk widgets (so no Glib, for example), but it's still useful to get started.
Is there a gi.repository documentation for python?
8,420,108
29
2011-12-07T17:54:46Z
21,083,315
22
2014-01-13T03:17:46Z
[ "python", "gtk", "pygtk", "gtk3" ]
I'm looking for a `gi.repository` module documentation and I can't find anything on the internet. All I found is documentation of new Gtk3 libraries for C, or old [PyGtk 2.0 Reference Manual](http://www.pygtk.org/docs/pygtk/) I'm looking for something like [PyGtk 2.0 Reference Manual](http://www.pygtk.org/docs/pygtk/)...
Yes, I found a site that contains documentations for all python bindings of perhaps all Gnome projects that are supported by the python gi.repository module or the Python GObject Introspection module <http://lazka.github.io/pgi-docs/> the one specifically for GTK is <http://lazka.github.io/pgi-docs/Gtk-3.0/index.html>...
ValueError: could not convert string to float: id
8,420,143
14
2011-12-07T17:57:05Z
8,420,179
15
2011-12-07T18:00:17Z
[ "python", "string", "floating-point" ]
I'm running the following python script: ``` #!/usr/bin/python import os,sys from scipy import stats import numpy as np f=open('data2.txt', 'r').readlines() N=len(f)-1 for i in range(0,N): w=f[i].split() l1=w[1:8] l2=w[8:15] list1=[float(x) for x in l1] list2=[float(x) for x in l2] result=sta...
Obviously some of your lines don't have valid float data, specifically some line have text `id` which can't be converted to float. When you try it in interactive prompt you are trying only first line, so best way is to print the line where you are getting this error and you will know the wrong line e.g. ``` #!/usr/bi...
Example use of "continue" statement in Python?
8,420,705
57
2011-12-07T18:43:27Z
8,420,746
11
2011-12-07T18:46:02Z
[ "python", "continue" ]
The definition of the continue statement is: > The continue statement continues with the next iteration of the loop. I can't find any good example of code. Could someone suggest some simple cases where `continue` is necessary?
Usually the situation where continue is necessary/useful, is when you want to skip the remaining code in the loop and continue iteration. I don't really believe it's necessary, since you can always use if statements to provide the same logic, but it might be useful to increase readability of code.
Example use of "continue" statement in Python?
8,420,705
57
2011-12-07T18:43:27Z
8,421,045
58
2011-12-07T19:11:08Z
[ "python", "continue" ]
The definition of the continue statement is: > The continue statement continues with the next iteration of the loop. I can't find any good example of code. Could someone suggest some simple cases where `continue` is necessary?
I like to use continue in loops where there are a lot of contitions to be fulfilled before you get "down to business". So instead of code like this: ``` for x, y in zip(a, b): if x > y: z = calculate_z(x, y) if y - z < x: y = min(y, z) if x ** 2 - y ** 2 > 0: ...
Example use of "continue" statement in Python?
8,420,705
57
2011-12-07T18:43:27Z
23,470,680
53
2014-05-05T10:50:46Z
[ "python", "continue" ]
The definition of the continue statement is: > The continue statement continues with the next iteration of the loop. I can't find any good example of code. Could someone suggest some simple cases where `continue` is necessary?
Here's an simple example : ``` for letter in 'Django': # First Example if letter == 'D': continue print 'Current Letter:', letter output will be Current Letter: j Current Letter: a Current Letter: n Current Letter: g Current Letter: o ``` It continues with the next iteration ...
Export Python interpreter history to a file?
8,421,097
9
2011-12-07T19:14:55Z
8,421,225
10
2011-12-07T19:24:07Z
[ "python" ]
Many times I will use the Python interpreter to inspect variables and step through commands before I actually write to a file. However by the end I have around 30 commands in the interpreter, and have to copy/paste them into a file to run. Is there a way I can export/write the Python interpreter history into a file? F...
If you are using Linux/Mac and have readline library, you could add the following to a file and export it in your `.bash_profile` and you will have both completion and history. ``` # python startup file import readline import rlcompleter import atexit import os # tab completion readline.parse_and_bind('tab: complete')...
Export Python interpreter history to a file?
8,421,097
9
2011-12-07T19:14:55Z
8,421,231
17
2011-12-07T19:24:33Z
[ "python" ]
Many times I will use the Python interpreter to inspect variables and step through commands before I actually write to a file. However by the end I have around 30 commands in the interpreter, and have to copy/paste them into a file to run. Is there a way I can export/write the Python interpreter history into a file? F...
[IPython](http://ipython.scipy.org/moin/) is extremely useful if you like using interactive sessions. For example for your usecase there is the save command, you just input save my\_useful\_session 10-20 23 to save input lines 10 to 20 and 23 to my\_useful\_session.py. (to help with this, every line is prefixed by its ...
Create an instance, I already have the type
8,421,199
4
2011-12-07T19:22:18Z
8,421,543
10
2011-12-07T19:47:19Z
[ "python" ]
``` class ClassA: pass mytype = type(ClassA) ``` Using mytype, how do you create an instance of ClassA? Note that I'm *NOT* looking for this as my answer :) ``` instance = ClassA() ``` I know that in this example, that's all you need to do but suppose that you have this type (mytype), you don't know anything about ...
If you use a new style class it, this will work: ``` class ClassA(object): pass o = ClassA() mytype = type(o) new_object = mytype() ```
Rotating a two-dimensional array in Python
8,421,337
37
2011-12-07T19:31:30Z
8,421,412
18
2011-12-07T19:36:58Z
[ "python", "multidimensional-array" ]
In a program I'm writing the need to rotate a two-dimensional array came up. Searching for the optimal solution I found this impressive one-liner that does the job: ``` rotated = zip(*original[::-1]) ``` I'm using it in my program now and it works as supposed. My problem though, is that I don't understand how it work...
That's a clever bit. Here's the breakdown: * `[::1]` - makes a shallow copy of the original list in reverse order. Could also use `reversed()` since the copy is not needed. * `*` - makes each sublist in the original list a separate argument to `zip()` (i.e., unpacks the list) * `zip()` - takes one item from each argum...
Rotating a two-dimensional array in Python
8,421,337
37
2011-12-07T19:31:30Z
8,421,484
26
2011-12-07T19:43:00Z
[ "python", "multidimensional-array" ]
In a program I'm writing the need to rotate a two-dimensional array came up. Searching for the optimal solution I found this impressive one-liner that does the job: ``` rotated = zip(*original[::-1]) ``` I'm using it in my program now and it works as supposed. My problem though, is that I don't understand how it work...
Consider the following two-dimensional list: ``` original = [[1, 2], [3, 4]] ``` Lets break it down step by step: ``` >>> original[::-1] # elements of original are reversed [[3, 4], [1, 2]] ``` This list is passed into `zip()` using [argument unpacking](http://docs.python.org/tutorial/controlflow.html...
Rotating a two-dimensional array in Python
8,421,337
37
2011-12-07T19:31:30Z
8,421,565
9
2011-12-07T19:49:10Z
[ "python", "multidimensional-array" ]
In a program I'm writing the need to rotate a two-dimensional array came up. Searching for the optimal solution I found this impressive one-liner that does the job: ``` rotated = zip(*original[::-1]) ``` I'm using it in my program now and it works as supposed. My problem though, is that I don't understand how it work...
There are three parts to this: 1. original[::-1] reverses the original array. This notation is Python list slicing. This gives you a "sublist" of the original list described by [start:end:step], start is the first element, end is the last element to be used in the sublist. step says take every step'th element from fir...
In pyqt how do I add items in a combobox?
8,421,614
7
2011-12-07T19:53:05Z
8,424,718
14
2011-12-08T00:38:13Z
[ "python", "pyqt", "pyqt4", "qcombobox" ]
I need some help adding some items to a `combBox`.So,I have two comboboxes,one `combobox` populates the other depending on the item selected. My question is that,using `additem` for new items,it works,but if i choose another option for the `combobox`, it adds the new items but the previous items are gone,and there are...
Assuming `list1` is a list of strings, then you can simply add them all at once using the [addItems](http://doc.qt.nokia.com/latest/qcombobox.html#addItems) method: ``` self.comboBox_2.clear() self.comboBox_2.addItems(list1) ``` Note that you are probably using `QApplication.translate` in the wrong way in your exampl...
How do I convert a currency string to a floating point number in Python?
8,421,922
8
2011-12-07T20:16:53Z
8,422,055
10
2011-12-07T20:28:22Z
[ "python", "localization" ]
I have some strings representing numbers with specific currency format, for example: ``` money="$6,150,593.22" ``` I want to convert this string into the number ``` 6150593.22 ``` What is the best way to achieve this?
Try this: ``` from re import sub from decimal import Decimal money = '$6,150,593.22' value = Decimal(sub(r'[^\d.]', '', money)) ``` This has some advantages since it uses [`Decimal`](http://docs.python.org/library/decimal.html) instead of `float` (which is better for representing currency) and it also avoids any loc...
Remove mean from numpy matrix
8,423,051
15
2011-12-07T21:47:26Z
8,423,212
22
2011-12-07T22:02:28Z
[ "python", "numpy" ]
I have a numpy matrix `A` where the data is organised column-vector-vise i.e `A[:,0]` is the first data vector, `A[:,1]` is the second and so on. I wanted to know whether there was a more elegant way to zero out the mean from this data. I am currently doing it via a `for` loop: ``` mean=A.mean(axis=1) for k in range(A...
As is typical, you can do this a number of ways. Each of the approaches below works by adding a dimension to the `mean` vector, making it a 4 x 1 array, and then NumPy's broadcasting takes care of the rest. Each approach creates a view of `mean`, rather than a deep copy. The first approach (i.e., using `newaxis`) is li...
Remove mean from numpy matrix
8,423,051
15
2011-12-07T21:47:26Z
8,423,344
7
2011-12-07T22:13:28Z
[ "python", "numpy" ]
I have a numpy matrix `A` where the data is organised column-vector-vise i.e `A[:,0]` is the first data vector, `A[:,1]` is the second and so on. I wanted to know whether there was a more elegant way to zero out the mean from this data. I am currently doing it via a `for` loop: ``` mean=A.mean(axis=1) for k in range(A...
You can also use `matrix` instead of `array`. Then you won't need to reshape: ``` >>> A = np.matrix([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]]) >>> m = A.mean(axis=1) >>> A - m matrix([[-1., 0., 1.], [-1., 0., 1.], [-1., 0., 1.], [-1., 0., 1.]]) ```
Using argparse in conjunction with sys.argv in Python
8,423,895
5
2011-12-07T23:03:07Z
8,424,052
12
2011-12-07T23:18:51Z
[ "python", "command-line-arguments", "glob", "argparse" ]
I currently have a script, which uses file globbing via the `sys.argv` variable like this: ``` if len(sys.argv) > 1: for filename in sys.argv[1:]: ``` This works great for processing a bunch of files; however, I would like to use this with the `argparse` module as well. So, I would like my program to be able ...
If I got you correctly, your question is about passing a list of files together with a few flag or optional parameters to the command. If I got you right, then you just must leverage the argument settings in argparse: File **p.py** ``` import argparse parser = argparse.ArgumentParser(description='SO test.') parser.a...
Extract just email headers in python
8,424,317
7
2011-12-07T23:45:10Z
8,424,563
8
2011-12-08T00:17:37Z
[ "python", "email", "header" ]
I'm having some issues trying to extract all the email headers in python. I know how to get the ones I'm looking for but I want to save all the headers and I'm not sure how to do that. I have it loaded into a email object ``` import email f = open(kwargs['opt_emailfile']) msg = email.message_from_file(f) f.close() ``...
Using [HeaderParser](http://docs.python.org/library/email.parser.html) perhaps: ``` from email.parser import HeaderParser parser = HeaderParser() h = parser.parsestr(email) print h.keys() ``` I just noticed you edited your question. You can actually get the same information from what you had without using HeaderPars...
Parallel processing of a large .csv file in Python
8,424,771
12
2011-12-08T00:45:47Z
8,424,899
7
2011-12-08T01:04:34Z
[ "python" ]
I'm processing large CSV files (on the order of several GBs with 10M lines) using a Python script. The files have different row lengths, and cannot be loaded fully into memory for analysis. Each line is handled separately by a function in my script. It takes about 20 minutes to analyze one file, and it appears disk a...
Because of the [GIL](http://wiki.python.org/moin/GlobalInterpreterLock), Python's threading won't speed-up computations that are processor bound like it can with IO bound. Instead, take a look at the [multiprocessing module](http://docs.python.org/library/multiprocessing.html#module-multiprocessing) which can run your...
Creating a new dict in Python
8,424,942
152
2011-12-08T01:10:58Z
8,424,954
89
2011-12-08T01:13:09Z
[ "python", "list", "dictionary" ]
I want to build a dictionary in Python. However, all the examples that I see are instantiating a dictionary from a list, etc . .. How do I create a new empty dictionary in Python?
You can do this ``` x = {} x['a'] = 1 ```
Creating a new dict in Python
8,424,942
152
2011-12-08T01:10:58Z
8,424,955
236
2011-12-08T01:13:15Z
[ "python", "list", "dictionary" ]
I want to build a dictionary in Python. However, all the examples that I see are instantiating a dictionary from a list, etc . .. How do I create a new empty dictionary in Python?
Call `dict` with no parameters ``` new_dict = dict() ``` or simply write ``` new_dict = {} ```
Creating a new dict in Python
8,424,942
152
2011-12-08T01:10:58Z
8,424,968
11
2011-12-08T01:16:09Z
[ "python", "list", "dictionary" ]
I want to build a dictionary in Python. However, all the examples that I see are instantiating a dictionary from a list, etc . .. How do I create a new empty dictionary in Python?
``` d = dict() ``` or ``` d = {} ``` or ``` import types d = types.DictType.__new__(types.DictType, (), {}) ```
Creating a new dict in Python
8,424,942
152
2011-12-08T01:10:58Z
29,582,379
7
2015-04-11T19:57:43Z
[ "python", "list", "dictionary" ]
I want to build a dictionary in Python. However, all the examples that I see are instantiating a dictionary from a list, etc . .. How do I create a new empty dictionary in Python?
Knowing how to write a preset dictionary is useful to know as well: ``` cmap = {'US':'USA','GB':'Great Britain'} def cxlate(country): try: ret = cmap[country] except: ret = '?' return ret present = 'US' # this one is in the dict missing = 'RU' # this one is not print cxlate(present) # =...
What happens when import a module in ironpython?
8,426,999
6
2011-12-08T06:19:31Z
8,434,676
7
2011-12-08T16:57:12Z
[ "python", "import", "ironpython", "dynamic-language-runtime" ]
In CPython, I think, import means compile the py file to a pyc file and execute the file in the current frame, and the next time CPython will load the pyc file directly without compiling again. What about import in ironpython? I guess ironpython don't have a pyc-like format. Does it compile every time when import?
Yes, IronPython recompiles the imported module on every run. Twice, actually. It's complicated. On the first pass, the Python code is parsed into an AST, the AST is converted into a DLR expression tree, and the expression tree is stored. When it is time to execute it, the expression tree is compiled into a set of ins...
how to solve AttributeError: '_Environ' object has no attribute 'has_key'
8,427,352
2
2011-12-08T07:00:18Z
8,427,495
8
2011-12-08T07:15:29Z
[ "python", "eclipse", "web-services" ]
``` def _is_dev_mode(): # quick hack to check if the program is running in dev mode. # if 'has_key' in os.environ if os.environ.has_key('SERVER_SOFTWARE') \ or os.environ.has_key('PHP_FCGI_CHILDREN') \ or 'fcgi' in sys.argv or 'fastcgi' in sys.argv \ or 'mod_wsgi' in sys.argv: ...
I supose you are working on python 3. In Python 2, dictionaries had a `has_key()` method. In Python 3, as the exception says, it no longer exists. You need to use the `in` operator: ``` if 'SERVER_SOFTWARE' in os.environ ``` here you have an example (py3k): ``` >>> import os >>> if 'PROCESSOR_LEVEL' in os.environ: p...
How does virtualenv work?
8,427,709
32
2011-12-08T07:39:33Z
8,428,674
21
2011-12-08T09:20:06Z
[ "python", "virtualenv" ]
I checked the *activate* script and it looks to me all it does is: * set VIRTUAL\_ENV env * append $VIRTUAL\_ENV/bin in front of PATH How does `virtualenv` provide that magical virtual environment by these? What do I miss?
This is a very good [presentation](http://pyvideo.org/video/389/pycon-2011--reverse-engineering-ian-bicking--39-s) about the subject. Basically, it explains the steps to write your own `virtualenv` with the same tricks Ian Bicking used to write it.
How does virtualenv work?
8,427,709
32
2011-12-08T07:39:33Z
12,424,980
23
2012-09-14T12:52:36Z
[ "python", "virtualenv" ]
I checked the *activate* script and it looks to me all it does is: * set VIRTUAL\_ENV env * append $VIRTUAL\_ENV/bin in front of PATH How does `virtualenv` provide that magical virtual environment by these? What do I miss?
I will describe the basic process, which I learned from the presentation which jcollado linked to. When Python starts, it looks at the path of binary, and the prefixes thereof. So let's say your virtualenv is `/home/blah/scratch`. Then the python binary (which is just a copy of your system python binary) will be in `/...
Upload file with Selenium in Python
8,428,102
2
2011-12-08T08:23:53Z
11,276,130
9
2012-06-30T17:28:02Z
[ "python", "file-upload", "selenium", "attachment" ]
Is it possible to upload file attachment with selenium in Python script?
It can be done via: ``` element = driver.find_element_by_name("file") element.send_keys("/home/pavel/Desktop/949IH3GNHAo.jpg") ```
Python List comprehension one declaration and 2 Comprehensions
8,428,122
2
2011-12-08T08:25:58Z
8,428,153
7
2011-12-08T08:30:12Z
[ "python" ]
How can I combine this: ``` ipaddresses = [ipadr['ip'] for ipadr in hosts] for ipadr in ipaddresses: ips = '.'.join(str(i) for i in ipadr) ``` Into One declaration with 2 list comprehensions? I just don't get it. Thanks ipaddresses will print something like this: > [[10, 10, 10, 10], [10, 20, 20, 20]]
You only need 1 LC, not 2. ``` ['.'.join(str(octet) for octet in addr['ip']) for addr in hosts] ```
Django default settings convention for pluggable app?
8,428,556
17
2011-12-08T09:08:10Z
8,429,282
29
2011-12-08T10:11:37Z
[ "python", "django", "configuration" ]
What's a djangonautic way of handling default settings in an app if one isn't defined in `settings.py`? I've currently placed a `default_settings` file in the app and I've considered a few options. I'm leaning towards the first option, but there may be pitfalls I'm not aware of in using `globals()` I've mostly seen a...
I think it's quite common to create a `settings.py` in your app's package, where you define your settings like this: ``` from django.conf import settings FOO = getattr(settings, 'FOO', "default_value") ``` In your app you can import them from your app's `settings` module: ``` from myapp.settings import * def print_...
how to implement python spell checker using google's "did you mean?"
8,428,767
7
2011-12-08T09:28:02Z
8,428,853
9
2011-12-08T09:35:20Z
[ "python", "api" ]
I'm looking for a way to make a function in python where you pass in a string and it returns whether it's spelled correctly. I don't want to check against a dictionary. Instead, I want it to check Google's spelling suggestions. That way, celebrity names and other various proper nouns will count as being spelled correct...
Peter Norvig tells you how implement [spell checker in Python.](http://norvig.com/spell-correct.html)
Move child folder contents to parent folder in python
8,428,954
5
2011-12-08T09:43:28Z
8,429,176
9
2011-12-08T10:03:19Z
[ "python" ]
I have a specific problem in python. Below is my folder structure. dstfolder/slave1/slave I want the contents of 'slave' folder to be moved to "slave1" (parent folder). Once moved, 'slave' folder should be deleted. shutil.move seems to be not helping. Please let me know how to do it ?
Example using the os and shutil modules: ``` from os.path import join from os import listdir, rmdir from shutil import move root = 'dstfolder/slave1' for filename in listdir(join(root, 'slave')): move(join(root, 'slave', filename), join(root, filename)) rmdir(root) ```
How to fill a list
8,429,794
5
2011-12-08T10:51:55Z
8,430,287
7
2011-12-08T11:28:21Z
[ "python", "list", "fill" ]
I have to make a function that takes an empty list as first argument and n as secound argument, so that: ``` L=[] function(L,5) print L returns: [1,2,3,4,5] ``` I was thinking: ``` def fillList(listToFill,n): listToFill=range(1,n+1) ``` but it is returning an empty list.
Consider the usage of `extend`: ``` >>> l = [] >>> l.extend(range(1, 6)) >>> print l [1, 2, 3, 4, 5] >>> l.extend(range(1, 6)) >>> print l [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] ``` If you want to make a function (doing the same): ``` def fillmylist(l, n): l.extend(range(1, n + 1)) l = [] fillmylist(l, 5) ```
Using TimedRotatingFileHandler logging with a logging.config
8,430,136
6
2011-12-08T11:17:33Z
8,430,342
11
2011-12-08T11:31:46Z
[ "python", "logging" ]
I'm trying to test using a TimedRotatingFileHandler with a logging.config file, nothing that complicated but it should roll over every 10 seconds into a new log file. However I'm getting the following ``` Traceback (most recent call last): File "testLogging.py", line 6, in <module> logging.config.fileConfig(log...
``` args=('./logs/log.out', 'when=\'S\'', 'interval=10', 'backupCount=5') ``` Doesn't look right. Try this ``` args=('./logs/log.out', when='S', interval=10, backupCount=5) ``` Or possibly this ``` args=('./logs/log.out','S',10,5) ```
Parsing a date in python without using a default
8,434,854
11
2011-12-08T17:13:04Z
8,435,089
7
2011-12-08T17:29:54Z
[ "python", "python-dateutil" ]
I'm using python's `dateutil.parser` tool to parse some dates I'm getting from a third party feed. It allows specifying a default date, which itself defaults to today, for filling in missing elements of the parsed date. While this is in general helpful, there is no sane default for my use case, and I would prefer to tr...
Depending on your domain following solution might work: ``` DEFAULT_DATE = datetime.datetime(datetime.MINYEAR, 1, 1) def parse_no_default(dt_str): dt = parser.parse(dt_str, default=DEFAULT_DATE).date() if dt != DEFAULT_DATE: return dt else: return None ``` Another approach would be to m...
How to check for a string format in python?
8,436,142
3
2011-12-08T18:57:13Z
8,436,159
7
2011-12-08T18:58:32Z
[ "python", "regex" ]
I would like to check for string "tDDDDD" where D has to be digits and should not be more than the length (minimum 4, maximum 5) of it. No other characters allowed. Currently my code checks like this, ``` m = re.match('^(t)(\d+)', changectx.branch()) ``` But is also allows t12345anythingafterit. I changed the regu...
Your regular expression will work, but you could also use this regular expression: ``` r'^t\d{4,5}$' ``` The `{4,5}` is a quantifier that means the previous token must occur between 4 and 5 times. The parentheses are only necessary here if you wish to capture the matching parts of the string.
Passing a C pointer around with the Python/C API
8,436,578
7
2011-12-08T19:33:55Z
21,374,737
8
2014-01-27T06:58:11Z
[ "python", "python-c-api" ]
Im new to the Python/C API ... Im trying to add new functionality to my C program, wherein I can embed python into it and simultaneously extend functionality so that the embedded interpreter can execute a script that will interact with an extending python module written as part of my C program. My C program doesnt have...
Capsules are basically python-opaque void pointers that you can pass around or associate with modules. They are "the way" to solve your problem. Here's an example that uses an instance x that doesn't have to be static. First attach the pointer to your module something like this (error checking removed)... ``` // wrap...
How to make python on Heroku https only?
8,436,666
40
2011-12-08T19:41:42Z
9,204,892
12
2012-02-09T03:10:34Z
[ "python", "django", "ssl", "https", "heroku" ]
I have python/django app on Heroku (Cedar stack) and would like to make it accessible over https only. I have enabled the "ssl piggyback"-option, and can connect to it via https. But what is the best way to disable http access, or redirect to https?
Not sure if @CraigKerstiens's answer takes into account that `request.is_secure()` always returns `False` if behind Heroku's reverse proxy and not "fixed". If I remember correctly, this will cause a HTTP redirect loop. If you are running Django with gunicorn, another way to do it is to add the following to gunicorn's ...
How to make python on Heroku https only?
8,436,666
40
2011-12-08T19:41:42Z
9,207,726
55
2012-02-09T08:48:27Z
[ "python", "django", "ssl", "https", "heroku" ]
I have python/django app on Heroku (Cedar stack) and would like to make it accessible over https only. I have enabled the "ssl piggyback"-option, and can connect to it via https. But what is the best way to disable http access, or redirect to https?
Combining the answer from @CraigKerstiens and @allanlei into something I have tested, and verified to work. Heroku sets the HTTP\_X\_FORWARDED\_PROTO to https when request is ssl, and we can use this to check: ``` from django.conf import settings from django.http import HttpResponseRedirect class SSLMiddleware(objec...
How to make python on Heroku https only?
8,436,666
40
2011-12-08T19:41:42Z
26,670,053
17
2014-10-31T08:12:36Z
[ "python", "django", "ssl", "https", "heroku" ]
I have python/django app on Heroku (Cedar stack) and would like to make it accessible over https only. I have enabled the "ssl piggyback"-option, and can connect to it via https. But what is the best way to disable http access, or redirect to https?
Django 1.8 will have core support for non-HTTPS redirect (integrated from [django-secure](https://docs.djangoproject.com/en/dev/releases/1.8/#security-enhancements)): ``` SECURE_SSL_REDIRECT = True # [1] SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') ``` [1] <https://docs.djangoproject.com/en/1.8/ref/s...
Can Python select what network adapter when opening a socket?
8,437,726
13
2011-12-08T21:10:56Z
8,437,870
11
2011-12-08T21:23:08Z
[ "python", "windows", "linux", "sockets" ]
The target machine running the python application will have three network interfaces available to it. In general all three networks will be vastly different, however there is a possibility that two of the three could be on similar networks. In the example below I do not have control over the destination address on ETH...
I can't speak much for Windows, but on Linux the interface is normally not chosen until a routing decision is made, therefore you usually don't have a say on which interface your packets leave. You do have the option though, of using `SO_BINDTODEVICE` (see `man 7 socket`) on Linux. This binds a socket to a device, how...
Can Python select what network adapter when opening a socket?
8,437,726
13
2011-12-08T21:10:56Z
8,441,679
8
2011-12-09T06:01:48Z
[ "python", "windows", "linux", "sockets" ]
The target machine running the python application will have three network interfaces available to it. In general all three networks will be vastly different, however there is a possibility that two of the three could be on similar networks. In the example below I do not have control over the destination address on ETH...
On Windows, if you know the IP address of the interface you want to use, just bind to that before you connect. On Linux,use socket option SO\_BINDTODEVICE as suggested by JimB (seems to be a privileged call too). i.e. on Windows ``` import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('192.168....
python: printing horizontally rather than current default printing
8,437,964
7
2011-12-08T21:31:05Z
8,438,002
16
2011-12-08T21:34:03Z
[ "python" ]
I was wondering if we can print like row-wise in python. Basically I have a loop which might go on million times and I am printing out some strategic counts in that loop.. so it would be really cool if I can print like row-wise ``` print x # currently gives # 3 # 4 #.. and so on ``` and i am looking something like ...
In Python2: ``` data = [3, 4] for x in data: print x, # notice the comma at the end of the line ``` or in Python3: ``` for x in data: print(x, end=' ') ``` prints ``` 3 4 ```
Determine if package installed with Yum Python API?
8,439,074
8
2011-12-08T23:13:52Z
8,451,454
15
2011-12-09T20:40:11Z
[ "python", "linux", "rpm", "yum" ]
**TLDR**; I need simple a Python call given a package name (e.g., 'make') to see if it's installed; if not, install it (I can do the latter part). **Problem:** So there are a few code examples given in <http://yum.baseurl.org/wiki/YumCodeSnippets>, but other than kludging around inside ipython and guessing at what ea...
``` import yum yb = yum.YumBase() if yb.rpmdb.searchNevra(name='make'): print "installed" else: print "not installed" ```
__getitem__ invocation in for loop
8,439,482
2
2011-12-09T00:09:54Z
8,439,519
9
2011-12-09T00:13:45Z
[ "python" ]
I am learning Python I don't get one thing. Consider this code: ``` class Stack: def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def __getitem__(self,index): print "index",index return self.items...
The `for` loop doesn't know how to iterate over your object specifically because you have not implemented `__iter__()`, so it uses the default iterator. This starts at index 0 and goes until it gets an `IndexError` by asking for index 3. See <http://effbot.org/zone/python-for-statement.htm>. Your implementation would ...
How do I print a Celsius symbol with matplotlib?
8,440,117
7
2011-12-09T01:43:50Z
8,440,294
14
2011-12-09T02:22:50Z
[ "python", "unicode", "latex", "matplotlib" ]
I want to print an axis label: "Temperature (℃)". How do I do it? A snippet is this: ``` # -*- coding: utf-8 -*- import matplotlib.pyplot as plt x = range(10,60,1) y = range(-100, 0, 2) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x,y) ax.set_xlabel('Temperature (℃)') ``` For that last line I have tried: ...
Use the LaTeX interpreter to make the degree symbol. ``` ax.set_xlabel('Temperature ($^\circ$C)') ``` Here's the results: ![enter image description here](http://i.stack.imgur.com/FlsPA.png)
Setting styles in Openpyxl
8,440,284
31
2011-12-09T02:21:27Z
8,441,753
64
2011-12-09T06:13:38Z
[ "python", "excel", "xlsx", "openpyxl" ]
I need advice on setting styles in Openpyxl. I see that the NumberFormat of a cell can be set, but I also require setting of font colors and attributes (bold etc). There is a style.py class but it seems I can't set the style attribute of a cell, and I don't really want to start tinkering with the openpyxl source code....
As of openpyxl version 1.5.7, I have successfully applied the following worksheet style options... ``` from openpyxl.reader.excel import load_workbook from openpyxl.workbook import Workbook from openpyxl.styles import Color, Fill from openpyxl.cell import Cell # Load the workbook... book = load_workbook('foo.xlsx') ...
Setting styles in Openpyxl
8,440,284
31
2011-12-09T02:21:27Z
25,555,701
10
2014-08-28T18:34:35Z
[ "python", "excel", "xlsx", "openpyxl" ]
I need advice on setting styles in Openpyxl. I see that the NumberFormat of a cell can be set, but I also require setting of font colors and attributes (bold etc). There is a style.py class but it seems I can't set the style attribute of a cell, and I don't really want to start tinkering with the openpyxl source code....
As of openpyxl 2.0, styles are immutable. If you have a `cell`, you can (e.g.) set bold text by: `cell.style = cell.style.copy(font=cell.style.font.copy(bold=True))` Yes, this is annoying.
Stripping payload from a tcpdump?
8,440,709
5
2011-12-09T03:30:41Z
8,441,995
7
2011-12-09T06:44:20Z
[ "python", "networking", "tcp", "tcpdump", "scapy" ]
Is there an automated way (either in tcpdump or via a helper app Out There) to generate a pcap file that contains only Ethernet, IP and Layer 4 (TCP in my case) headers, so that there is no payload/application data in the resulting pcap? I've found that since header sizes often vary, it's impossible to pick a capture s...
You can strip out the TCP payload very easily with Python's [`scapy`](http://www.secdev.org/projects/scapy/) module **BEFORE** ``` [mpenning@hotcoffee tshark_wd]$ tcpdump -n -r sample.pcap reading from file sample.pcap, link-type EN10MB (Ethernet) 00:25:42.443559 IP 192.168.12.237.1052 > 192.168.12.236.22: Flags [P....
Draw lines from x axis to points
8,441,882
4
2011-12-09T06:29:24Z
8,442,122
9
2011-12-09T07:01:23Z
[ "python", "matplotlib" ]
I have a bunch of points that I am trying to plot using matplotlib. For each point (a,b) I want to draw the line X = a for Y in [0,b]. Any idea how to do this?
You just draw each line using the two endpoints. A vertical line X=a for Y in [0,b] has endpoints (x,y) = (a,0) and (a,b). So: ``` # make up some sample (a,b): format might be different to yours but you get the point. import matplotlib.pyplot as plt points = [ (1.,2.3), (2.,4.), (3.5,6.) ] # (a1,b1), (a2,b2), ... plt...
Aggregate items in dict
8,443,087
5
2011-12-09T08:50:59Z
8,443,646
7
2011-12-09T09:44:57Z
[ "python" ]
I have a list like this: ``` A = [{u'CI': {u'RP': 1}}, {u'CI': {u'RP': 1}}, {u'JI': {u'RP': 1}}] ``` and I want merge same keys and increment value in dict. Example: From these values : ``` {u'CI': {u'RP': 1}}, {u'CI': {u'RP': 1}} ``` I will have: ``` {u'CI': {u'RP': 2}} ``` final list result is: ``` A = [{u'...
You can use a [`defaultdict` from `collections`](http://docs.python.org/library/collections.html#collections.defaultdict) to help here. This is a `dict` that will create default values for missing keys. Firstly you'll want a `defaultdict` that has a default value of `0` to do your aggregation. Next you'll need a `defau...
Call a python main from another python script
8,443,880
2
2011-12-09T10:05:00Z
8,443,963
8
2011-12-09T10:11:56Z
[ "python" ]
I have been giving some huge command line tool from a colleague. The main reads a bunch of arguments, parses those using the elegant `import OptionParser` later on and does the job. ``` if __name__ == '__main__': main(sys.argv) ``` I can either dig into the code and copy paste loads of code, or find a way to use ...
You don't need to do cut and paste or launch a new Python interpreter. You should be able to [`import` the other script](http://docs.python.org/reference/simple_stmts.html#import). For example, if your colleague's script is called `somescript.py` you could do: ``` import somescript args = ['one','two'] somescript.mai...
Python noob: "ImportError: No module named internet"
8,443,931
4
2011-12-09T10:09:43Z
8,444,001
20
2011-12-09T10:15:41Z
[ "python", "module", "twisted" ]
I'm trying to get Python twisted to work on my Ubuntu 11.04 box. I did `sudo apt-get install python-twisted` However, when I try the following code: ``` from twisted.internet import protocol, reactor class Echo(protocol.Protocol): def dataReceived(self, data): self.transport.write(data) class EchoFacto...
The problem is the name of your file. Python looks first in your current directory for modules. When you try to import `twisted.internet` it finds the file in your folder, which is called `twisted.py`. But there can not `internet` submodule be found. If you rename your file, Python will load the correct `twisted` and e...
Reverse sort and argsort in python
8,445,323
14
2011-12-09T12:12:07Z
8,445,471
10
2011-12-09T12:28:20Z
[ "python", "numpy", "scipy", "information-retrieval", "sparse-matrix" ]
I'm trying to write a function in Python (still a noob!) which returns indices and scores of documents ordered by the inner products of their tfidf scores. The procedure is: * Compute vector of inner products between doc `idx` and all other documents * Sort in descending order * Return the "scores" and indices from th...
I don't think there's any real need to skip the `toarray`. The `v` array will be only `n_docs` long, which is dwarfed by the size of the `n_docs` × `n_terms` tf-idf matrix in practical situations. Also, it will be quite dense since any term shared by two documents will give them a non-zero similarity. Sparse matrix re...
Can wtforms custom validator make a field optional?
8,445,332
6
2011-12-09T12:13:26Z
8,450,362
8
2011-12-09T19:00:44Z
[ "python", "flask", "wtforms" ]
I'm using a custom validator to check a field is not empty if a check box is checked. It checks correctly but regardless it always still validating if the value is a number. Basically I need a field to stop validation under certain conditions of the form. Is there a way for the custom validator to stop validation on ...
Yes, custom validators can control the validation flow just like the built-in Optional and Required validators. To control the validation flow, you use the `StopValidation` exception, and no further validation will be done. If StopValidation is raised with a message, it will be added to the errors list, otherwise if t...
In python, how to convert a hex ascii string to raw internal binary string?
8,445,447
8
2011-12-09T12:25:52Z
8,445,492
9
2011-12-09T12:29:41Z
[ "python" ]
In python, how to convert a hex ASCII string to binary string? Example: > 01000001B8000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F303132333435362021222324 Needs to be converted to a binary string. (`0A` need to be converted to `1010`, not to ASCII bit `1000001` which...
Is this what you're searching for? ``` hex_string = '0A' '{0:b}'.format(int(hex_string, 16)) # returns '1010' ``` or ``` ''.join('{0:04b}'.format(int(c, 16)) for c in hex_string) ```
In python, how to convert a hex ascii string to raw internal binary string?
8,445,447
8
2011-12-09T12:25:52Z
8,445,553
12
2011-12-09T12:35:59Z
[ "python" ]
In python, how to convert a hex ASCII string to binary string? Example: > 01000001B8000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F303132333435362021222324 Needs to be converted to a binary string. (`0A` need to be converted to `1010`, not to ASCII bit `1000001` which...
``` import base64 data = base64.b16decode("01000001B8000102030405") ```
Fabric - sudo -u
8,445,698
14
2011-12-09T12:47:12Z
8,445,745
35
2011-12-09T12:51:41Z
[ "python", "django", "sudo", "fabric" ]
I'm using fabric to launch a command on a remote server. I'd like to launch this command as a different user (neither the one connected nor root). ``` def colstat(): run('python manage.py collectstatic --noinput') ``` Trying ``` def colstat(): sudo('-u www-data python manage.py collectstatic --noinput') ``` O...
Judging from the [documentation](http://docs.fabfile.org/en/latest/api/core/operations.html#fabric.operations.sudo): ``` sudo('python manage.py collectstatic --noinput', user='www-data') ``` HTH!
To prevent a function from printing in the batch console in Python
8,447,185
9
2011-12-09T14:47:54Z
8,447,352
14
2011-12-09T14:59:18Z
[ "python", "printing", "batch-file" ]
Well, the headline seems to me sufficient. I use some function that at some points print something in the console. As I can't modify them, I would like to know if there is a solution to not printing while using these functions. Thanks a lot ! Nico
Yes, you can redirect `sys.stdout`: ``` import sys import os sys.stdout = open(os.devnull, "w") my_nasty_function() sys.stdout = sys.__stdout__ ``` Just replace `my_nasty_function` with your actual function. **EDIT:** Now should work on windows aswell and makes use of `sys.__stdout__` instead of a backup variable...
ctypes and string
8,447,308
8
2011-12-09T14:56:07Z
8,447,487
9
2011-12-09T15:09:00Z
[ "python", "c", "ctypes" ]
I have a simple C-file: ``` char* initializetest() { char * test = malloc(1000); return test; } int searchtest( char* test ) { strcpy(test,"test"); return 0; } main() { char *test = initializetest(); searchtest(test); printf("%s\n", test ); } ``` and python file: ``` from ctypes import *...
``` from ctypes import * charptr = POINTER(c_char) test = CDLL('test.so') test.initializetest.argtypes = [] test.initializetest.restype = charptr test.searchtest.argtypes = [charptr] test.searchtest.restype = c_int buf = test.initializetest() test.searchtest(buf) print cast(buf, c_char_p).value # TODO Release the "b...
How to do "insert if not exist else update" with mongoengine?
8,447,502
8
2011-12-09T15:10:04Z
16,100,666
24
2013-04-19T08:44:59Z
[ "python", "django", "mongodb", "mongoengine" ]
I'm working with mongoengine in Django, this is my document defination: ``` class Location(mongoengine.Document): user_id = mongoengine.IntField(required=True) point = mongoengine.GeoPointField(required=True) ``` I want to do this: given a `user_id` and a `point`: if there is no document that have t...
Note that `get_or_create` is now scheduled to be deprecated, because with no transaction support in MongoDB it cannot ensure atomicity. The preferred way is [update](http://mongoengine-odm.readthedocs.org/en/latest/apireference.html#mongoengine.queryset.QuerySet.update) with upsert: ``` Location.objects(user_id=user_...
Is there a filter for divide for Django Template?
8,447,913
15
2011-12-09T15:42:16Z
8,447,990
28
2011-12-09T15:48:42Z
[ "python", "django" ]
I noticed there is built-in `add` filter, but I wasn't able to find `divide`. I am new to Django and not sure if there is a such filter.
There is not it. But if you are a little hacker.... <http://slacy.com/blog/2010/07/using-djangos-widthratio-template-tag-for-multiplication-division/> > to compute A\*B: {% widthratio A 1 B %} > > to compute A/B: {% widthratio A B 1 %} > > to compute A^2: {% widthratio A 1 A %} > > to compute (A+B)^2: {% widthratio A...
Is there a filter for divide for Django Template?
8,447,913
15
2011-12-09T15:42:16Z
17,400,676
9
2013-07-01T09:01:02Z
[ "python", "django" ]
I noticed there is built-in `add` filter, but I wasn't able to find `divide`. I am new to Django and not sure if there is a such filter.
Using a custom filter: ``` register = template.Library() @register.filter def divide(value, arg): try: return int(value) / int(arg) except (ValueError, ZeroDivisionError): return None ```
Is it possible to modify variable in python that is in outer, but not global, scope?
8,447,947
27
2011-12-09T15:45:07Z
8,448,011
30
2011-12-09T15:50:31Z
[ "python", "python-2.7" ]
Given following python 2.7 code: ``` def A() : def B() : b = 1 def C() : # I can access 'b' from here. print( b ) # But can i modify 'b' here? 'global' and assignment will not work. C() print( b ) B() A() ``` For the code in `C()` function variable `b` is in outer scope, but not ...
Python 3.x has the [`nonlocal` keyword](http://docs.python.org/py3k/reference/simple_stmts.html#the-nonlocal-statement). I think this does what you want, but I'm not sure if you are running python 2 or 3. > The nonlocal statement causes the listed identifiers to refer to > previously bound variables in the nearest enc...
Is it possible to modify variable in python that is in outer, but not global, scope?
8,447,947
27
2011-12-09T15:45:07Z
21,688,502
7
2014-02-10T21:40:19Z
[ "python", "python-2.7" ]
Given following python 2.7 code: ``` def A() : def B() : b = 1 def C() : # I can access 'b' from here. print( b ) # But can i modify 'b' here? 'global' and assignment will not work. C() print( b ) B() A() ``` For the code in `C()` function variable `b` is in outer scope, but not ...
You can use an empty class to hold a temporary scope. It's like the mutable but a bit prettier. ``` def outer_fn(): class FnScope: b = 5 c = 6 def inner_fn(): FnScope.b += 1 FnScope.c += FnScope.b inner_fn() inner_fn() inner_fn() ``` This yields the following interactive output: ...
Remove more than one key from Python dict
8,448,202
5
2011-12-09T16:02:45Z
8,448,255
10
2011-12-09T16:05:40Z
[ "python", "dictionary" ]
Is there any efficient shortcut method to delete more than one key at a time from a python dictionary? For instance; ``` x = {'a': 5, 'b': 2, 'c': 3} x.pop('a', 'b') print x {'c': 3} ```
Use [the `del` statement](http://docs.python.org/tutorial/datastructures.html#the-del-statement): ``` x = {'a': 5, 'b': 2, 'c': 3} del x['a'], x['b'] print x {'c': 3} ```
python - tkinter -- Having trouble with resizing multiple grids
8,448,690
2
2011-12-09T16:37:37Z
8,451,563
7
2011-12-09T20:52:00Z
[ "python", "tkinter" ]
i have the following code and i can't manage to resize properly the frames. When i resize, everything disappears.. When i run it, it's ok.But when i resize it, i want to keep the original view. ``` from Tkinter import * import os,sys ALL=N+S+E+W class Application(Frame): def __init__(self,master=None): ...
Your problem is that you seem to not quite understand how grid works. For example, you are putting only two widgets in the red frame (self.myentry and self.text) yet you are putting them in column 2 and 4. Are you aware that the columns are relative to their parent, not the GUI as a whole? You want them in column 0 *of...
Remove strings containing only white spaces from list
8,449,454
11
2011-12-09T17:35:27Z
8,449,520
17
2011-12-09T17:41:06Z
[ "python" ]
How do I delete empty strings from a list? I tried like this: ``` starring = ['Vashu Bhagnani', 'Khemchand Bhagnani', ' ', 'Jacky Bhagnani', ' ', 'Prashant Shah', ' '] output = filter(bool, starring) ``` Output I want: ``` ['Vashu Bhagnani', 'Khemchand Bhagnani', 'Jacky Bhagnani', 'Prashant Shah'] ``` But `output...
Only the empty string evaluates to `False` so you need to use `strip()` to remove any whitespace and we can then rely on non-blank strings being evaluated as true. ``` >>> starring = ['Vashu Bhagnani', 'Khemchand Bhagnani', ' ', 'Jacky Bhagnani', ' ', 'Prashant Shah', ' '] >>> sta...
What is the meaning of '*' in numpy?
8,450,055
4
2011-12-09T18:32:29Z
8,450,161
14
2011-12-09T18:43:11Z
[ "python", "numpy" ]
``` >>> shape=(2,2) >>> np.random.randn(*shape) array([[-1.64633649, -0.03132273], [-0.92331459, 1.05325462]]) ``` I can't find it in numpy's documentation. Any help is appreciated.
This is not NumPy-specific syntax; it is Python syntax. The so-called `*`-operator is Python syntax that does sequence unpacking in argument lists (see [Unpacking Argument Lists](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists)). The use in your example is to unpack the `shape` tuple into sep...
How to format print output into fixed width?
8,450,472
37
2011-12-09T19:10:54Z
8,450,514
57
2011-12-09T19:13:52Z
[ "python", "python-2.7", "format" ]
I have this code (printing the occurrence of the all permutations in a string) ``` def splitter(str): for i in range(1, len(str)): start = str[0:i] end = str[i:] yield (start, end) for split in splitter(end): result = [start] result.extend(split) ...
**EDIT 12.11.2013** - This answer is very old. It is still valid and correct, but people looking at this should prefer the [new format syntax](https://docs.python.org/2/library/string.html#format-string-syntax). You can use [string formatting](http://docs.python.org/library/stdtypes.html#string-formatting) like this: ...
How to format print output into fixed width?
8,450,472
37
2011-12-09T19:10:54Z
16,047,503
79
2013-04-16T21:32:37Z
[ "python", "python-2.7", "format" ]
I have this code (printing the occurrence of the all permutations in a string) ``` def splitter(str): for i in range(1, len(str)): start = str[0:i] end = str[i:] yield (start, end) for split in splitter(end): result = [start] result.extend(split) ...
I find using `str.format` much more elegant: ``` >>> '{0: <5}'.format('ss') 'ss ' >>> '{0: <5}'.format('sss') 'sss ' >>> '{0: <5}'.format('ssss') 'ssss ' >>> '{0: <5}'.format('sssss') 'sssss' ``` If you like the string to be align to the right use `>` instead of `<`: ``` >>> '{0: >5}'.format('ss') ' ss' ```
Method without return value in python c extension module
8,450,481
6
2011-12-09T19:11:18Z
8,450,880
9
2011-12-09T19:47:08Z
[ "python", "c", "python-c-api", "parallel-port", "python-extensions" ]
I'm trying to create a script in python that sends data through a parallel port. I'm creating my own module in C language. The problem is: when I try to execute my module, python crashes. No errors, no data, nothing. It simply closes. This is my module: ``` #include <Python.h> #include <sys/io.h> #define BaseAddr 0x...
Returning NULL to the python/c API indicates that an error has occurred. But since you didn't actually set an exception you get the error: > SystemError: error return without exception set If you are trying to return None, use: ``` return Py_BuildValue(""); ```
Method without return value in python c extension module
8,450,481
6
2011-12-09T19:11:18Z
8,451,069
12
2011-12-09T20:02:37Z
[ "python", "c", "python-c-api", "parallel-port", "python-extensions" ]
I'm trying to create a script in python that sends data through a parallel port. I'm creating my own module in C language. The problem is: when I try to execute my module, python crashes. No errors, no data, nothing. It simply closes. This is my module: ``` #include <Python.h> #include <sys/io.h> #define BaseAddr 0x...
All python functions should return a PyObject, unless when they want to raise an exception, as explained: here <http://docs.python.org/extending/extending.html#intermezzo-errors-and-exceptions> The error message you get `SystemError: error return without exception set`, is trying to tell you that your function returne...
Does PyPy translate itself?
8,452,396
48
2011-12-09T22:16:15Z
8,452,592
12
2011-12-09T22:37:27Z
[ "python", "pypy", "rpython" ]
Am I getting this straight? Does the PyPy interpreter actually interpret itself and then *translate itself?* So here's my current understanding: * RPython's toolchain involves partially executing the program to be translated to get a sort of preprocessed version to annotate and translate. * The PyPy interpreter, runn...
> Disclaimer: I'm not an expert on PyPy - in particular, I don't understand the details of the RPython translation, I'm only citing stuff that I've read before. For a more specific post on how RPython translation *may* work, check out this [answer](http://stackoverflow.com/a/6153933/832391). The answer is, yes, it can...
Does PyPy translate itself?
8,452,396
48
2011-12-09T22:16:15Z
8,569,919
65
2011-12-20T01:54:18Z
[ "python", "pypy", "rpython" ]
Am I getting this straight? Does the PyPy interpreter actually interpret itself and then *translate itself?* So here's my current understanding: * RPython's toolchain involves partially executing the program to be translated to get a sort of preprocessed version to annotate and translate. * The PyPy interpreter, runn...
PyPy's translation process is actually much less conceptually recursive than it sounds. Really all it is is a Python program that processes Python function/class/other objects (**not** Python source code) and outputs C code. But of course it doesn't process just **any** Python objects; it can only handle particular fo...
Convert string to ASCII value python
8,452,961
18
2011-12-09T23:23:49Z
8,452,992
32
2011-12-09T23:28:44Z
[ "python" ]
how would you convert a string to ascii values? For example hi would return 104105. I can individually do ord(h) and ord(i) but its going to be troublesome when there are a lot of letters.
You can use a list comprehension: ``` >>> s = 'hi' >>> [ord(c) for c in s] [104, 105] ```
Convert string to ASCII value python
8,452,961
18
2011-12-09T23:23:49Z
8,453,077
7
2011-12-09T23:37:36Z
[ "python" ]
how would you convert a string to ascii values? For example hi would return 104105. I can individually do ord(h) and ord(i) but its going to be troublesome when there are a lot of letters.
Here is a pretty concise way to perform the concatenation: ``` >>> s = "hello world" >>> ''.join(str(ord(c)) for c in s) '10410110810811132119111114108100' ``` And a sort of fun alternative: ``` >>> '%d'*len(s) % tuple(map(ord, s)) '10410110810811132119111114108100' ```
jinja2 recursive loop vs dictionary
8,453,007
8
2011-12-09T23:30:28Z
8,456,277
8
2011-12-10T11:45:11Z
[ "python", "jinja2", "jinja" ]
I have the following dictionary: ``` {'a': {'b': {'c': {}}}} ``` And the following Jinja2 template: ``` {% for key in dictionary recursive %} <li>{{ key }} {% if dictionary[key] %} <ul>{{ loop(dictionary[key]) }}</ul> {% endif %} </li> ...
You're right, `dictionary` isn't being updated in the recursion calls, and the loop cannot continue because the keys aren't found. A workaround to this problem is using just the variables assigned in the for loop. In the dictionary example, this means to iterate through the items of the dictionary instead of just the ...
compress numpy array(matrix) by removing columns using another numpy array as mask
8,453,501
6
2011-12-10T00:53:28Z
8,453,589
8
2011-12-10T01:11:55Z
[ "python", "numpy" ]
I have a 2D `numpy` array (i.e matrix) `A` which contains useful data interspread with garbage in the form of column vectors as well as a 'selection' array `B` which contains '1' for those columns that are important and 0 for those that are not. Is there a way to select only those columns from `A` that correspond to on...
``` >>> A array([[ 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]]) >>> B = NP.array([ 0, 1, 0, 1, 0]) >>> # convert the indexing array to a boolean array >>> B = NP.array(B, dtype=bool) >>> # index A against B--inde...
Does anyone know the word that built-in function ord() abbreviate for?
8,453,615
4
2011-12-10T01:15:57Z
8,453,620
12
2011-12-10T01:16:44Z
[ "python", "function", "built-in" ]
python has a built-in function `ord()`, I think it must be a anbbreviation. Just like another built-in function `chr()`, which is an abbreviation of the word "character". Does anyone know the word that built-in function `ord()` abbreviate for?
It's an abbreviation for "ordinal". *Ordinal numbers* are counting numbers -- i.e., 1, 2, 3. `ord()` converts the character into its (countable) position in the character set.
Is there a matplotlib counterpart of Matlab "stem3"?
8,453,726
8
2011-12-10T01:41:19Z
8,454,036
11
2011-12-10T02:54:58Z
[ "python", "matlab", "matplotlib" ]
It is quite easy to make a 3d stem plot with stem3 command as documented in <http://www.mathworks.com/help/techdoc/ref/stem3.html> I wonder if there is a similar command in matplotlib? I checked the online document for the latest version, but could not find one. Can anyone give some suggestions?
I'm unaware of any direct equivalent of `stem3` in matplotlib. However, it isn't hard to draw such figures (at least in its basic form) using [Line3D](http://matplotlib.sourceforge.net/mpl_toolkits/mplot3d/api.html#mpl_toolkits.mplot3d.art3d.Line3D)s: ``` import matplotlib.pyplot as plt import mpl_toolkits.mplot3d.art...
python can't send attachment files through email
8,456,181
6
2011-12-10T11:27:50Z
8,456,942
12
2011-12-10T13:47:17Z
[ "python", "email" ]
I have the following code which works fine, but it doesn't send the attachment files. ``` import smtplib import os from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.MIMEBase import MIMEBase from email import Encoders msg=MIMEMultipart() def mymail(address,body,format,myli...
I would recommend to use [MIMEApplication](http://docs.python.org/library/email.mime.html#email.mime.application.MIMEApplication%20MIMEApplication) instead for the attachment. You also do not need to do all the payload encoding manually since that is already done automatically. This example works for me: ``` from emai...
GtkSpinButton disabled by default in Glade
8,456,578
4
2011-12-10T12:44:14Z
8,457,166
7
2011-12-10T14:26:26Z
[ "python", "pygtk", "glade" ]
I added GtkSpinButton to my dialog from Glade and it is disabled by default: ![enter image description here](http://i.stack.imgur.com/ZwsYn.png) What should I do to make arrows enabled?
You need to configure the GtkSpinButton with the Adjustment object as follows (example values): ``` adj = gtk.Adjustment(1, 1, 99, 1, 1, 1) spinBtn = self.builder.get_object("spinbutton1") spinBtn.configure(adj, 1, 0) ```
Django password reset email subject
8,456,714
3
2011-12-10T13:11:10Z
8,457,769
10
2011-12-10T15:55:46Z
[ "python", "django" ]
I have successfully added my own custom HTML templates for the password reset pages in Django and it's all working nicely. The only bit I can't work out it how to include my own email subject. The default is "Password reset on [my site name]" and I can obviously change the site name in admin but does anyone know how t...
**Development Version** Just create new file `registration/password_reset_subject.txt` in your templates dir. This will override default django subject See <https://github.com/django/django/blob/master/django/contrib/auth/templates/registration/password_reset_subject.txt> and <https://github.com/django/django/blob/m...
Call a function defined in another function
8,457,669
2
2011-12-10T15:41:48Z
8,457,693
11
2011-12-10T15:45:30Z
[ "python", "python-3.x" ]
Can I call a function nested inside another function from the global scope in python3.2? ``` def func1(): def func2(): print("Hello") return return ``` Is ther a way to call func2() from outside func1()?
No, unless you return the function: ``` def func1(): def func2(): print("Hello") return func2 innerfunc = func1() innerfunc() ``` or even ``` func1()() ```
Call a function defined in another function
8,457,669
2
2011-12-10T15:41:48Z
8,457,771
8
2011-12-10T15:55:56Z
[ "python", "python-3.x" ]
Can I call a function nested inside another function from the global scope in python3.2? ``` def func1(): def func2(): print("Hello") return return ``` Is ther a way to call func2() from outside func1()?
You **want** to use [@larsmans'](http://stackoverflow.com/a/8457693/89391) solution, but theoretically you can cut yourself into the code object of the locally accessible `func1` and slice out the code object of `func2` and execute that: ``` #!/usr/bin/env python def func1(): def func2(): print("Hello") ...
Convert CSS selector to XPath in Python
8,458,052
3
2011-12-10T16:37:48Z
11,067,636
8
2012-06-16T22:47:52Z
[ "python", "xpath", "css-selectors" ]
Is there a Python library that can parse an CSS selector and emit an equivalent XPath expression? For Ruby, there is [Nokogiri](http://nokogiri.org/Nokogiri/CSS.html).
I recently took over cssselect and made it an independent project after extracting it from lxml: <http://packages.python.org/cssselect/> It does precisely what the question asks for. The XPath expressions produced can then be used in lxml. PyQuery actually uses cssselect (formerly lxml.cssselect)
swap letters in a string in python
8,458,244
5
2011-12-10T17:05:08Z
8,458,282
14
2011-12-10T17:09:55Z
[ "python" ]
I am trying to switch the first character in a string and move it to the end of the string. It needs to repeat the rotation a number of n times. For example, `rotateLeft(hello,2)=llohe`. I tried doing ``` def rotateLeft(str,n): rotated="" rotated=str[n:]+str[:n] return rotated ``` Is this right, and how ...
You can shorten it to ``` def rotate(strg,n): return strg[n:] + strg[:n] ``` and simply use negative indices to rotate "to the right": ``` >>> rotate("hello", 2) 'llohe' >>> rotate("hello", -1) 'ohell' >>> rotate("hello", 1) 'elloh' >>> rotate("hello", 4) 'ohell' >>> rotate("hello", -3) 'llohe' >>> rotate("hello...
Reverse each word in a string
8,458,434
4
2011-12-10T17:28:30Z
8,458,451
8
2011-12-10T17:30:56Z
[ "python", "string" ]
I am having a small problem in my code. I am trying to reverse the words and the character of a string. For example "the dog ran" would become "ehT god nar" The code almost works. It just does not add spaces. How would you do that? ``` def reverseEachWord(str): reverseWord="" list=str.split() for word in list: ...
You are on the right track. The main issue is that `""` is an empty string, not a space (and even if you fix this, you probably don't want a space after the final word). Here is how you can do this more concisely: ``` >>> s='The dog ran' >>> ' '.join(w[::-1] for w in s.split()) 'ehT god nar' ```
PyGame in a virtualenv on OS X with brew?
8,458,911
22
2011-12-10T18:37:52Z
8,460,209
28
2011-12-10T21:56:10Z
[ "python", "osx", "pygame", "virtualenv" ]
Can't quite figure out how to install PyGame in a virtualenv on OSX Lion. I'd really like to keep things contained in the virtualenv, if at all possible. I've tried downloading the source for PyGame and running the included `setup.py` in the virtualenv, but it seems to be having a bunch of issues finding the SDL requi...
Yes, you can use it in [3 steps with brew](https://bitbucket.org/pygame/pygame/issue/82/homebrew-on-leopard-fails-to-install#comment-627494): ``` brew install python brew install sdl sdl_image sdl_mixer sdl_ttf smpeg portmidi /usr/local/share/python/pip install hg+http://bitbucket.org/pygame/pygame ``` (this is how ...
Sort tuples based on second parameter
8,459,231
39
2011-12-10T19:29:33Z
8,459,243
69
2011-12-10T19:30:49Z
[ "python", "sorting", "tuples" ]
I have a list of tuples that look something like this: ``` ("Person 1",10) ("Person 2",8) ("Person 3",12) ("Person 4",20) ``` What I want produced, is the list sorted in ascending order, by the second value of the tuple. So L[0] should be `("Person 2", 8)` after sorting. How can I do this? Using Python 3.2.2 If that...
You can use the `key` parameter to `list.sort()`: ``` my_list.sort(key=lambda x: x[1]) ``` or, slightly faster, ``` my_list.sort(key=operator.itemgetter(1)) ``` (As with any module, you'll need to `import operator` to be able to use it.)