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
Re-read an open file Python
17,021,863
5
2013-06-10T10:34:19Z
17,021,923
8
2013-06-10T10:38:13Z
[ "python", "file", "testing" ]
I have a script that reads a file and then completes tests based on that file however I am running into a problem because the file reloads after one hour and I cannot get the script to re-read the file after or at that point in time. So: GETS NEW FILE TO READ Reads file performs tests on file GET NEW FILE TO READ (wit...
Either `seek` to the beginning of the file ``` with open(...) as fin: fin.read() # read first time fin.seek(0) # offset of 0 fin.read() # read again ``` or open the file again (I'd prefer this way since you are otherwise keeping the file open for an hour doing nothing between passes) ``` with open(....
Assignment rules
17,023,906
5
2013-06-10T12:28:47Z
17,023,959
8
2013-06-10T12:31:02Z
[ "python", "python-3.x" ]
I've noticed a (seemingly) strange behaviour with assignments, which has led me several times to do programming mistakes. See the following example first : ``` >>> i = 0 >>> t = (i,) >>> t (0,) >>> i += 1 >>> t (0,) ``` As expected, the value of the unique element of `t` does not change, even after the value of `i` ...
That's because integers are immutable and lists are mutable. ``` >>> i = 0 >>> t = (i,) >>> t[0] is i # both of them point to the same immutable object True >>> i += 1 # We can't modify an immutable object, changing `i` simply # makes it point to a new object 2. # All other references to the...
Is there a "and=" operator for boolean?
17,026,239
3
2013-06-10T14:26:47Z
17,026,295
9
2013-06-10T14:29:27Z
[ "python", "boolean", "operators" ]
There is the "+=" operator for, namely, int. ``` a = 5 a += 1 b = a == 6 # b is True ``` Is there a "and=" operator for bool? ``` a = True a and= 5 > 6 # a is False a and= 5 > 4 # a is still False ``` I know, this 'and=' operator would correspond to: ``` a = True a = a and 5 > 6 # a is False a = a and 5 > 4 # a is...
Yes - you can use `&=`. ``` a = True a &= False # a is now False a &= True # a is still False ``` You can similarly use `|=` for "or=". It should be noted (as in the comments below) that this is actually a bitwise operation; it will have the expected behavior **only** if `a` starts out as a Boolean, and the opera...
Cython either marginally faster or slower than pure Python
17,027,487
4
2013-06-10T15:29:30Z
17,029,243
10
2013-06-10T17:08:48Z
[ "python", "python-2.7", "numpy", "scipy", "cython" ]
I am using several techniques (**NumPy**, **Weave** and **Cython**) to perform a Python performance benchmark. What the code basically does mathematically is `C = AB`, where A, B and C are `N x N` matrices (**NOTE:** this is a matrix product and not an element-wise multiplication). I have written 5 distinct implementa...
Python lists and high performance math are incompatible, forget about `cython_list_matmul`. The only problem with your `cython_array_matmul` is incorrect usage of indexing. It should be ``` C[i,k] += A[i,j] * B[j,k] ``` That's how numpy arrays are indexed in Python and that's the syntax Cython optimizes. With this c...
How to skip the extra newline while printing lines read from a file?
17,027,690
5
2013-06-10T15:40:17Z
17,027,711
10
2013-06-10T15:41:29Z
[ "python" ]
I am reading input for my python program from stdin (I have assigned a file object to stdin). The number of lines of input is not known beforehand. Sometimes the program might get 1 line, 100 lines or even no lines at all. ``` import sys sys.stdin = open ("Input.txt") sys.stdout = open ("Output.txt", "w") def main()...
the python `print` statement adds a newline, but the original line already had a newline on it. You can suppress it by adding a comma at the end: ``` print line , #<--- trailing comma ``` For python3, (where `print` becomes a function), this looks like: ``` print(line,end='') #rather than the default `print(line,end...
Using Python 3.3 in C++ 'python33_d.lib' not found
17,028,576
5
2013-06-10T16:26:27Z
17,659,306
9
2013-07-15T16:39:29Z
[ "c++", "python", "visual-c++" ]
I am trying to `#include <Python.h>` in my C++ code and when I go to compile my code I get the error of: ``` fatal error LNK1104: cannot open file 'python33_d.lib' ``` Now I have tried to find the `python33_d.lib` file on my computer to include in my linker dependencies, but I is not found. I have been able to find `...
In the event that you need a debug version (as I do for work), it is possible to build the library yourself: 1. Download the source tarball from <http://www.python.org/download> 2. Extract the tarball (7zip will do the trick) and go into the resulting directory (should be something like Python-3.3.2). 3. From the Pyth...
Is this duck-typing in Python?
17,028,722
6
2013-06-10T16:35:37Z
17,029,047
19
2013-06-10T16:55:10Z
[ "python", "python-3.x", "duck-typing" ]
Here is some Ruby code: ``` class Duck def help puts "Quaaaaaack!" end end class Person def help puts "Heeeelp!" end end def InTheForest x x.help end donald = Duck.new john = Person.new print "Donald in the forest: " InTheForest donald print "John in the forest: " InTheForest john ``` And, I tran...
The code does not show the whole story. Duck typing is about trying something and handling exceptions if they occur. As long it quacks, treat it like a duck, otherwise, treat it differently. ``` try: dog.quack() except AttributeError: dog.woof() ``` This behavior is explained at the top of the [wikipedia Duck...
Speed up web scraper
17,029,752
7
2013-06-10T17:42:33Z
17,030,686
12
2013-06-10T18:46:56Z
[ "python", "performance", "web-scraping", "scrapy", "scrapy-spider" ]
I am scraping 23770 webpages with a pretty simple web scraper using `scrapy`. I am quite new to scrapy and even python, but managed to write a spider that does the job. It is, however, really slow (it takes approx. 28 hours to crawl the 23770 pages). I have looked on the `scrapy` webpage and the mailing lists and `sta...
Here's a collection of things to try: * use latest scrapy version (if not using already) * check if non-standard middlewares are used * try to increase `CONCURRENT_REQUESTS_PER_DOMAIN`, `CONCURRENT_REQUESTS` settings ([docs](http://doc.scrapy.org/en/latest/topics/settings.html#concurrent-requests)) * turn off logging ...
Can Redis write out to a database like PostgreSQL?
17,033,031
8
2013-06-10T21:16:52Z
17,037,464
9
2013-06-11T06:03:05Z
[ "python", "django", "postgresql", "redis", "redis-cache" ]
I've been using PostgreSQL for the longest time. All of my data lives inside Postgres. I've recently looked into redis and it has a lot of powerful features that would otherwise take a couple of lines in Django (python) to do. Redis data is persistent as long the machine it's running on doesn't go down and you can conf...
Redis is increasingly used as a caching layer, much like a more sophisticated memcached, and is very useful in this role. You usually use Redis as a *write-through* cache for data you want to be durable, and *write-back* for data you might want to accumulate then batch write (where you can afford to lose recent data). ...
Python Logging to multiple log files from different classes
17,035,077
10
2013-06-11T01:02:48Z
17,037,016
30
2013-06-11T05:26:09Z
[ "python", "logging" ]
I want to write a python class which uses Python Logging. This Python class will be responsible for the creating a file with a given name in init function. I want to create a object of the above class in two or more classes and expect two or files getting generated. I tried writing this class but I am not able to cre...
Sounds like the internals of your class should probably have a [`Logger`](http://docs.python.org/2/library/logging.html#logger-objects) and that you'll want to add a [`FileHandler`](http://docs.python.org/2/library/logging.handlers.html#filehandler) to the `Logger`. You might want to consider just using a factory metho...
Show terminal output in a gui window using python Gtk
17,038,063
3
2013-06-11T06:48:57Z
17,105,259
7
2013-06-14T09:25:20Z
[ "python", "gtk" ]
I am developing a software and in that I want a window, that will display the output thrown by the terminal (like a package manager does ). Example, if i give the install command, the installation process should be outptutted to my window and not the terminal. Is there a way to do this in python Gtk?
If you are on Linux (as you state), something like this should work: ``` import gtk import gobject import pango import os from subprocess import Popen, PIPE import fcntl wnd = gtk.Window() wnd.set_default_size(400, 400) wnd.connect("destroy", gtk.main_quit) textview = gtk.TextView() fontdesc = pango.FontDescription(...
all possible phase combination
17,038,124
5
2013-06-11T06:53:35Z
17,038,181
10
2013-06-11T06:56:43Z
[ "python" ]
Suppose, I have a list of > 1,1 and it can take either + or - sign. So the possible combination would be 2 to the power 2. ``` 1 1 1 -1 -1 1 -1 -1 ``` Similarly, I have a list of > 1,1,1 and it can take either + or - sign. So the possible combination would be 2 to the power 3. ``` -1 1 -1 -1 1 1 1 ...
``` >>> import itertools >>> lst = [1,1,1] >>> for xs in itertools.product([1,-1], repeat=len(lst)): ... print([a*b for a,b in zip(lst, xs)]) ... [1, 1, 1] [1, 1, -1] [1, -1, 1] [1, -1, -1] [-1, 1, 1] [-1, 1, -1] [-1, -1, 1] [-1, -1, -1] ```
splitting a string based on tab in the file
17,038,426
14
2013-06-11T07:13:17Z
17,038,485
33
2013-06-11T07:16:11Z
[ "python", "string" ]
I have file that contains values separated by tab ("\t"). I am trying to create a list and store all values of file in the list. But I get some problem. Here is my code. ``` line = "abc def ghi" values = line.split("\t") ``` It works fine as long as there is only one tab between each value. But if there is one than o...
You can use `regex` here: ``` >>> import re >>> strs = "foo\tbar\t\tspam" >>> re.split(r'\t+', strs) ['foo', 'bar', 'spam'] ``` **update:** You can use `str.rstrip` to get rid of trailing `'\t'` and then apply regex. ``` >>> yas = "yas\t\tbs\tcda\t\t" >>> re.split(r'\t+', yas.rstrip('\t')) ['yas', 'bs', 'cda'] ```
sorting a list with objects of a class as its items
17,038,639
4
2013-06-11T07:25:36Z
17,038,658
8
2013-06-11T07:26:52Z
[ "python", "list", "class", "sorting" ]
i have a python list whose items are objects of a class with various attributes such as birthday\_score, anniversary\_score , baby\_score..... I want to to sort the list on the basis of one of these attributes ,say anniversary\_score. How do i do it ?
``` your_list.sort(key = lambda x : x.anniversary_score) ``` or if the attribute name is a string then you can use : ``` import operator your_list.sort(key=operator.attrgetter('anniversary_score')) ```
If I send a python 'Signal' object from a function, what should the "sender" argument be?
17,043,163
13
2013-06-11T11:38:54Z
17,043,380
9
2013-06-11T11:50:35Z
[ "python", "django", "signals" ]
If I send a Signal from a module function (a django view function as it happens), that is not inside a Class, it's not obvious (to me) what the sender should be - if anything? Is `sender=None` appropriate in this case? Alternatively, the function is invoked by an HTTP request, which I currently pass in as a separate a...
The django.dispatch.Dispatcher [source](https://github.com/django/django/blob/master/django/dispatch/dispatcher.py#L159) simply says it should be ``` "...[t]he sender of the signal. Either a specific object or None." ``` which then ties in with the receiver via [connect()](https://github.com/django/django/blob/master...
Setting the fmt option in numpy.savetxt
17,043,393
8
2013-06-11T11:50:58Z
17,044,898
16
2013-06-11T13:07:34Z
[ "python", "arrays", "string", "numpy", "save" ]
I am looking at the numpy.savetxt, and am stuck at the fmt option. I tried looking at [here](http://docs.python.org/2/library/stdtypes.html#string-formatting) and also the reference in the link below all the letters that can be used for the fmt option sort give me a general sense of what is going on. What I do not un...
You can use the `fmt` parameter in many ways, here are some examples to give you some insight. ``` import numpy as np a = np.array([[11,12,13,14], [21,22,23,24]]) ``` 1) `np.savetxt('tmp.txt',a, fmt='%1.3f')` ``` 11.000 12.000 13.000 14.000 21.000 22.000 23.000 24.000 ``` 2) `np.savetxt('tmp.txt',a, f...
Python dump dict to json file
17,043,860
35
2013-06-11T12:15:18Z
17,043,913
12
2013-06-11T12:18:05Z
[ "python", "json", "dictionary", "d3.js", "treemap" ]
I have a dict like this: ``` sample = {'ObjectInterpolator': 1629, 'PointInterpolator': 1675, 'RectangleInterpolator': 2042} ``` I can't figure out how to dump the dict to a `json` file as showed below: ``` { "name": "interpolator", "children": [ {"name": "ObjectInterpolator", "size": 1629}, ...
``` d = {"name":"interpolator", "children":[{'name':key,"size":value} for key,value in sample.items()]} json_string = json.dumps(d) ``` Of course, it's unlikely that the order will be exactly preserved ... But that's just the nature of dictionaries ...
Python dump dict to json file
17,043,860
35
2013-06-11T12:15:18Z
17,060,754
8
2013-06-12T08:17:19Z
[ "python", "json", "dictionary", "d3.js", "treemap" ]
I have a dict like this: ``` sample = {'ObjectInterpolator': 1629, 'PointInterpolator': 1675, 'RectangleInterpolator': 2042} ``` I can't figure out how to dump the dict to a `json` file as showed below: ``` { "name": "interpolator", "children": [ {"name": "ObjectInterpolator", "size": 1629}, ...
Combine the answer of @mgilson and @gnibbler, I found what I need was this: ``` d = {"name":"interpolator", "children":[{'name':key,"size":value} for key,value in sample.items()]} j = json.dumps(d, indent=4) f = open('sample.json', 'w') print >> f, j f.close() ``` It this way, I got a pretty-print json file. The...
Python dump dict to json file
17,043,860
35
2013-06-11T12:15:18Z
26,057,360
54
2014-09-26T10:22:42Z
[ "python", "json", "dictionary", "d3.js", "treemap" ]
I have a dict like this: ``` sample = {'ObjectInterpolator': 1629, 'PointInterpolator': 1675, 'RectangleInterpolator': 2042} ``` I can't figure out how to dump the dict to a `json` file as showed below: ``` { "name": "interpolator", "children": [ {"name": "ObjectInterpolator", "size": 1629}, ...
``` import json with open('result.json', 'w') as fp: json.dump(sample, fp) ``` This is an easier way to do it. The second line of code determines the destination of your new json file. In this case it is the file `result.json` which will be created and get filled in the third line: Your dict `sample` gets written...
What Unicode symbols are accepted in Python3 variable names?
17,043,894
9
2013-06-11T12:16:55Z
17,043,983
18
2013-06-11T12:22:23Z
[ "python", "variables", "unicode", "syntax", "python-3.x" ]
I want to use a larger variety of Unicode symbols for variable names in my Python3 scripts. What characters are acceptable to use in Python3 variable names? UPDATE: I recently started using Unicode symbols (such as Greek and Asian symbols) for code obfuscation.
According to [PEP 3131](http://www.python.org/dev/peps/pep-3131/), the first character of an identifier needs to belong to `ID_Start`, the rest to `ID_Continue`, defined as follows: > `ID_Start` is defined as all characters having one of the general > categories uppercase letters (Lu), lowercase letters (Ll), titlecas...
What is the fastest way to merge two lists in python?
17,044,508
10
2013-06-11T12:48:24Z
17,044,540
15
2013-06-11T12:49:43Z
[ "python", "performance", "list", "merge" ]
Given, ``` list_1 = [1,2,3,4] list_2 = [5,6,7,8] ``` What is the **fastest way** to achieve the following in python? ``` list = [1,2,3,4,5,6,7,8] ``` Please note that, there can be many ways to merge two lists in python. I am looking for the most time efficient way. [EDIT]++++++++++++++++++++++++++++++++++++++++++...
You can just use concatenation: ``` list = list_1 + list_2 ``` If you don't need to keep list\_1 around, you can just modify it: ``` list_1.extend(list_2) ```
Asterisks outside of function calls
17,045,816
5
2013-06-11T13:49:23Z
17,045,906
8
2013-06-11T13:53:57Z
[ "python", "python-3.x" ]
I'm venturing into python and I had a question regarding asterisks. I know that they are used for arguments in function calls but I have seen snippets of code using them outside of function cards (say for example, in a tuple of 5 grades, unpacking them into variables such as: `first, *middle, last = grades` Whenever ...
Python 3 added extended tuple unpacking with support for *one* wildcard, see [PEP 3132](http://www.python.org/dev/peps/pep-3132/): ``` *start, tail = ... head, *middle, tail = ... ``` See the [assignment statements](http://docs.python.org/3/reference/simple_stmts.html#assignment-statements) reference documentation: ...
vim-flake8 is not working
17,046,421
8
2013-06-11T14:19:35Z
17,046,746
11
2013-06-11T14:33:52Z
[ "python", "vim", "pyflakes", "flake8" ]
I installed [vim-flake8](https://github.com/nvie/vim-flake8) by git cloning it on my Pathogen bundle folder as usual, but when I tried to run the plugin pressing `F7` or using `:call Flake8()` in one Python file I receive the following message: > Error detected while processing function Flake8: > > line 8: > > File fl...
The error message is telling you that you didn't install the program [flake8](https://pypi.python.org/pypi/flake8). Install it. Assuming pip is installed ``` pip install flake8 ``` should work.
Command history in interpreters in emacs
17,046,929
8
2013-06-11T14:41:53Z
17,047,117
13
2013-06-11T14:50:00Z
[ "python", "emacs", "command", "interpreter" ]
Inside emacs I am running interpreters for several different languages (python, R, lisp, ...). When I run the interpreters through the terminal in most cases I can use the up arrow to see the last command or line of code that I entered. I no longer have this functionality when I am running the interpreters in emacs. Ho...
You can use `M-p` or `Ctrl-up` to get to the previous command. The complementary keys `M-n` or `Ctrl-down` will get you the next command in history. Check out [Emacs' manual page on the shell history ring](http://www.gnu.org/software/emacs/manual/html_node/emacs/Shell-Ring.html#Shell-Ring).
Why is a list needed for random.choice
17,047,608
12
2013-06-11T15:12:03Z
17,047,643
8
2013-06-11T15:13:06Z
[ "python", "list" ]
This is probably a very straight forward question but would love a simple explanation as to the why? The below code requires a list in order to obtain a random card. ``` import random card = random.choice (["hearts", "clubs", "frogs"]) ``` I am puzzled as to why it requires a list and why I cannot do this. ``` im...
The issue is that you're calling `random.choice` with 3 parameters, not a single parameter with 3 elements. Try `random.choice(('one', 'two', 'three'))` for instance. Any sequence with a length and a suitable `__getitem__` (for indexing) will do - since it picks a number between 0 and `len(something)` to choose the el...
Why is a list needed for random.choice
17,047,608
12
2013-06-11T15:12:03Z
17,047,686
30
2013-06-11T15:14:50Z
[ "python", "list" ]
This is probably a very straight forward question but would love a simple explanation as to the why? The below code requires a list in order to obtain a random card. ``` import random card = random.choice (["hearts", "clubs", "frogs"]) ``` I am puzzled as to why it requires a list and why I cannot do this. ``` im...
Because of Murphy's law: anything that *can* be done the wrong way *will* be done the wrong way by someone, some day. Your suggested API would require ``` random.choice(*lst) ``` when the values to choose from are in the list (or other sequence) `lst`. When someone writes ``` random.choice(lst) ``` instead, they wo...
Python list to dict
17,049,794
3
2013-06-11T17:03:59Z
17,049,888
10
2013-06-11T17:09:40Z
[ "python", "list", "dictionary" ]
I have a huge list like ``` ['a', '2'] ['a', '1'] ['b', '3'] ['c', '2'] ['b', '1'] ['a', '1']['b', '1'] ['c', '2']['b', '3'] ['b', '1'] ``` I want to walk through this and get an output of number of each second item for a distinct first item: ``` {a:[2,1,1] b:[3,1,3,1] c:[2,2]} ```
``` data = [['a','2'],['a','1'],['b','3'],['c','2'],['b','1'],['a','1'],['b','1'],['c','2'],['b','3'],['b','1']] result = {} for key, value in data: result.setdefault(key, []).append(value) ``` Outcome: ``` >>> result {'a': ['2', '1', '1'], 'c': ['2', '2'], 'b': ['3', '1', '1', '3', '1']} ``` I prefer [dict.setd...
How to test if a Python object is a module?
17,049,806
3
2013-06-11T17:04:26Z
17,049,835
9
2013-06-11T17:06:03Z
[ "python" ]
Python modules are objects too. So I would imagine it could be possible to test if a given object is a module(/package) this way: ``` >>> import sys, os, my_module >>> isinstance(sys, ModuleClass) True >>> isinstance(os, ModuleClass) True >>> isinstance(my_module, ModuleClass) True >>> isinstance(5, ModuleClass) False...
You can use [`inspect.ismodule`](http://docs.python.org/2/library/inspect.html#inspect.ismodule): ``` >>> import inspect >>> import os >>> os2 = object() >>> inspect.ismodule(os) True >>> inspect.ismodule(os2) False ```
How to test if a Python object is a module?
17,049,806
3
2013-06-11T17:04:26Z
17,049,842
9
2013-06-11T17:06:25Z
[ "python" ]
Python modules are objects too. So I would imagine it could be possible to test if a given object is a module(/package) this way: ``` >>> import sys, os, my_module >>> isinstance(sys, ModuleClass) True >>> isinstance(os, ModuleClass) True >>> isinstance(my_module, ModuleClass) True >>> isinstance(5, ModuleClass) False...
You can do: ``` from types import ModuleType print isinstance(obj, ModuleType) ```
I want to loop 100 times but not print 100 times in the loop (Python)
17,050,132
2
2013-06-11T17:24:34Z
17,050,169
7
2013-06-11T17:27:09Z
[ "python", "loops", "random", "printing" ]
``` for lp in range(100): if guess == number: break if guess < number: print "Nah m8, Higher." else: print "Nah m8, lower." ``` This is some basic code that I was told to make for a basic computing class. My aim is to make a simple 'game' where the user has to guess a random number ...
It seems like you're omitting the guessing stage. Where is the program asking the user for input? Ask them at the beginning of the loop! ``` for lp in range(100): guess = int(input('Guess number {0}:'.format(lp + 1))) ... ```
How to loop over a dictionary with more than 3 sublevels of dictionaries inside it
17,051,376
4
2013-06-11T18:39:57Z
17,051,459
8
2013-06-11T18:44:32Z
[ "python", "dictionary", "nested" ]
I am trying to loop over a dictionary where some keys have other dictionaries as values and some of those values are a key for a dictionary it has as a value. I am parsing a YAML file with over 5000 lines using pyyaml. When I load it, it creates a dictionary of everything in the file and breaks all the sub levels into ...
Sounds like you want a solution using recursion: ``` def recurse( x ): for k, v in x.items(): if isinstance( v , dict ): recurse( v ) else: print "key: {}, val: {}".format(k, v) ``` Note that recursion will result in a stack overflow if you go too deep. However, the limit is generally much highe...
Is there a CLI to tail logs from AWS Elastic Beanstalk
17,051,925
22
2013-06-11T19:12:48Z
18,625,002
19
2013-09-04T22:42:49Z
[ "python", "logging", "flask", "elastic-beanstalk" ]
Is there a CLI utility for tailing logs from Elastic Beanstalk applications. Specifically a python flask application. You can use their eb CLI to get a snap shot ... ``` eb logs ``` But I would like to do (similar to what [heroku offers](https://devcenter.heroku.com/articles/logging#log-retrieval))... ``` eb logs -...
I had been struggling with this one too. The eb CLI utility does not seem to allow for tailing your application logs currently. However, you can tail these logs by: 1. Creating a key pair in the EC2 console (which should give you a `.pem` file) 2. Linking your EB instance to this key pair (in the EB console) 3. Findi...
Reporting yielded results of long-running Celery task
17,052,291
17
2013-06-11T19:35:17Z
17,203,290
19
2013-06-19T23:59:59Z
[ "python", "django", "celery" ]
### Problem I've segmented a long-running task into logical subtasks, so I can report the results of each subtask as it completes. However, I'm trying to report the results of a task that will effectively never complete (instead yielding values as it goes), and am struggling to do so with my existing solution. ### Ba...
In order for Celery to know what the current state of the task is, it sets some metadata in whatever result backend you have. You can piggy-back on that to store other kinds of metadata. ``` def yielder(): for i in range(2**100): yield i @task def report_progress(): for progress in yielder(): ...
How to print current date on python3?
17,053,099
9
2013-06-11T20:24:06Z
17,053,233
16
2013-06-11T20:31:28Z
[ "python", "date", "datetime", "time" ]
From what I gather, [here](http://pleac.sourceforge.net/pleac_python/datesandtimes.html) (for example), this should print the current year in two digits ``` print (datetime.strftime("%y")) ``` However, I get this error ``` TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str' ``` S...
``` import datetime now = datetime.datetime.now() print (now.year) ``` The above code works perfectly fine for me.
When to use "with" in python
17,053,103
17
2013-06-11T20:24:29Z
17,053,461
10
2013-06-11T20:44:00Z
[ "python" ]
I saw [this question](http://stackoverflow.com/questions/903557/pythons-with-statement-versus-with-as), and I understand when you would want to use `with foo() as bar:`, but I don't understand when you would just want to do: ``` bar = foo() with bar: .... ``` Doesn't that just remove the tear-down benefits of usin...
To expand a bit on @freakish's answer, `with` guarantees entry into and then exit from a "context". What the heck is a context? Well, it's "whatever the thing you're with-ing makes it". Some obvious ones are: * locks: you take a lock, manipulate some data, and release the lock. * external files/streams: you open a fil...
MySQL Connector/Python - insert python variable to MySQL table
17,053,435
6
2013-06-11T20:42:39Z
19,502,805
11
2013-10-21T19:13:49Z
[ "python", "mysql", "insert", "mysql-connector-python" ]
I'm trying to insert a python variable into a MySQL table within a python script but it is not working. Here is my code ``` add_results=("INSERT INTO account_cancel_predictions" "(account_id,21_day_probability,flagged)" "Values(%(account_id)s,%(21_day_probability)s,%(flagged)s)") data_result={...
Assuming you are using `mysql.connector` (I think you are), define your own converter class: ``` class NumpyMySQLConverter(mysql.connector.conversion.MySQLConverter): """ A mysql.connector Converter that handles Numpy types """ def _float32_to_mysql(self, value): return float(value) def _float64_...
Python: How do you stop numpy from multithreading?
17,053,671
13
2013-06-11T20:56:14Z
17,054,932
8
2013-06-11T22:30:19Z
[ "python", "multithreading", "numpy" ]
I know this might seem like a ridiculous question, but I have to run jobs on a regular basis on compute servers that I share with others in the department and when I start 10 jobs, I really would like it to just take 10 cores and not more; I don't care if it takes a bit longer with a single core per run: I just don't w...
Set the `MKL_NUM_THREADS` environment variable to 1. As you might have guessed, this environment variable controls the behavior of the Math Kernel Library which is included as part of Enthought's `numpy` build. I just do this in my startup file, .bash\_profile, with `export MKL_NUM_THREADS=1`. You should also be able ...
Remove specific characters from list python
17,054,022
4
2013-06-11T21:19:44Z
17,054,154
8
2013-06-11T21:29:10Z
[ "python", "regex" ]
I am fairly new to Python. I have a list as follows: ``` sorted_x = [('pvg-cu2', 50.349189), ('hkg-pccw', 135.14921), ('syd-ipc', 163.441705), ('sjc-inap', 165.722676)] ``` I am trying to write a regex which will remove everything after the '-' and before the ',', i.e I need the same list to look as below: ``` [('pv...
``` result = [(a.split('-', 1)[0], b) for a, b in sorted_x] ``` Example: ``` >>> sorted_x = [('pvg-cu2', 50.349189), ('hkg-pccw', 135.14921), ('syd-ipc', 163.441705), ('sjc-inap', 165.722676)] >>> [(a.split('-', 1)[0], b) for a, b in sorted_x] [('pvg', 50.349189000000003), ('hkg', 135.14921000000001), ('syd', 163.441...
Python JSON dump / append to .txt with each variable on new line
17,055,117
20
2013-06-11T22:48:53Z
17,055,135
33
2013-06-11T22:50:51Z
[ "python", "json", "append", "newline", "dump" ]
My code creates a dictionary, which is then stored in a variable. I want to write each dictionary to a JSON file, but I want each dictionary to be on a new line. My dictionary: ``` hostDict = {"key1": "val1", "key2": "val2", "key3": {"sub_key1": "sub_val2", "sub_key2": "sub_val2", "sub_key3": "sub_val3"}, "key4": "va...
Your question is a little unclear. If you're generating `hostDict` in a loop: ``` with open('data.txt', 'a') as outfile: for hostDict in ....: json.dump(hostDict, outfile) outfile.write('\n') ``` If you mean you want each variable within `hostDict` to be on a new line: ``` with open('data.txt', '...
How to set environment variables in Supervisor service
17,055,951
21
2013-06-12T00:30:52Z
17,063,321
9
2013-06-12T10:34:48Z
[ "python", "supervisord" ]
How do you export environment variables in the command executed by Supervisor? I first tried: ``` command="export SITE=domain1; python manage.py command" ``` but Supervisor reports "can't find command". So then I tried: ``` command=/bin/bash -c "export SITE=domain1; python manage.py command" ``` and the command ru...
Just do it separately: ``` environment=SITE=domain1 command=python manage.py command ``` Refer to <http://supervisord.org/subprocess.html#subprocess-environment> for more info.
How to set environment variables in Supervisor service
17,055,951
21
2013-06-12T00:30:52Z
26,732,916
26
2014-11-04T10:32:20Z
[ "python", "supervisord" ]
How do you export environment variables in the command executed by Supervisor? I first tried: ``` command="export SITE=domain1; python manage.py command" ``` but Supervisor reports "can't find command". So then I tried: ``` command=/bin/bash -c "export SITE=domain1; python manage.py command" ``` and the command ru...
To add a single environment variable, You can do something like this. ``` [program:django] environment=SITE=domain1 command = python manage.py command ``` But, if you want to export multiple environment variables, you need to separate them by comma. ``` [program:django] environment = SITE=domain1, DJANGO_SE...
Python/PIL affine transformation
17,056,209
9
2013-06-12T01:08:08Z
17,141,975
7
2013-06-17T07:00:27Z
[ "python", "matlab", "python-imaging-library", "transformation" ]
This is a basic transform question in PIL. I've tried at least a couple of times in the past few years to implement this correctly and it seems there is something I don't quite get about Image.transform in PIL. I want to implement a similarity transformation (or an affine transformation) where I can clearly state the l...
OK! So I've been working on understanding this all weekend and I think I have an answer that satisfies me. Thank you all for your comments and suggestions! I start by looking at this: [affine transform in PIL python](http://stackoverflow.com/questions/7501009/affine-transform-in-pil-python)? while I see that the aut...
Read file in chunks - RAM-usage, read Strings from binary files
17,056,382
6
2013-06-12T01:29:43Z
17,056,467
12
2013-06-12T01:43:22Z
[ "python", "string", "ram" ]
i'd like to understand the difference in RAM-usage of this methods when reading a large file in python. Version 1, found here on stackoverflow: ``` def read_in_chunks(file_object, chunk_size=1024): while True: data = file_object.read(chunk_size) if not data: break yield data ...
`yield` is the keyword in python used for generator expressions. That means that the next time the function is called (or iterated on), the execution will start back up at the exact point it left off last time you called it. The two functions function identically; the only difference is that the first one uses a tiny b...
Flask: redirect while passing arguments?
17,057,191
15
2013-06-12T03:21:24Z
17,061,023
22
2013-06-12T08:32:54Z
[ "python", "flask" ]
In flask, I can do this: ``` render_template("foo.html", messages={'main':'hello'}) ``` And if foo.html contains `{{ messages['main'] }}`, the page will show `hello`. But what if there's a route that leads to foo: ``` @app.route("/foo") def do_foo(): # do some logic here return render_template("foo.html") ``...
You could pass the messages as explicit URL parameter (appropriately encoded), or store the messages into `session` (cookie) variable before redirecting and then get the variable before rendering the template. For example: ``` def do_baz(): messages = json.dumps({"main":"Condition failed on page baz"}) session...
Python - Extract folder path from file path
17,057,544
27
2013-06-12T04:11:12Z
17,057,583
22
2013-06-12T04:15:47Z
[ "python", "file", "path", "folder", "extract" ]
I have seen this solution but not for Python specifically. I would like to get just the folder path from the full path to a file. For example `T:\Data\DBDesign\DBDesign_93_v141b.mdb` and I would like to get just `T:\Data\DBDesign` (excluding the `\DBDesign_93_v141b.mdb`). I have tried something like this: ``` exist...
Use the [os.path](http://docs.python.org/2/library/os.path.html) module: ``` >>> import os >>> existGDBPath = r'T:\Data\DBDesign\DBDesign_93_v141b.mdb' >>> wkspFldr = os.path.dirname(existGDBPath) >>> print wkspFldr 'T:\Data\DBDesign' ``` You can go ahead and assume that if you need to do some sort of filename manip...
Python - Extract folder path from file path
17,057,544
27
2013-06-12T04:11:12Z
17,057,603
33
2013-06-12T04:18:47Z
[ "python", "file", "path", "folder", "extract" ]
I have seen this solution but not for Python specifically. I would like to get just the folder path from the full path to a file. For example `T:\Data\DBDesign\DBDesign_93_v141b.mdb` and I would like to get just `T:\Data\DBDesign` (excluding the `\DBDesign_93_v141b.mdb`). I have tried something like this: ``` exist...
You were almost there with your use of the `split` function. You just needed to join the strings, like follows. ``` >>> '\\'.join(existGDBPath.split('\\')[0:-1]) 'T:\\Data\\DBDesign' ``` Although, I would recommend using the `os.path.dirname` function to do this, you just need to pass the string, and it'll do the wor...
A good pythonic way to map bits to characters in python?
17,059,840
2
2013-06-12T07:23:31Z
17,059,923
7
2013-06-12T07:28:26Z
[ "python" ]
`the_map = { 1:'a',0:'b'}` Now to generate, 8 patterns of `a` and `b` , we create 8 bit patterns: ``` >>> range(8) [0, 1, 2, 3, 4, 5, 6, 7] # 001,010,011....111 ``` How to map the bits to characters 'a' and 'b' , to receive output like : ``` ['aaa','aab','aba'.......'bbb'] ``` I am looking for an efficient one lin...
I think you are looking for [`product`](http://docs.python.org/2/library/itertools.html#itertools.product): ``` >>> from itertools import product >>> [''.join(i) for i in product('ABC',repeat=3)] ['AAA', 'AAB', 'AAC', 'ABA', 'ABB', 'ABC', 'ACA', 'ACB', 'ACC', 'BAA', 'BAB', 'B AC', 'BBA', 'BBB', 'BBC', 'BCA', 'BCB', 'B...
Split string at nth occurrence of a given character
17,060,039
21
2013-06-12T07:36:01Z
17,060,409
32
2013-06-12T07:57:05Z
[ "python", "string", "split" ]
Is there a Python-way to split a string after the nth occurrence of a given delimiter? Given a string: ``` '20_231_myString_234' ``` It should be split into (with the delimiter being '\_', after its second occurrence): ``` ['20_231', 'myString_234'] ``` Or is the only way to accomplish this to count, split and joi...
``` >>> n = 2 >>> groups = text.split('_') >>> '_'.join(groups[:n]), '_'.join(groups[n:]) ('20_231', 'myString_234') ``` Seems like this is the most readable way, the alternative is regex)
Is it possible to have an if inside a tuple?
17,061,231
2
2013-06-12T08:44:40Z
17,061,293
7
2013-06-12T08:48:07Z
[ "python", "if-statement", "conditional-expressions" ]
I'd like to build something like: ``` A = ( 'parlament', 'queen/king' if not country in ('england', 'sweden', …), 'press', 'judges' ) ``` Is there any way to build a tuple like that? I tried ``` 'queen/king' if not country in ('england', 'sweden', …) else None, 'queen/king' if not country in ('england',...
Yes, but you need an `else` statement: ``` >>> country = 'australia' >>> A = ( ... 'parlament', ... 'queen/king' if not country in ('england', 'sweden') else 'default', ... 'press', ... 'judges' ... ) >>> print A ('parlament', 'queen/king', 'press', 'judges') ``` --- Another example: ``` >>> country = ...
Find all possible sublists of a list
17,061,686
8
2013-06-12T09:08:56Z
17,061,862
7
2013-06-12T09:19:36Z
[ "python" ]
Let's say I have the following list ``` [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18] ``` I want to find all possible sublists of a certain lenght where they don't contain one certain number and without losing the order of the numbers. For example all possible sublists with length 6 without the 12 are: ``` [1,2,3,...
A straightforward, non-optimized solution would be ``` result = [sublist for sublist in (lst[x:x+size] for x in range(len(lst) - size + 1)) if item not in sublist ] ``` An optimized version: ``` result = [] start = 0 while start < len(lst): try: end = lst.index(item, start + 1) e...
Reading an Excel file in python using pandas
17,063,458
34
2013-06-12T10:42:11Z
17,063,653
66
2013-06-12T10:52:50Z
[ "python", "python-2.7", "pandas" ]
I am trying to read an excel file this way : ``` newFile = pd.ExcelFile(PATH\FileName.xlsx) ParsedData = pd.io.parsers.ExcelFile.parse(newFile) ``` which throws an error that says two arguments expected, I don't know what the second argument is and also what I am trying to achieve here is to convert an Excel file to ...
Close: first you call `ExcelFile`, but then you call the `.parse` method and pass it the sheet name. ``` >>> xl = pd.ExcelFile("dummydata.xlsx") >>> xl.sheet_names [u'Sheet1', u'Sheet2', u'Sheet3'] >>> df = xl.parse("Sheet1") >>> df.head() Tid dummy1 dummy2 dummy3 dummy4 dummy5 \ 0 2006...
Reading an Excel file in python using pandas
17,063,458
34
2013-06-12T10:42:11Z
36,590,692
9
2016-04-13T06:51:37Z
[ "python", "python-2.7", "pandas" ]
I am trying to read an excel file this way : ``` newFile = pd.ExcelFile(PATH\FileName.xlsx) ParsedData = pd.io.parsers.ExcelFile.parse(newFile) ``` which throws an error that says two arguments expected, I don't know what the second argument is and also what I am trying to achieve here is to convert an Excel file to ...
This is much simple and easy way. ``` import pandas df = pandas.read_excel(open('your_xls_xlsx_filename','rb'), sheetname='Sheet 1') # or using sheet index starting 0 df = pandas.read_excel(open('your_xls_xlsx_filename','rb'), sheetname=2) ``` check out documentation full details <http://pandas.pydata.org/pandas-docs...
Django Multiple Authentication Backend for one project, HOW?
17,064,443
7
2013-06-12T11:34:44Z
17,077,239
17
2013-06-12T23:49:28Z
[ "python", "django", "authentication", "backend" ]
Need serious help here. I have an application written in django/python and I have to extend it and include some other solution as an "app" in this application. For example my app to be integrated is named "my\_new\_app" Now there is a backend authentication written for the main application and i cannot use it. I have ...
You *can* have multiple authentication backends. Just set the `AUTHENTICATION_BACKENDS` in `settings.py` of your Django project to list the backend implementations you want to use. For example I often use a combination of OpenID authentication and the standard Django authentication, like this in my `settings.py`: ``` ...
how to embed a code editor in a page?
17,064,681
2
2013-06-12T11:47:45Z
17,064,871
7
2013-06-12T11:56:38Z
[ "javascript", "python" ]
Problem ``` I want to create a page with a code editor embedded in it.I looked up codemirror but i am having problems using it as i am new to java script. ``` So I am looking for an easy way to embed a code editor into a page(using java script or python).Can someone please provide some link/tutorial or method for it.
Try Ace: <https://github.com/ajaxorg/ace> (source) <http://ace.ajax.org/> (Project page), this JavaScript editor is used by Cloud9
How to get the caller class name inside a function of another class in python?
17,065,086
5
2013-06-12T12:06:51Z
17,065,634
11
2013-06-12T12:33:46Z
[ "python", "stack", "runtime", "sequence-diagram" ]
My objective is to stimulate a sequence diagram of an application for this i need the information about a caller and callee class names during runtime. I can successfully retive the caller function but not able to get a caller class name? ``` #Scenario caller.py: import inspect class A: def Apple(self): ...
Well, after some digging at the prompt, here's what I get: ``` stack = inspect.stack() the_class = stack[1][0].f_locals["self"].__class__ the_method = stack[1][0].f_code.co_name print("I was called by {}.{}()".format(str(calling_class), calling_code_name)) # => I was called by A.a() ``` When invoked: ``` ➤ python...
Python decorator error?
17,066,177
2
2013-06-12T13:00:24Z
17,066,216
8
2013-06-12T13:01:53Z
[ "python", "python-2.7", "python-decorators" ]
I try to creating decorator using following code. ``` def outer(): def inner(): print 'inner called' return inner foo = outer() foo() ``` But it gives the error ``` TypeError: 'NoneType' object is not callable ``` Please solve my problem. Thanks..
I believe this is the code you wanted: ``` def outer(): def inner(): print 'inner called' return inner foo = outer() foo() ``` Your `return` was indented too far
Application icon in PySide GUI
17,068,003
9
2013-06-12T14:22:34Z
17,069,868
7
2013-06-12T15:48:41Z
[ "python", "qt", "qt4", "pyside", "python-3.3" ]
I have a PySide GUI app (written in Python 3, running on Windows 7 Pro) in which I’m setting the application icon as follows: ``` class MyGui(QtGui.QWidget): def __init__(self): super(MyGui, self).__init__() ... self.setWindowIcon(QtGui.QIcon('MyGui.ico')) if os.name == 'nt': ...
PySide needs access to a special DLL to read .ico files. I think it's qico4.dll. You could try changing the call to setWindowIcon to open the icon as a .png and put a .png of it in the ./dist directory and see if that works. If so, then your code is fine and I'm pretty sure it's the .dll problem. You'll need to tell c...
Joining byte list with python
17,068,100
9
2013-06-12T14:27:48Z
17,068,310
20
2013-06-12T14:38:04Z
[ "python", "list", "join", "byte" ]
I'm trying to develop a tool that read a binary file, makes some changes and save it. What I'm trying to do is make a list of each line in the file, work with several lines and then join the list again. This is what I tried: ``` file = open('myFile.exe', 'r+b') aList = [] for line in f: aList.append(line) #Here...
Perform the join on a byte string using `b''.join()`: ``` >>> b''.join([b'line 1\n', b'line 2\n']) b'line 1\nline 2\n' ```
Return max of zero or value for a pandas DataFrame column
17,068,269
15
2013-06-12T14:35:47Z
17,068,439
10
2013-06-12T14:44:08Z
[ "python", "pandas" ]
I want to replace negative values in a pandas DataFrame column with zero. Is there a more concise way to construct this expression? ``` df['value'][df['value'] < 0] = 0 ```
Here is the canonical way of doing it, while not necessarily more concise, is more flexible (in that you can apply this to arbitrary columns) ``` In [39]: df = DataFrame(randn(5,1),columns=['value']) In [40]: df Out[40]: value 0 0.092232 1 -0.472784 2 -1.857964 3 -0.014385 4 0.301531 In [41]: df.loc[df['val...
Return max of zero or value for a pandas DataFrame column
17,068,269
15
2013-06-12T14:35:47Z
17,068,462
8
2013-06-12T14:44:48Z
[ "python", "pandas" ]
I want to replace negative values in a pandas DataFrame column with zero. Is there a more concise way to construct this expression? ``` df['value'][df['value'] < 0] = 0 ```
You could use the [clip method](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Series.clip.html#pandas-series-clip): ``` import pandas as pd import numpy as np df = pd.DataFrame({'value': np.arange(-5,5)}) df['value'] = df['value'].clip(0, None) print(df) ``` yields ``` value 0 0 1 0 2 0...
Python: check if any word in a list of words matches any pattern in a list of regular expression patterns
17,068,486
4
2013-06-12T14:45:54Z
17,068,688
8
2013-06-12T14:55:42Z
[ "python", "regex" ]
I have a long list of words and [regular expression patterns](http://docs.python.org/2/library/re.html) in a .txt file, which I read in like this: ``` with open(fileName, "r") as f1: pattern_list = f1.read().split('\n') ``` for illustration, the first seven look like this: ``` print pattern_list[:7] # ['abandon...
For matching shell-style wildcards you could (ab)use the module [`fnmatch`](http://docs.python.org/2/library/fnmatch.html#module-fnmatch) As `fnmatch` is primary designed for filename comparaison, the test will be case sensitive or not depending your operating system. So you'll have to normalize both the text and the ...
Writing xlwt dates with Excel 'date' format
17,069,694
7
2013-06-12T15:40:08Z
17,085,722
11
2013-06-13T11:15:46Z
[ "python", "xlwt" ]
I'm using xlwt to make a .xls spreadsheet, and I need to create date cells. I've got writing out numbers, and setting the number format string to make them look like dates, but critically they aren't actually getting written as dates - if you do format cell in Excel, it's a "custom" Category rather than a "date" one, ...
The number will show up in the Excel "Date" category if you use a format string that corresponds to one of Excel's built-in format strings such as `dd/mm/yyy`. for example: ``` import xlwt import datetime workbook = xlwt.Workbook() worksheet = workbook.add_sheet('Sheet1') date_format = xlwt.XFStyle() date_format.num...
Celerybeat not executing periodic tasks
17,071,632
10
2013-06-12T17:26:59Z
18,210,174
16
2013-08-13T13:16:12Z
[ "python", "django", "django-celery", "celerybeat" ]
How do you diagnose why `manage.py celerybeat` won't execute any tasks? I'm running celerybeat via supervisord with the command: ``` /usr/local/myapp/src/manage.py celerybeat --schedule=/tmp/celerybeat-schedule-myapp --pidfile=/tmp/celerybeat-myapp.pid --loglevel=INFO ``` Supervisord appears to run celerybeat just f...
celerybeat will just schecdule task, wont execute it. To execute task you need to also start worker. You can start celery beat as well as worker together. I use "celeryd -B" In your case it should look like: > /usr/local/myapp/src/manage.py **celery worker --beat** > --schedule=/tmp/celerybeat-schedule-myapp --pidfil...
Select rows from a DataFrame based on values in a column in pandas
17,071,871
167
2013-06-12T17:42:05Z
17,071,908
315
2013-06-12T17:44:20Z
[ "python", "pandas", "dataframe" ]
How to select rows from a DataFrame based on values in some column in pandas? In SQL I would use: ``` select * from table where colume_name = some_value. ``` *I tried to look at pandas documentation but did not immediately find the answer.*
To select rows whose column value equals a scalar, `some_value`, use `==`: ``` df.loc[df['column_name'] == some_value] ``` To select rows whose column value is in an iterable, `some_values`, use `isin`: ``` df.loc[df['column_name'].isin(some_values)] ``` --- To select rows whose column value *does not equal* `some...
Select rows from a DataFrame based on values in a column in pandas
17,071,871
167
2013-06-12T17:42:05Z
31,296,878
26
2015-07-08T15:17:38Z
[ "python", "pandas", "dataframe" ]
How to select rows from a DataFrame based on values in some column in pandas? In SQL I would use: ``` select * from table where colume_name = some_value. ``` *I tried to look at pandas documentation but did not immediately find the answer.*
### tl;dr The pandas equivalent to ``` select * from table where column_name = some_value ``` is ``` table[table.column_name == some_value] ``` ### Code example: ``` import pandas as pd # Create data set d = {'foo':[100, 111, 222], 'bar':[333, 444, 555]} df = pd.DataFrame(d) # Full dataframe: df # Shows:...
Select rows from a DataFrame based on values in a column in pandas
17,071,871
167
2013-06-12T17:42:05Z
35,282,530
7
2016-02-09T01:36:49Z
[ "python", "pandas", "dataframe" ]
How to select rows from a DataFrame based on values in some column in pandas? In SQL I would use: ``` select * from table where colume_name = some_value. ``` *I tried to look at pandas documentation but did not immediately find the answer.*
I find the syntax of the previous answers to be redundant and difficult to remember. Pandas introduced the `query()` method in v0.13 and I much prefer it. For your question, you could do `df.query('col == val')` Reproduced from <http://pandas.pydata.org/pandas-docs/version/0.17.0/indexing.html#indexing-query> ``` In ...
What's the purpose of %d and %s
17,073,669
3
2013-06-12T19:26:55Z
17,073,714
12
2013-06-12T19:29:48Z
[ "python", "python-3.x" ]
Before you get mad at me for asking this question, I have looked for the answer but still can't seem to get what exactly they do. I saw this one answer by a user named "marcog" on SOF. For example : ``` name = "marcog" number = 42 print "%s %d" (name, number) ``` What I did then was deleting this part and the code st...
It tells `print` to output a string (`%s`) and a signed integer (`%d`). This is more useful if you want to have a more complicated output. For example: ``` print("Hello %s your number is %d" % (name, number)) ``` With the sample values you've given, this will output: > Hello marcog your number is 42
How to use argparse subparsers correctly?
17,073,688
17
2013-06-12T19:28:27Z
17,074,215
16
2013-06-12T19:59:06Z
[ "python", "argparse" ]
I've been searching through allot of the subparser examples on here and in general but can't seem to figure this seemingly simple thing out. I have two var types of which one has constraints so thought subparser was the way to go. e.g. -t allows for either "A" or "B". If the user passes "A" then they are further requi...
Subparsers are invoked based on the value of the first *positional* argument, so your call would look like ``` python test01.py A a1 -v 61 ``` The "A" triggers the appropriate subparser, which would be defined to allow a positional argument and the `-v` option. Because `argparse` does not otherwise impose any restri...
How to debug python CLI that takes stdin?
17,074,177
11
2013-06-12T19:57:17Z
26,975,795
8
2014-11-17T15:15:59Z
[ "python", "stdin", "pdb", "command-line-interface", "command-line-tool" ]
I'm trying to debug a Python CLI I wrote that can take its arguments from stdin. A simple test case would have the output of ``` echo "test" | python mytool.py ``` be equivalent to the output of ``` python mytool.py test ``` I'd like to debug some issues with this tool, so I tried to run this: ``` echo "test" | pd...
Another option is to create you own Pdb object, and set there the stdin and stdout. My proof of concept involves 2 terminals, but for sure some work can be merged some kind of very unsecure network server. 1. Create two fifos: `mkfifo stdin mkfifo stdout` 2. In one terminal, open stdout on background, and write ...
Sum consecutive numbers in a list. Python
17,074,920
2
2013-06-12T20:39:36Z
17,074,965
8
2013-06-12T20:42:24Z
[ "python", "function", "numbers", "sum" ]
i'm trying to sum consecutive numbers in a list while keeping the first one the same. so in this case 5 would stay 5, 10 would be 10 + 5 (15), and 15 would be 15 + 10 + 5 (30) ``` x = [5,10,15] y = [] for value in x: y.append(...) print y [5,15,30] ```
You want [`itertools.accumulate()`](http://docs.python.org/dev/library/itertools.html#itertools.accumulate) (added in Python 3.2). Nothing extra needed, already implemented for you. In earlier versions of Python where this doesn't exist, you can use the pure python implementation given: ``` def accumulate(iterable, f...
Is it possible to move / merge messages between RabbitMQ queues?
17,075,116
2
2013-06-12T20:50:35Z
26,814,659
8
2014-11-08T06:55:27Z
[ "python", "queue", "rabbitmq", "amqp", "pika" ]
I'm looking to know is it possible to move / merge messages from one queue to another. For example: `main-queue` contains messages `['cat-1','cat-2','cat-3','cat-4','dog-1','dog-2','cat-5']` `dog-queue` contains messages `['dog-1, dog-2, dog-3, dog-4]` So the question is, (assuming both queues are on the same cluste...
What you are/were looking for is the 'shovel' plugin. The shovel plugin comes built into the core but you have to explicitly enable it. It's really easy to use as it does everything for you (no manually consuming/republishing to another queue). Enable shovel plugin via cli: ``` sudo rabbitmq-plugins enable rabbitmq_s...
Numpy chain comparison with two predicates
17,075,324
6
2013-06-12T21:04:07Z
17,075,432
11
2013-06-12T21:10:43Z
[ "python", "arrays", "numpy", "scipy", "boolean-expression" ]
In Numpy, I can generate a boolean array like this: ``` >>> arr = np.array([1, 2, 1, 2, 3, 6, 9]) >>> arr > 2 array([False, False, False, False, True, True, True], dtype=bool) ``` Is is possible to chain comparisons together? For example: ``` >>> 6 < arr > 2 array([False, False, False, False, True, False, Fals...
AFAIK the closest you can get is to use `&`, `|`, and `^`: ``` >>> arr = np.array([1, 2, 1, 2, 3, 6, 9]) >>> (2 < arr) & (arr < 6) array([False, False, False, False, True, False, False], dtype=bool) >>> (2 < arr) | (arr < 6) array([ True, True, True, True, True, True, True], dtype=bool) >>> (2 < arr) ^ (arr < 6...
"with" statement in python __exit__
17,076,106
2
2013-06-12T22:00:16Z
17,076,136
10
2013-06-12T22:02:11Z
[ "python" ]
When using a `with` statement without a `as`, does the `__enter__` function never get executed but the `__exit__` method will? Example: ``` with test: test.do_something ``` `test.__exit__()` will be executed at the end of the with clause but `test.__enter__()` won't?
They are always\* both executed. The only difference is that if you don't use `as`, the return value of the `__enter__` function is discarded. The precise steps are laid out very nicely in the [`with` statement documentation](http://docs.python.org/2/reference/compound_stmts.html#with). ``` class T(object): def __...
please help me understanding python object instantiation.
17,076,141
4
2013-06-12T22:02:26Z
17,076,307
7
2013-06-12T22:14:42Z
[ "python", "instantiation" ]
I am not a programmer and I am trying to learn python at the moment. But I am a little confused with the object instantiation. I am thinking Class like a template and object is make(or instantiated) based on the template. **Doesn't that mean once object is created(eg. classinst1 = MyClass() ), change in template should...
You have the general idea of class declaration and instantiation right. But the reason why the output in your example doesn't seem to make sense is that there are actually two variables called `common`. The first is the class variable declared and instantiated at the top of your code, in the class declaration. This is ...
Invert index and columns in a pandas DataFrame
17,076,705
5
2013-06-12T22:51:34Z
17,076,764
10
2013-06-12T22:57:15Z
[ "python", "pandas" ]
I have a pandas DataFrame with a single row: ``` 10 20 30 70 data1: 2.3 5 6 7 ``` I want to reindex the frame so that the column values (10, 20, 30, 70) become index values and the data becomes the column: ``` data1: 10 2.3 20 5.0 30 6.0 70 7.0 ``` How do I achieve this?
You're looking for the [transpose](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.transpose.html) ([`T`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.T.html)) method: ``` In [11]: df Out[11]: 10 20 30 70 data1: 2.3 5 6 7 In [12]: df.T Out[12]: d...
python split statement into multiple lines
17,076,710
2
2013-06-12T22:52:00Z
17,076,730
7
2013-06-12T22:53:50Z
[ "python" ]
I have following code: ``` print "my name is [%s], I like [%s] and I ask question on [%s]" % ("xxx", "python", "stackoverflow") ``` I want to split this LONG line into multiple lines: ``` print "my name is [%s]" ", I like [%s] " "and I ask question on [%s]" % ("xxx", "python", "stackoverflow") ``` Can you p...
Use implied line continuation by putting everything within parentheses. This is the method recommended in [Python's Style Guide (PEP 8)](http://www.python.org/dev/peps/pep-0008/#id12): ``` print ("my name is [%s]" ", I like [%s] " "and I ask question on [%s]" % ("xxx", "python", "stackoverflow")) ...
Django + Heroku + Mandrill mail_admins() not working, either manually or as triggered by 500 error
17,077,114
6
2013-06-12T23:35:31Z
17,222,670
13
2013-06-20T19:58:28Z
[ "python", "django", "mandrill" ]
I have a Django (v1.4) site on Heroku using Mandrill for SMTP. I have all the required values in my settings file: * EMAIL\_HOST\_PASSWORD * EMAIL\_HOST\_USER * EMAIL\_HOST * EMAIL\_PORT * SERVER\_EMAIL (set to a real address, not root@localhost) I can send regular emails just fine using `send_messages()` manually fr...
Have you checked your Mandrill API logs? I am having the same issue and noticed that the emails are being sent to the Mandrill API (since I set my smtp settings for Mandrill in settings.py), but that the from\_email and from\_name are empty in the API calls. So, I found <https://github.com/brack3t/Djrill> and am abou...
If Statement and while loop
17,078,136
2
2013-06-13T02:08:19Z
17,078,161
7
2013-06-13T02:12:53Z
[ "python", "loops", "if-statement", "while-loop" ]
I'm a self taught programmer, and I just started using python. I'm having a bit of a problem, when I execute this code: ``` x = 0 while x == 0: question = raw_input("Would you like a hint? ") if question == "y" or "yes": print "Ok" first.give_hint("Look over there") x = 1 elif question == "n" or "no"...
The problem is this line: ``` if question == "y" or "yes": ``` `"yes"` will always evaluate to `True`. What you really want is: ``` if question == "y" or question == "yes": ``` Similar changes must be made for the other conditions.
How do I get a Blender exporter script to run from the command line?
17,079,106
2
2013-06-13T04:12:00Z
17,094,485
9
2013-06-13T18:32:12Z
[ "python", "command-line", "export", "blender" ]
I am trying to export some objects from blender into a proprietary format. I'd like the script I write to be able to export the objects from blender from the File drop down and from the command line. I am using blender 2.66 on ubuntu 12.04 LTS. Below is the file I currently am trying to get to run. ``` # Required Blen...
I finally figured this out and thought it would be a good idea to come back and share the answer. First here is the file that works. ``` # Required Blender information. bl_info = { "name": "My Exporter", "author": "", "version": (1, 0), "blender": (2, 65, 0), "loc...
how is axis indexed in numpy's array?
17,079,279
5
2013-06-13T04:30:56Z
17,079,437
10
2013-06-13T04:49:06Z
[ "python", "numpy" ]
From [Numpy's tutorial](http://wiki.scipy.org/Tentative_NumPy_Tutorial), axis can be indexed with integers, like `0` is for column, `1` is for row, but I don't grasp why they are indexed this way? And How do I figure out each axis' index when coping with multidimensional array?
By definition, the axis number of the dimension is the index of that dimension within the array's `shape`. It is also the position used to access that dimension during indexing. For example, if a 2D array `a` has shape (5,6), then you can access `a[0,0]` up to `a[4,5]`. Axis 0 is thus the first dimension (the "rows"),...
How to use a callback function in python?
17,081,243
14
2013-06-13T07:11:45Z
18,354,546
14
2013-08-21T10:06:45Z
[ "python", "authentication", "python-2.7", "callback", "functional-programming" ]
I wonder how to correctly use python 2.7 callback functions. I have some callback functions from Cherrypy auth examples in my code. (These callbacks return a function that can evaluate to True or False, depending on the logged in user being in a group or not.) I wonder if a callback is executed or not if I write a p...
In python, like in many other languages, a variable can also contain a function and you can pass them around like other variables that contain e.g. numbers or strings. CherryPy's `member_of` function itself does return a function in your example. I am explaining it in simple steps: If you write `member_of()` it retu...
Python modbus library
17,081,442
21
2013-06-13T07:24:05Z
21,459,211
59
2014-01-30T14:30:17Z
[ "python", "modbus" ]
I have to control a modbus device with a serial interface. I've got not experience with modbus. But my short research revealed several modbus libraries * [pymodbus](https://pypi.python.org/pypi/pymodbus) * [MinimalModbus](https://pypi.python.org/pypi/MinimalModbus/) * [Modbus-tk](http://code.google.com/p/modbus-tk/) ...
About the same time I faced the same problem - which library to choose for python modbus master implementation but in my case for serial communication (modbus RTU) so my observations are only valid for modbus RTU. In my examination I didn't pay too much attention to documentation but examples for serial RTU master wer...
Why would I ever use anything else than %r in Python string formatting?
17,081,815
5
2013-06-13T07:46:26Z
17,081,858
7
2013-06-13T07:49:29Z
[ "python", "string-formatting" ]
I occasionally use Python string formatting. This can be done like so: ``` print('int: %i. Float: %f. String: %s' % (54, 34.434, 'some text')) ``` But, this can also be done like this: ``` print('int: %r. Float: %r. String: %r' % (54, 34.434, 'some text')) ``` As well as using %s: ``` print('int: %s. Float: %s. St...
For floats, the value of `repr` and `str` can vary: ``` >>> num = .2 + .1 >>> 'Float: %f. Repr: %r Str: %s' % (num, num, num) 'Float: 0.300000. Repr: 0.30000000000000004 Str: 0.3' ``` Using `%r` for strings will result in quotes around it: ``` >>> 'Repr:%r Str:%s' % ('foo','foo') "Repr:'foo' Str:foo" ``` You should...
Python vs Iron Python
17,081,821
6
2013-06-13T07:46:50Z
17,081,959
10
2013-06-13T07:54:48Z
[ "python", "ironpython" ]
I have to make a GUI for some testing teams. I have been asked to do it in Python, but when I Google, all I see is about Iron Python.. I also was asked not to use Visual Studio because it is too expensive for the company. So if you have any idea to avoid that I would be very happy. I am still new to Python and progra...
Python is the name of a programming language, there are various implementations of it: * **CPython**: the standard Python interpreter, written in C * **Jython**: Python interpreter for Java * **IronPython**: Python interpreter for the .NET framework * **PyPy**: Python interpreter written in Python All of them are fre...
Running Selenium Webdriver with a proxy in Python
17,082,425
17
2013-06-13T08:21:17Z
17,093,125
10
2013-06-13T17:14:01Z
[ "python", "selenium", "proxy", "selenium-webdriver", "selenium-ide" ]
I am trying to run a Selenium Webdriver script in Python to do some basic tasks. I can get the robot to function perfectly when running it through the Selenium IDE inteface (ie: when simply getting the GUI to repeat my actions). However when I export the code as a Python script and try to execute it from the command li...
How about something like this ``` PROXY = "149.215.113.110:70" webdriver.DesiredCapabilities.FIREFOX['proxy'] = { "httpProxy":PROXY, "ftpProxy":PROXY, "sslProxy":PROXY, "noProxy":None, "proxyType":"MANUAL", "class":"org.openqa.selenium.Proxy", "autodetect":False } # you have to use remote...
SSL error : routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
17,084,886
18
2013-06-13T10:33:17Z
17,086,938
13
2013-06-13T12:19:59Z
[ "python", "file", "ssl" ]
I have a large number of file download links in a `txt` file. I am trying to write a `python` script to download all the files at once, but I end up with the following error: ``` SSLError: [Errno 1] _ssl.c:499: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed ``` The file is being dow...
The server certificate is invalid, either because it is signed by an invalid CA (internal CA, self signed,...), doesn't match the server's name or because it is expired. Either way, you need to find how to tell to the Python library that you are using that it must not stop at an invalid certificate if you really want ...
SSL error : routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
17,084,886
18
2013-06-13T10:33:17Z
20,611,680
9
2013-12-16T13:05:46Z
[ "python", "file", "ssl" ]
I have a large number of file download links in a `txt` file. I am trying to write a `python` script to download all the files at once, but I end up with the following error: ``` SSLError: [Errno 1] _ssl.c:499: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed ``` The file is being dow...
Experienced this myself when using **`requests`**: ``` requests.get('https://github.com', verify=True) ``` Making that `verify=False` did the trick for me.
SSL error : routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
17,084,886
18
2013-06-13T10:33:17Z
28,826,316
7
2015-03-03T07:31:02Z
[ "python", "file", "ssl" ]
I have a large number of file download links in a `txt` file. I am trying to write a `python` script to download all the files at once, but I end up with the following error: ``` SSLError: [Errno 1] _ssl.c:499: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed ``` The file is being dow...
Got this issue today and after wandering for several hours just came to know that my server datetime was wrong. So first please check your server datetime before going so deep in this issue. also try doing ``` >> sudo update-ca-certificates ```
Box around text in matplotlib
17,086,847
11
2013-06-13T12:15:45Z
17,087,794
23
2013-06-13T13:04:07Z
[ "python", "text", "matplotlib" ]
how is possible to make a box around text in matplotlib? I have text on three different lines and in three different colors: ``` ax.text(2,1, 'alpha', color='red') ax.text(2,2, 'beta', color='cyan') ax.text(2,3, 'epsilon', color='black') ``` I saw the tutorial <http://matplotlib.org/users/recipes.html> (last examp...
As the example you linked to mentions, you can use [the `bbox` kwarg](http://matplotlib.org/users/annotations_guide.html) to add a box. I assume you're confused on how to set the color, etc, of the box? As a quick example: ``` import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.text(0.5, 0.8, 'Test', color='...
Box around text in matplotlib
17,086,847
11
2013-06-13T12:15:45Z
17,092,777
9
2013-06-13T16:53:58Z
[ "python", "text", "matplotlib" ]
how is possible to make a box around text in matplotlib? I have text on three different lines and in three different colors: ``` ax.text(2,1, 'alpha', color='red') ax.text(2,2, 'beta', color='cyan') ax.text(2,3, 'epsilon', color='black') ``` I saw the tutorial <http://matplotlib.org/users/recipes.html> (last examp...
![enter image description here](http://i.stack.imgur.com/7d50Z.png) There is some documentation online somewhere (the best I can find quickly is <http://matplotlib.org/users/annotations_guide.html>) for using `VPacker` and an `AnnotationBbox` to put together several texts of varying font properties. ``` from matplotli...
Get date from week number
17,087,314
12
2013-06-13T12:39:50Z
17,087,427
25
2013-06-13T12:44:33Z
[ "python", "datetime", "strptime" ]
Please what's wrong with my code: ``` import datetime d = "2013-W26" r = datetime.datetime.strptime(d, "%Y-W%W") print(r) ``` Display "2013-01-01 00:00:00", Thanks.
A week number is not enough to generate a date; you need a day of the week as well. Add a default: ``` import datetime d = "2013-W26" r = datetime.datetime.strptime(d + '-0', "%Y-W%W-%w") print(r) ``` The `-0` and `-%w` pattern tells the parser to pick the sunday in that week. This outputs: ``` 2013-07-07 00:00:00 `...
Python regex to match a specific word
17,090,144
4
2013-06-13T14:50:02Z
17,090,205
11
2013-06-13T14:52:21Z
[ "python", "regex", "match" ]
I want to match all lines in a test report, which contain words 'Not Ok'. Example line of text : ``` 'Test result 1: Not Ok -31.08' ``` I tried this: ``` filter1 = re.compile("Not Ok") for line in myfile: if filter1.match(line): print line ``` which should work accor...
You should use `re.search` here not `re.match`. From the [docs](http://docs.python.org/2/library/re.html#re.match) on `re.match`: > If you want to locate a match anywhere in string, use search() instead. If you're looking for the exact word `'Not Ok'` then use `\b` word boundaries, otherwise if you're only looking f...
How to unit test with a mocked file object in Python?
17,090,151
6
2013-06-13T14:50:13Z
17,090,242
8
2013-06-13T14:53:48Z
[ "python", "unit-testing", "python-2.7", "mocking" ]
I have a class which I instantiate by giving a file name like `parser = ParserClass('/path/to/file')`, then I call `parser.parse()` method which opens and reads the file. Now I want to unit test that if something bad happening inside: ``` with open(filename, 'rb') as fp: // do something ``` the correct Exceptio...
You could subclass `StringIO` to provide a context manager: ``` class ContextualStringIO(StringIO): def __enter__(self): return self def __exit__(self, *args): self.close() # icecrime does it, so I guess I should, too return False # Indicate that we haven't handled the exception, if rec...
Save by cell and not by line #: IPython %save magic: Is there a way?
17,091,462
3
2013-06-13T15:47:58Z
17,097,964
7
2013-06-13T22:05:53Z
[ "javascript", "python", "ipython", "ipython-notebook" ]
I'm creating a Django tutorial in an IPython Notebook and I want to use the `%save` magic to save `.py` files to create / edit / advance a website as the tutorial progresses. The problem is the `%save` magic works by specifying which lines to save. Undoubtedly, the line number will change when users execute the cells b...
After talking with the IPython dev team minrk found an answer: ``` %%writefile filename.py ``` will write everything below it in the cell to `filename.py`. link to the [converastion](https://github.com/ipython/ipython/issues/3426).
How can I more easily suppress previous exceptions when I raise my own exception in response?
17,091,520
6
2013-06-13T15:51:27Z
17,092,033
8
2013-06-13T16:15:09Z
[ "python", "exception", "python-3.x", "python-3.3", "traceback" ]
Consider ``` try: import someProprietaryModule except ImportError: raise ImportError('It appears that <someProprietaryModule> is not installed...') ``` When run, if someProprietaryModule is not installed, one sees: ``` (traceback data) ImportError: unknown module: someProprietaryModule During handling of the ...
In Python 3.3 and later `raise ... from None` may be used in this situation. ``` try: import someProprietaryModule except ImportError: raise ImportError('It appears that <someProprietaryModule> is not installed...') from None ``` This has the desired results.
Python pandas: fill a dataframe row by row
17,091,769
33
2013-06-13T16:02:32Z
17,092,113
32
2013-06-13T16:19:28Z
[ "python", "dataframe", "row", "pandas" ]
The simple task of adding a row to a `pandas.DataFrame` object seems to be hard to accomplish. There are 3 stackoverflow questions relating to this, none of which give a working answer. Here is what I'm trying to do. I have a DataFrame of which I already know the shape as well as the names of the rows and columns. ``...
`df['y']` will set a column since you want to set a row, use `.loc` Note that `.ix` is equivalent here, yours failed because you tried to assign a dictionary to each element of the row `y` probably not what you want; converting to a Series tells pandas that you want to align the input (for example you then don't have...
Can't seem to get my 'while True' loop to keep looping
17,092,307
2
2013-06-13T16:28:11Z
17,092,338
8
2013-06-13T16:29:49Z
[ "python" ]
I'm making a little guess a number game and I have a 'while True' loop that I want to keep looping until the user guesses the correct number. Right now I have the number displayed for ease of testing. Whether I guess the correct number or not though, I get an error **" 'Nonetype' object has no attribute 'Guess'."** Im ...
Your `.Guess()` method doesn't return anything: ``` def Guess(self): guess_code = raw_input(self.prompt) ``` You need to add a `return` statement there: ``` def Guess(self): guess_code = raw_input(self.prompt) return guess_code ``` When a function doesn't have an explicit return statement, it's return v...
Python pandas: output dataframe to csv with integers
17,092,671
12
2013-06-13T16:47:35Z
17,092,718
7
2013-06-13T16:50:13Z
[ "python", "csv", "dataframe", "pandas" ]
I have a `pandas.DataFrame` that I wish to export to a CSV file. However, pandas seems to write some of the values as `float` instead of `int` types. I couldn't not find how to change this behavior. Building a data frame: ``` df = pandas.DataFrame(columns=['a','b','c','d'], index=['x','y','z'], dtype=int) x = pandas....
This is a ["gotcha" in pandas (Support for integer NA)](http://pandas.pydata.org/pandas-docs/stable/gotchas.html#support-for-integer-na), where integer columns with NaNs are converted to floats. > This trade-off is made largely for memory and performance reasons, and also so that the resulting Series continues to be â...
Python Bytearray Printing
17,093,700
5
2013-06-13T17:46:08Z
17,093,845
17
2013-06-13T17:55:06Z
[ "python", "python-3.x" ]
I have an integer list in Python that should correspond to the following int values (which can be changed to hex byte values): ``` [10, 145, 140, 188, 212, 198, 210, 25, 152, 20, 120, 15, 49, 113, 33, 220, 124, 67, 174, 224, 220, 241, 241] ``` However, when I convert that list to a bytearray (using bytearray(nameOfLi...
``` >>> x = bytearray(b'\n\x91\x8c\xbc\xd4\xc6\xd2\x19\x98\x14x\x0f1q!\xdc|C\xae\xe0 \xdc\xf1\xf1') >>> import binascii >>> print binascii.hexlify(x) 0a918cbcd4c6d2199814780f317121dc7c43aee0dcf1f1 ``` Use binascii if you want all of it to be printed as a hex string
os.system vs subprocess in python on linux
17,094,423
3
2013-06-13T18:29:05Z
17,094,488
7
2013-06-13T18:32:19Z
[ "python", "linux", "qsub" ]
I have two python scripts. The first script calls a table of second scripts in which I need to execute a third party python script. It looks something like this: ``` #the call from the first script. cmd = "qsub -sync y -b -cwd -V -q long -t 1-10 -tc 5 -N 'script_two' ./script2.py" script2thread = pexpect.spawn(cmd)...
You should use `subprocess`. Not that it makes any difference, it's just newer module intended to replace `os.system` (have a look at [this section](http://docs.python.org/2/library/subprocess.html#replacing-os-system) for a drop-in replacement). It also has more features in case you need them one day. In short: there...