title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
How do I test one variable against multiple values? | 15,112,125 | 190 | 2013-02-27T12:26:23Z | 17,603,667 | 10 | 2013-07-11T21:16:33Z | [
"python",
"if-statement",
"comparison",
"match",
"boolean-logic"
] | I'm trying to make a function that will compare multiple variables to an integer and output a string of three letters. I was wondering if there was a way to translate this into Python. So say:
```
x = 0
y = 1
z = 3
Mylist = []
if x or y or z == 0 :
Mylist.append("c")
elif x or y or z == 1 :
Mylist.append("d")... | The direct way to write `x or y or z == 0` is
```
if any(map((lambda value: value == 0), (x,y,z))):
pass # write your logic.
```
But I dont think, you like it. :)
And this way is ugly.
The other way (a better) is:
```
0 in (x, y, z)
```
BTW lots of `if`s could be written as something like this
```
my_cases = ... |
How do I test one variable against multiple values? | 15,112,125 | 190 | 2013-02-27T12:26:23Z | 17,604,212 | 24 | 2013-07-11T21:56:54Z | [
"python",
"if-statement",
"comparison",
"match",
"boolean-logic"
] | I'm trying to make a function that will compare multiple variables to an integer and output a string of three letters. I was wondering if there was a way to translate this into Python. So say:
```
x = 0
y = 1
z = 3
Mylist = []
if x or y or z == 0 :
Mylist.append("c")
elif x or y or z == 1 :
Mylist.append("d")... | Your problem is more easily addressed with a dictionary structure like:
```
x == 0
y == 1
z == 3
d = {0: 'c', 1:'d', 2:'e', 3:'f'}
MyList = [d[k] for k in [x, y, z]]
``` |
How do I test one variable against multiple values? | 15,112,125 | 190 | 2013-02-27T12:26:23Z | 30,430,962 | 7 | 2015-05-25T03:53:36Z | [
"python",
"if-statement",
"comparison",
"match",
"boolean-logic"
] | I'm trying to make a function that will compare multiple variables to an integer and output a string of three letters. I was wondering if there was a way to translate this into Python. So say:
```
x = 0
y = 1
z = 3
Mylist = []
if x or y or z == 0 :
Mylist.append("c")
elif x or y or z == 1 :
Mylist.append("d")... | If you ARE very very lazy, you can put the values inside an array. Such as
```
list = []
list.append(x)
list.append(y)
list.append(z)
nums = [add numbers here]
letters = [add corresponding letters here]
for index in range(len(nums)):
for obj in list:
if obj == num[index]:
MyList.append(letters[... |
How do I test one variable against multiple values? | 15,112,125 | 190 | 2013-02-27T12:26:23Z | 32,085,628 | 9 | 2015-08-19T02:34:58Z | [
"python",
"if-statement",
"comparison",
"match",
"boolean-logic"
] | I'm trying to make a function that will compare multiple variables to an integer and output a string of three letters. I was wondering if there was a way to translate this into Python. So say:
```
x = 0
y = 1
z = 3
Mylist = []
if x or y or z == 0 :
Mylist.append("c")
elif x or y or z == 1 :
Mylist.append("d")... | **Previous Solution:** As stated by Martijn Pieters, the correct, and fastest, format is:
```
if 1 in {x, y, z}:
```
The one major issue that does not seem to be addressed is that you want your output list to include each letter after a true if statement.
Using only Martijn Pieters' advice you would now have:
... |
converting dataframe into a list | 15,112,234 | 12 | 2013-02-27T12:33:19Z | 15,112,264 | 21 | 2013-02-27T12:34:42Z | [
"python",
"dataframe",
"pandas"
] | I have a Python dataFrame with multiple columns.
```
2u 2s 4r 4n 4m 7h 7v
0 1 1 0 0 0 1
0 1 0 1 0 0 1
1 0 0 1 0 1 0
1 0 0 0 1 1 0
1 0 1 0 0 1 0
0 1 1 0 0 ... | It looks like a transposed matrix:
```
df.values.T.tolist()
``` |
Using len() and def __len__(self): to build a class | 15,114,023 | 9 | 2013-02-27T14:03:26Z | 15,114,062 | 16 | 2013-02-27T14:04:59Z | [
"python",
"class",
"optimization",
"coding-style"
] | Just curious,
Is there any difference (advantages and disadvantages) between using `len()` or `def __len__()` when I build a class? And which is the best Python style?
```
class foo(object):
def __init__(self,obs=[])
self.data = obs
self.max = max(obs)
self.min = min(obs)
... | There is a *huge* difference.
The `__len__()` method is a hook method. The `len()` *function* will use the `__len__` method if present to query your object for it's length.
The *normal* API people expect to use is the `len()` method, using a `.len` attribute instead would deviate from that norm.
If the length of `se... |
Accessing dictionary value by index in python | 15,114,843 | 6 | 2013-02-27T14:41:57Z | 15,114,896 | 9 | 2013-02-27T14:43:56Z | [
"python",
"dictionary",
"indexing"
] | I would like to get the value by key index from a Python dictionary. Is there a way to get it something like this?
```
dic = {}
value_at_index = dic.ElementAt(index)
```
where `index` is an integer
P.S. Asking question means lack of some understanding especially if it's a new language, so what the downvoting is for,... | Standard Python dictionaries are inherently unordered, so what you're asking to do doesn't really make sense.
If you really, really know what you're doing, use
```
value_at_index = dic.values()[index]
```
Bear in mind that adding or removing an element can potentially change the index of every other element. |
Python Requests - No connection adapters | 15,115,328 | 53 | 2013-02-27T15:01:16Z | 15,115,345 | 90 | 2013-02-27T15:01:57Z | [
"python",
"python-2.7",
"python-requests"
] | I'm using the [Requests: HTTP for Humans](http://docs.python-requests.org/en/latest/) library and I got this weird error and I don't know what is mean.
```
No connection adapters were found for '192.168.1.61:8080/api/call'
```
Anybody has an idea? | You need to include the protocol scheme:
```
'http://192.168.1.61:8080/api/call'
```
Without the `http://` part, `requests` has no idea how to connect to the remote server. |
Find closest row of DataFrame to given time in Pandas | 15,115,547 | 5 | 2013-02-27T15:12:11Z | 19,974,491 | 11 | 2013-11-14T09:54:50Z | [
"python",
"datetime",
"pandas",
"time-series"
] | I have a Pandas dataframe which is indexed by a DatetimeIndex:
```
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 53732 entries, 1993-01-07 12:23:58 to 2012-12-02 20:06:23
Data columns:
Date(dd-mm-yy)_Time(hh-mm-ss) 53732 non-null values
Julian_Day 53732 non-null values
AOT_870 ... | This simple method will return the (integer index of the) TimeSeriesIndex entry closest to a given datetime object. There's no need to copy the index to a regular column - simply use the `.to_pydatetime` method instead.
```
import numpy as np
i = np.argmin(np.abs(df.index.to_pydatetime() - image_time))
```
Then you ... |
urllib.quote() throws KeyError | 15,115,588 | 27 | 2013-02-27T15:14:25Z | 15,115,696 | 43 | 2013-02-27T15:19:23Z | [
"python",
"unicode",
"urllib2",
"urlencode",
"urllib"
] | To encode the URI, I used `urllib.quote("schönefeld")` but when some non-ascii characters exists in string, it thorws
```
KeyError: u'\xe9'
Code: return ''.join(map(quoter, s))
```
My input strings are `köln, brønshøj, schönefeld` etc.
When I tried just printing statements in windows(Using python2.7, pyscripter... | You are trying to quote Unicode data, so you need to decide how to turn that into URL-safe bytes.
Encode the string to bytes first. UTF-8 is often used:
```
>>> import urllib
>>> urllib.quote(u'sch\xe9nefeld')
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py:1268: UnicodeWarning: Un... |
How to access sparse matrix elements? | 15,115,765 | 6 | 2013-02-27T15:22:51Z | 15,115,989 | 7 | 2013-02-27T15:34:16Z | [
"python",
"scipy"
] | ```
type(A)
<class 'scipy.sparse.csc.csc_matrix'>
A.shape
(8529, 60877)
print A[0,:]
(0, 25) 1.0
(0, 7422) 1.0
(0, 26062) 1.0
(0, 31804) 1.0
(0, 41602) 1.0
(0, 43791) 1.0
print A[1,:]
(0, 7044) 1.0
(0, 31418) 1.0
(0, 42341) 1.0
(0, 47125) 1.0
(0, 54376) 1.0
print A[:,0]
... | `A[1,:]` is itself a sparse matrix with shape (1, 60877). *This* is what you are printing, and it has only one row, so all the row coordinates are 0.
For example:
```
In [12]: a = csc_matrix([[1,0,0,0],[0,0,10,11],[0,0,0,99]])
In [13]: a.todense()
Out[13]:
matrix([[ 1, 0, 0, 0],
[ 0, 0, 10, 11],
... |
How do get the ID field in App Engine Datastore? | 15,115,803 | 3 | 2013-02-27T15:24:53Z | 15,116,179 | 8 | 2013-02-27T15:42:05Z | [
"python",
"google-app-engine"
] | Say I have a blog on Google AppEngine and wants to print out the id of each post through jinja2.
```
blog = db.GqlQuery('SELECT * FROM Blog')
self.render('blog.html', blog = blog)
```
and in the template:
```
{{% for b in blog %}}
{{b.id}}
{{% endfor %}}
```
Now I havent added an 'id' field to my DB model, I just ... | Have a look at the db key class. When you have an entity you can do:
```
entity.key().id_or_name()
```
or in NDB:
```
entity.key.id()
``` |
Redirect HTTP to HTTPS on Flask+Heroku | 15,116,312 | 8 | 2013-02-27T15:47:48Z | 22,137,608 | 9 | 2014-03-03T02:23:05Z | [
"python",
"heroku",
"https",
"flask"
] | When I attempt to redirect incoming traffic to https I get an infinite redirect loop.
```
@app.route('/checkout/')
def checkout(): ... | 1) Do "pip install flask-sslify"
(github is here: <https://github.com/kennethreitz/flask-sslify>)
2) Include the following lines:
```
from flask_sslify import SSLify
if 'DYNO' in os.environ: # only trigger SSLify if the app is running on Heroku
sslify = SSLify(app)
``` |
Capture arbitrary path in Flask route | 15,117,416 | 14 | 2013-02-27T16:39:47Z | 15,117,464 | 29 | 2013-02-27T16:41:40Z | [
"python",
"flask",
"werkzeug"
] | I have a simple Flask route that I want to capture a path to a file. If I use `<path>` in the rule, it works for `/get_dir/one` but not `/get_dir/one/two`. How can I capture an arbitrary path, so that `path='/one/two/etc` will be passed to the view function?
```
@app.route('/get_dir/<path>')
def get_dir(path):
ret... | Use the `path` converter to capture arbitrary length paths: `<path:path>` will capture a path and pass it to the `path` argument. The default converter captures a single string but stops at slashes, which is why your first url matched but the second didn't.
If you also want to match the root directory (a leading slash... |
Apply function to each row of pandas dataframe to create two new columns | 15,118,111 | 19 | 2013-02-27T17:13:54Z | 15,125,793 | 13 | 2013-02-28T01:21:16Z | [
"python",
"pandas"
] | I have a pandas DataFrame, `st` containing multiple columns:
```
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 53732 entries, 1993-01-07 12:23:58 to 2012-12-02 20:06:23
Data columns:
Date(dd-mm-yy)_Time(hh-mm-ss) 53732 non-null values
Julian_Day 53732 non-null values
AOT_1020 ... | To make the first approach work, try returning a Series instead of a tuple (apply is throwing an exception because it doesn't know how to glue the rows back together as the number of columns doesn't match the original frame).
```
def calculate(s):
a = s['path'] + 2*s['row'] # Simple calc for example
b = s['pat... |
Apply function to each row of pandas dataframe to create two new columns | 15,118,111 | 19 | 2013-02-27T17:13:54Z | 24,222,837 | 7 | 2014-06-14T18:14:40Z | [
"python",
"pandas"
] | I have a pandas DataFrame, `st` containing multiple columns:
```
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 53732 entries, 1993-01-07 12:23:58 to 2012-12-02 20:06:23
Data columns:
Date(dd-mm-yy)_Time(hh-mm-ss) 53732 non-null values
Julian_Day 53732 non-null values
AOT_1020 ... | I always use lambdas and the built-in `map()` function to create new rows by combining other rows:
```
st['a'] = map(lambda path, row: path + 2 * row, st['path'], st['row'])
```
It might be slightly more complicated than necessary for doing linear combinations of numerical columns. On the other hand, I feel it's good... |
Call a function in python, getting '(function) is not defined'? | 15,119,451 | 2 | 2013-02-27T18:24:15Z | 15,119,470 | 7 | 2013-02-27T18:25:31Z | [
"python",
"function"
] | I recently started learning Python and have some code here.
```
...
workout = input("Work out if you won?")
if workout == "y":
ballone()
elif workout == "n":
print("Okay.")
sys.exit("Not working out if you won")
else:
sys.exit("Could not understand")
##Ball one
def ballone():
...
```
The issue is ca... | Move the function definition to *before* the lines that use it.
```
def ballone():
# ...
if workout == "y":
ballone()
elif workout == "n":
print("Okay.")
sys.exit("Not working out if you won")
else:
sys.exit("Could not understand")
```
Functions are stored in identifiers (variables), just like yo... |
Does a heaviside step function exist? | 15,121,048 | 20 | 2013-02-27T19:50:37Z | 15,121,188 | 11 | 2013-02-27T19:57:25Z | [
"python",
"matlab"
] | Is there a [heaviside](http://en.wikipedia.org/wiki/Heaviside_step_function) function in Python similar to that of MATLAB's [`heaviside`](http://www.mathworks.co.uk/help/symbolic/heaviside.html)?
I am struggling to find one. | It's part of [sympy](http://docs.sympy.org/0.6.7/modules/functions.html#heaviside), which you can install with `pip install sympy`
From the docs:
```
class sympy.functions.special.delta_functions.Heaviside
Heaviside Piecewise function. Heaviside function has the following properties:
1) diff(Heaviside(x),x) = Dir... |
Does a heaviside step function exist? | 15,121,048 | 20 | 2013-02-27T19:50:37Z | 15,122,658 | 29 | 2013-02-27T21:21:35Z | [
"python",
"matlab"
] | Is there a [heaviside](http://en.wikipedia.org/wiki/Heaviside_step_function) function in Python similar to that of MATLAB's [`heaviside`](http://www.mathworks.co.uk/help/symbolic/heaviside.html)?
I am struggling to find one. | If you are using numpy, you could implement it as `0.5 * (numpy.sign(x) + 1)`
```
In [19]: x
Out[19]: array([-2. , -1.5, -1. , -0.5, 0. , 0.5, 1. , 1.5, 2. ])
In [20]: 0.5 * (numpy.sign(x) + 1)
Out[20]: array([ 0. , 0. , 0. , 0. , 0.5, 1. , 1. , 1. , 1. ])
``` |
Does a heaviside step function exist? | 15,121,048 | 20 | 2013-02-27T19:50:37Z | 28,892,278 | 9 | 2015-03-06T04:18:58Z | [
"python",
"matlab"
] | Is there a [heaviside](http://en.wikipedia.org/wiki/Heaviside_step_function) function in Python similar to that of MATLAB's [`heaviside`](http://www.mathworks.co.uk/help/symbolic/heaviside.html)?
I am struggling to find one. | Probably the simplest method is just
```
def step(x):
return 1 * (x > 0)
```
This works for both single numbers and numpy arrays, returns integers, and is zero for x = 0. The last criteria may be preferable over `step(0) => 0.5` in certain circumstances. |
How can I get the android kernel version via adb (or via Python command)? | 15,121,061 | 5 | 2013-02-27T19:51:11Z | 15,121,226 | 16 | 2013-02-27T19:59:32Z | [
"android",
"python",
"kernel",
"adb"
] | I need the kernel version from a device with Android OS to use in a Python script. How can I get this value? | You can use the following command:
```
adb shell cat /proc/version
```
For my phone I received the following output:
```
Linux version 2.6.35.7-g3cc95e3 (peter@boris) (gcc version 4.4.3 (GCC) ) #3 PREEMPT Thu Aug 18 14:34:17 EDT 2011
``` |
Differentiate celery, kombu, PyAMQP and RabbitMQ/ironMQ | 15,121,519 | 7 | 2013-02-27T20:16:14Z | 15,124,719 | 12 | 2013-02-27T23:37:29Z | [
"python",
"heroku",
"rabbitmq",
"celery",
"kombu"
] | I want to upload images to S3 server, but before uploading I want to generate thumbnails of 3 different sizes, and I want it to be done out of request/response cycle hence I am using celery. I have read the docs, here is what I have understood. Please correct me if I am wrong.
1. Celery helps you manage your task queu... | IronMQ does not process your tasks for you; it simply serves as the backend for Celery to keep track of what jobs need to be performed.
So, here's what happens. Assume you have two servers, your web server and your Celery server. Your web server is responsible for handling requests, your Celery server creates the thum... |
"list index out of range" when using sys.argv[1] | 15,121,717 | 3 | 2013-02-27T20:27:03Z | 15,122,019 | 7 | 2013-02-27T20:44:31Z | [
"python",
"python-3.x",
"command-line-arguments"
] | I am writing a simple Python client and server, which works fine passing the server address within my code, however, I want the user to be able to enter the server address and throw and error if its incorrect. When I have the code below I get a error message from the terminal "list index out of range".
```
server = (s... | With this Python:
```
import sys
print(sys.argv)
```
And invoked with this command:
```
>python q15121717.py 127.0.0.1
```
I get this output:
```
['q15121717.py', '127.0.0.1']
```
I think you are not passing a argument to your Python script
Now you can change your code slightly to take a server form the command... |
Is a Python list a singly or doubly linked list? | 15,121,905 | 3 | 2013-02-27T20:37:58Z | 15,121,933 | 12 | 2013-02-27T20:39:48Z | [
"python",
"list",
"complexity-theory",
"singly-linked-list",
"doubly-linked-list"
] | I'm wondering what the order of complexity for a Python v2.7 list being built up using append() is? Is a Python list doubly linked and thus it is constant complexity or is it singly linked and thus linear complexity? If it is singly linked, how can I in linear time build up a list from an iteration that provides the va... | The time complexity for python `list.append()` is O(1). See the [Time Complexity list](http://wiki.python.org/moin/TimeComplexity) on the Python Wiki.
Internally, python lists are vectors of pointers:
```
typedef struct {
PyObject_VAR_HEAD
/* Vector of pointers to list elements. list[0] is ob_item[0], etc. *... |
How to import from config file in Flask? | 15,122,312 | 15 | 2013-02-27T21:00:25Z | 15,124,385 | 22 | 2013-02-27T23:13:16Z | [
"python",
"python-2.7",
"flask"
] | I have followed the layout of my Flask project from <http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world>.
I have the following structure:
```
app/
__init__.py
views.py
forms.py
myFile.py
run.py
config.py
```
In views.py, forms.py I am able to use
```
from config import ba... | When people talk about configs in Flask, they are generally talking about loading values into the app's configuration. In your above example you could have something like `app.config.from_object('config')` in your `init.py` file. Then all the configuration values will be loaded into the `app.config` dictionary.
Then i... |
Optimizing Django: nested queries vs relation lookups | 15,122,750 | 5 | 2013-02-27T21:27:05Z | 15,123,621 | 7 | 2013-02-27T22:21:06Z | [
"python",
"django",
"optimization"
] | I have a legacy code which uses nested ORM query, which produces SQL SELECT query with JOIN, and conditions which also contains SELECT and JOIN. Execution of this query takes enormous time. By the way, when I execute this query in raw SQL, taken from `Django_ORM_query.query`, it performs with reasonable time.
What are... | Performance issue in Django is usually caused by following relations in a loop, which causes multiple database queries. If you have [django-debug-toolbar](https://github.com/django-debug-toolbar/django-debug-toolbar) installed, you can check for how many queries you're doing and figure out which query needs to be optim... |
celery - chaining groups and subtasks. -> out of order execution | 15,123,772 | 12 | 2013-02-27T22:30:38Z | 15,147,171 | 9 | 2013-02-28T22:48:59Z | [
"python",
"celery",
"django-celery"
] | When I have something like the following
```
group1 = group(task1.si(), task1.si(), task1.si())
group2 = group(task2.si(), task2.si(), task2.si())
workflow = chain(group1, group2, task3.si())
```
The intuitive interpretation is that task3 should only execute after all tasks in group 2 have finished.
In reality, tas... | So as it turns out, in celery you cannot chain two groups together.
I suspect this is because groups chained with tasks automatically become a chord
--> Celery docs: <http://docs.celeryproject.org/en/latest/userguide/canvas.html>
> Chaining a group together with another task will automatically upgrade
> it to be a... |
celery - chaining groups and subtasks. -> out of order execution | 15,123,772 | 12 | 2013-02-27T22:30:38Z | 19,018,521 | 10 | 2013-09-26T02:51:05Z | [
"python",
"celery",
"django-celery"
] | When I have something like the following
```
group1 = group(task1.si(), task1.si(), task1.si())
group2 = group(task2.si(), task2.si(), task2.si())
workflow = chain(group1, group2, task3.si())
```
The intuitive interpretation is that task3 should only execute after all tasks in group 2 have finished.
In reality, tas... | I have the same issue with celery, trying to have a workflow where the first step is "spawn a million tasks". Tried groups of groups, subtasks, eventually my step2 kicks off before step1 is over.
Long story short I might have found a solution with the use of chords and a dumb finisher:
```
@celery.task
def chordfinis... |
Embedding tinyMCE in django flatpage | 15,123,927 | 2 | 2013-02-27T22:40:03Z | 15,178,791 | 11 | 2013-03-02T19:58:22Z | [
"python",
"django",
"django-tinymce"
] | I'm using [django-tinymce](https://github.com/aljosa/django-tinymce). I'd like to know how to embed it in a flatpage in admin panel.
From the project's readme:
Add tinymce to INSTALLED\_APPS in settings.py for your project:
```
INSTALLED_APPS = (
...
'tinymce',
)
```
Add tinymce.urls to urls.py for your pro... | you need to override the widget for the content field. To do this:
1. extend the `FlatpageForm` ModelForm as `PageForm`
2. extend the `FlatPageAdmin` to use the new `PageForm`
code example:
```
from django.contrib.flatpages.admin import FlatpageForm, FlatPageAdmin
from django.contrib.flatpages.models import FlatPage... |
matplotlib: change yaxis tick labels | 15,123,928 | 6 | 2013-02-27T22:40:04Z | 15,124,785 | 7 | 2013-02-27T23:43:01Z | [
"python",
"matplotlib"
] | For each tick label on the y axis, I would like to change:
`label -> 2^label`
I am plotting log-log data (base 2), but I would like the labels to show the original data values.
I know I can get the current y labels with
`ylabels = plt.getp(plt.gca(), 'yticklabels')`
This gives me a list: `<a list of 9 Text yticklabe... | If you want to do this in a general case you can use `FuncFormatter` (see :
[matplotlib axis label format](http://stackoverflow.com/questions/14775040/matplotlib-axis-label-format/14775453#14775453), [imshow: labels as any function of the image indices](http://stackoverflow.com/questions/12645946/imshow-labels-as-any-f... |
Priority queue with higher priority first in Python | 15,124,097 | 3 | 2013-02-27T22:52:04Z | 15,124,115 | 7 | 2013-02-27T22:53:29Z | [
"python",
"queue",
"priority-queue"
] | I need a priority queue that gets the item with the highest priority value first. I'm currently using the PriorityQueue Class from the [Queue](https://docs.python.org/2/library/queue.html) library. However, this function only returns the items with the lowest value first. I tried some ugly solutions like (sys.maxint - ... | Use a negative priority instead, no need to subtract from `sys.maxint`.
```
queue.put((-priority, item))
```
An item with priority -10 will be returned before items with priority -5, for example. |
Closest equivalent of a factor variable in Python Pandas | 15,124,439 | 13 | 2013-02-27T23:16:34Z | 27,023,500 | 12 | 2014-11-19T17:46:49Z | [
"python",
"pandas"
] | What is the closest equivalent to an [R Factor variable](http://www.stat.berkeley.edu/classes/s133/factors.html) in [Python pandas](http://pandas.pydata.org/)? | This question seems to be from a year back but since it is still open here's an update. pandas has introduced a `categorical` dtype and it operates very similar to `factors` in R. Please see this link for more information:
<http://pandas-docs.github.io/pandas-docs-travis/categorical.html>
Reproducing a snippet from t... |
Check if element exists in tuple of tuples | 15,124,833 | 23 | 2013-02-27T23:47:39Z | 15,124,843 | 33 | 2013-02-27T23:48:44Z | [
"python",
"list"
] | I have a list of tuples that look like :
```
CODES = (
('apple', 'reddelicious'),
('caramel', 'sweetsticky'),
('banana', 'yellowfruit'),
)
```
What's the best way to check if a value exists in that tuple? For example I want to be able to say:
```
'apple' in CODES
```
and get True | You are looking for [`any()`](http://docs.python.org/3/library/functions.html#any):
```
if any('apple' in code for code in CODES):
...
```
Combined with a simple [generator expression](http://www.youtube.com/watch?v=pShL9DCSIUw), this does the task. The generator expression takes each tuple and yields `True` if i... |
How to iterate through two pandas columns | 15,125,343 | 6 | 2013-02-28T00:33:33Z | 15,125,538 | 7 | 2013-02-28T00:56:25Z | [
"python",
"pandas"
] | ```
In [35]: test = pd.DataFrame({'a':range(4),'b':range(4,8)})
In [36]: test
Out[36]:
a b
0 0 4
1 1 5
2 2 6
3 3 7
In [37]: for i in test['a']:
....: print i
....:
0
1
2
3
In [38]: for i,j in test:
....: print i,j
....:
------------------------------------------------------------
Traceba... | use `DataFrame.itertuples()` method:
```
for a, b in test.itertuples(index=False):
print a, b
``` |
How to get RackSpace servers with a certain tag? | 15,125,712 | 6 | 2013-02-28T01:12:32Z | 15,162,041 | 7 | 2013-03-01T16:13:33Z | [
"python",
"openstack",
"rackspace-cloud",
"rackspace",
"pyrax"
] | Trying to fetch all the servers registered to our RackSpace account under a certain tag.
Using RackSpace's Python bindings for OpenStack, [`pyrax`](https://github.com/rackspace/pyrax/blob/master/docs/pyrax_doc.md), we haven't found a way to do this. Is there some way to achieve it with that library, or is there anothe... | I'm the author of `pyrax`. Currently there is no way to access tag information via pyrax, as that information is not returned from the API. But I agree that that would be useful information, so I'm talking to the various teams involved to see what might be possible. When I hear something I'll follow up here. |
Running Python on Windows for Node.js dependencies | 15,126,050 | 62 | 2013-02-28T01:48:44Z | 15,126,180 | 60 | 2013-02-28T02:00:39Z | [
"python",
"windows",
"node.js",
"npm"
] | I am getting into a Node.js codebase which requires that I download a few dependencies via NPM, namely jQuery.
In attempting to run `npm install jquery`, I keep getting this error:
```
Your environment has been set up for using Node.js 0.8.21 (x64) and NPM
C:\Users\Matt Cashatt>npm install jquery
npm http GET https:... | Your problem is that you *didn't* set the environment variable.
The error clearly says this:
```
gyp ERR! stack Error: Can't find Python executable "python", you can set the PYTHON env variable.
```
And in your comment, you say you did this:
```
set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib
```
That's nice, but tha... |
Running Python on Windows for Node.js dependencies | 15,126,050 | 62 | 2013-02-28T01:48:44Z | 15,126,623 | 9 | 2013-02-28T02:52:42Z | [
"python",
"windows",
"node.js",
"npm"
] | I am getting into a Node.js codebase which requires that I download a few dependencies via NPM, namely jQuery.
In attempting to run `npm install jquery`, I keep getting this error:
```
Your environment has been set up for using Node.js 0.8.21 (x64) and NPM
C:\Users\Matt Cashatt>npm install jquery
npm http GET https:... | Here is a guide that resolved a lot of these issues for me.
<http://www.steveworkman.com/node-js/2012/installing-jsdom-on-windows/>
I remember in particular the python version as important. Make sure you install 2.7.3 instead of 3's
Good luck! |
Recursion and Helper Function | 15,128,424 | 6 | 2013-02-28T05:53:26Z | 15,128,610 | 7 | 2013-02-28T06:05:31Z | [
"python"
] | Sorry if this is a general question but I am a beginner in Python and many times when I see other people code using recursion, they create a helper function for the main function and then call that helper function which itself is recursive.
This seems a bit different from the simplest cases of recursion for example (s... | This is actually used more often in other languages, because python can usually emulate that behavior with optional arguments. The idea is that the recursion gets a number of initial arguments, that the user doesn't need to provide, which help keep track of the problem.
```
def sum(lst):
return sumhelper(lst, 0)
... |
Python : csv.writer writing each character of word in separate column/cell | 15,129,567 | 13 | 2013-02-28T07:08:25Z | 27,065,792 | 20 | 2014-11-21T16:18:16Z | [
"python",
"csv",
"web-scraping"
] | Obj: To extract the text from the anchor tag inside all li in 'models' and put it in a csv.
I'm trying this code :
```
with open('Sprint_data.csv', 'ab') as csvfile:
spamwriter = csv.writer(csvfile)
models = soup.find_all('li' , {"class" : "phoneListing"})
for model in models:
model_name = unicode(u' '.... | `.writerow()` requires a sequence (`''`, `()`, `[]`) and places each index in it's own column of the row, sequentially. If your desired string is not an item in a sequence, `writerow()` will iterate over each letter in your string and each will be written to your CSV in a separate cell.
after you `import csv`
If this... |
Python int() of a string that is a float number | 15,132,352 | 4 | 2013-02-28T09:51:25Z | 15,132,401 | 13 | 2013-02-28T09:53:30Z | [
"python"
] | In all probability a stupid question, but I was wondering why python can't make a integer out of a string that is actually a float number.
```
>>> int(1.0)
1
>>> int(float('1.0'))
1
```
But
```
>>> int('1.0')
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
int('1.0')
ValueError: inv... | > Can anyone clarify why it cant be done in one step?
To quote the Zen of Python: [Explicit is better than implicit.](http://www.python.org/dev/peps/pep-0020/)
> I was wondering why python can't make a integer out of a string that is actually a float number.
In line with Python's philosophy, if a string contains a f... |
Python int() of a string that is a float number | 15,132,352 | 4 | 2013-02-28T09:51:25Z | 15,132,458 | 7 | 2013-02-28T09:56:33Z | [
"python"
] | In all probability a stupid question, but I was wondering why python can't make a integer out of a string that is actually a float number.
```
>>> int(1.0)
1
>>> int(float('1.0'))
1
```
But
```
>>> int('1.0')
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
int('1.0')
ValueError: inv... | Straight from the docs about `int`:
> If x is not a number or if base is given, then x must be a string or Unicode object representing an integer literal in radix base.
And here is how an integer literal in radix base is defined:
```
longinteger ::= integer ("l" | "L")
integer ::= decimalinteger | octint... |
Is there any difference between splitting application in app.yaml or webapp2 URI router | 15,134,866 | 4 | 2013-02-28T11:53:43Z | 15,135,376 | 7 | 2013-02-28T12:17:13Z | [
"python",
"google-app-engine"
] | Consider the two following scenarios:
There are two url handlers in app.yaml
```
handlers:
- url: /main
script: main.app1
- url: /secondary
script: secondary.app2
```
and URI router in main.py
```
app1 = webapp2.WSGIApplication([('/main', MainHandler)])
```
and another in secondary.py
```
app2 = webapp2.WSGIA... | You can use a lazy handler in webapp2 to optimize loading and use a single app.
See this link : <https://webapp2.readthedocs.io/en/latest/guide/routing.html#lazy-handlers> |
How can I say a file is SVG without using a magic number? | 15,136,264 | 6 | 2013-02-28T13:03:05Z | 15,136,684 | 9 | 2013-02-28T13:22:58Z | [
"python",
"xml",
"svg",
"file-format",
"magic-numbers"
] | An `SVG` file is basically an `XML` file so I could use the string `<?xml` (or the hex representation: `'3c 3f 78 6d 6c'`) as a magic number but there are a few opposing reason not to do that if for example there are extra white-spaces it could break this check.
The other images I need/expect to check are all binaries... | XML is not required to start with the `<?xml` preamble, so testing for that prefix is not a good detection technique â not to mention that it would identify every XML as SVG. A decent detection, and really easy to implement, is to use a real XML parser to test that the file is well-formed XML that contains the `svg` ... |
What's equivalent to Django's auto_now, auto_now_add in SQLAlchemy? | 15,136,301 | 6 | 2013-02-28T13:04:41Z | 15,136,559 | 15 | 2013-02-28T13:17:20Z | [
"python",
"django",
"date",
"sqlalchemy"
] | In Django, we can use these 2 parameters when making a date column:
> DateField.auto\_now Automatically set the field to now every time the
> object is saved. Useful for âlast-modifiedâ timestamps. Note that the
> current date is always used; itâs not just a default value that you
> can override.
>
> DateField.a... | Finally, I check SQLAlchemy's doc, this should be the way:
```
Column('created_on', DateTime, default=datetime.datetime.now)
Column('last_updated', DateTime, onupdate=datetime.datetime.now)
```
doc here:
<http://docs.sqlalchemy.org/en/latest/core/schema.html#python-executed-functions> |
Large objects and `multiprocessing` pipes and `send()` | 15,137,292 | 2 | 2013-02-28T13:55:06Z | 15,716,500 | 9 | 2013-03-30T08:17:08Z | [
"python",
"multiprocessing",
"pipe"
] | I've recently found out that, if we create a pair of parent-child connection objects by using `multiprocessing.Pipe`, and if an object `obj` we're trying to send through the pipe is too large, my program hangs without throwing exception or doing anything at all. See code below. (The code below uses the `numpy` package ... | Try to move `join()` below `recv()`:
```
import multiprocessing as mp
def big_array(conn, size=1200):
a = "a" * size
print "Child process trying to send array of %d floats." %size
conn.send(a)
return a
if __name__ == "__main__":
print "Main process started."
parent_conn, child_conn = mp.Pipe(... |
how to add directory to sys.path on ipython startup | 15,137,985 | 6 | 2013-02-28T14:28:33Z | 25,282,225 | 8 | 2014-08-13T09:06:07Z | [
"python",
"ipython"
] | env:
* windows 7 English 32bit
* python 2.7.3
* ipython 0.13.1
I try the config:
```
ipython -i -c "import sys; sys.path.append('path_name')"
```
But it does not seem to work.
So what's the proper solution?
Or how to add current directory to sys.path on ipython startup?
Thanks. | just a little follow up to Honghe.Wu's answer.
One might want to add:
```
c.InteractiveShellApp.exec_lines = [
'import sys; sys.path.append("/absolute/path/")']
```
to the ipython\_config.py to add an arbitrary directory.
Also, if you are new to ipython (as I am) you need to create the standard profile first, so th... |
How can I replace or remove HTML entities like " " using BeautifulSoup 4 | 15,138,406 | 9 | 2013-02-28T14:47:15Z | 15,138,705 | 13 | 2013-02-28T15:00:01Z | [
"python",
"beautifulsoup"
] | I am processing HTML using Python and the BeautifulSoup 4 library and I can't find an obvious way to replace ` ` with a space. Instead it seems to be converted to a Unicode non-breaking space character.
Am I missing something obvious? What is the best way to replace with a normal space using BeautifulSoup?... | ```
>>> soup = BeautifulSoup('<div>a b</div>')
>>> soup.prettify(formatter=lambda s: s.replace(u'\xa0', ' '))
u'<html>\n <body>\n <div>\n a b\n </div>\n </body>\n</html>'
``` |
How can I replace or remove HTML entities like " " using BeautifulSoup 4 | 15,138,406 | 9 | 2013-02-28T14:47:15Z | 15,138,729 | 8 | 2013-02-28T15:00:54Z | [
"python",
"beautifulsoup"
] | I am processing HTML using Python and the BeautifulSoup 4 library and I can't find an obvious way to replace ` ` with a space. Instead it seems to be converted to a Unicode non-breaking space character.
Am I missing something obvious? What is the best way to replace with a normal space using BeautifulSoup?... | See [Entities](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#entities) in the documentation, BeautifulSoup 4 produces proper Unicode for all entities:
> An incoming HTML or XML entity is always converted into the corresponding Unicode character.
Yes, ` ` is turned to a non-breaking space character, and i... |
How can I read the contents of an URL with Python? | 15,138,614 | 19 | 2013-02-28T14:55:56Z | 15,138,702 | 33 | 2013-02-28T14:59:55Z | [
"python"
] | The following works when I paste it on the browser:
```
http://www.somesite.com/details.pl?urn=2344
```
But when I try reading the URL with Python nothing happens:
```
link = 'http://www.somesite.com/details.pl?urn=2344'
f = urllib.urlopen(link)
myfile = f.readline()
print myfile
```
Do I need to e... | To answer your question:
```
import urllib
link = "http://www.somesite.com/details.pl?urn=2344"
f = urllib.urlopen(link)
myfile = f.read()
print myfile
```
You need to `read()`, not `readline()`
Or, just get this library here: <http://docs.python-requests.org/en/latest/> and seriously use it :)
```
import requests... |
Attribute access in Python: first slots, then __dict__? | 15,139,067 | 6 | 2013-02-28T15:15:20Z | 15,139,208 | 10 | 2013-02-28T15:22:03Z | [
"python",
"attributes",
"slots"
] | In the example below, attribute `x` is accessed from the slots of the object even though `x` is present in `__dict__` (this is not a typical or probably useful case, but I'm curious):
```
>>> class C(object):
... __slots__ = 'x'
...
>>> class D(C):
... pass
...
>>> obj = D()
>>> obj.x = 'Stored in slots'... | Yes, the `__dict__` of an object is only consulted after data descriptors have been consulted. `__slots__` attributes are implemented as data descriptors.
See [Invoking descriptors](http://docs.python.org/2/reference/datamodel.html#invoking-descriptors):
> For instance bindings, the precedence of descriptor invocatio... |
Performance of numpy.searchsorted is poor on structured arrays | 15,139,299 | 12 | 2013-02-28T15:25:59Z | 15,140,956 | 11 | 2013-02-28T16:44:11Z | [
"python",
"arrays",
"numpy",
"binary-search"
] | Sorry in advance if I'm misusing any terms, feel free to correct that.
I have a sorted array with `dtype` `'<f16, |S30'`. When I use `searchsorted` on its first field, it works really slow (about 0.4 seconds for 3 million items). That is much longer than `bisect` takes to do the same on a plain Python list of tuples.
... | I remember seeing this some time ago. If I remember correctly, I think searchsorted makes a temporary copy of the data when the data is not contiguous. If I have time later, I'll take a look at the code to confirm that's what's happening (or maybe someone more familiar with the code can confirm this).
In the mean time... |
How to map number to color using matplotlib's colormap? | 15,140,072 | 20 | 2013-02-28T16:02:39Z | 15,140,118 | 39 | 2013-02-28T16:04:50Z | [
"python",
"matplotlib"
] | Consider a variable `x` containing a floating point number. I want to use matplotlib's colormaps to map this number to a color, but not plot anything. Basically, I want to be able to choose the colormap with `mpl.cm.autumn` for example, use `mpl.colors.Normalize(vmin = -20, vmax = 10)` to set the range, and then map `x... | It's as simple as `cm.hot(0.3)`, which returns `(0.82400814813704837, 0.0, 0.0, 1.0)`.
A full working program could read
```
import matplotlib.cm as cm
print cm.hot(0.3)
```
If you also want to have the normalizer, use
```
import matplotlib as mpl
import matplotlib.cm as cm
norm = mpl.colors.Normalize(vmin=-20, v... |
Avoiding long lines of code in Python | 15,140,893 | 5 | 2013-02-28T16:41:22Z | 15,140,925 | 11 | 2013-02-28T16:42:50Z | [
"python",
"python-2.7",
"newline",
"backslash"
] | I try and keep my code within 80 characters wide so it is easy to see side by side in a standard window I set up. In doing this, I have a Python v2.7 construct like this:
```
subseq_id_to_intervals_dict, subseq_id_to_ccid_formats_dict, subseq_id_to_min_max_count_dict = map_cases(opts,
... | You could put the left side of the assignment into parentheses:
```
(subseq_id_to_intervals_dict,
subseq_id_to_ccid_formats_dict,
subseq_id_to_min_max_count_dict) = map_cases(opts,
format_to_ccid_funcs,
sys.stdin)
```
The left s... |
Python Turtle, draw text with on screen with larger font | 15,141,031 | 2 | 2013-02-28T16:47:01Z | 15,141,107 | 7 | 2013-02-28T16:50:23Z | [
"python",
"turtle-graphics"
] | I'm using python turtle's write method to write text on the screen like this:
```
turtle.write("messi fan")
```
The size of the font is too small. How can I increase the size of font? | Use the optional `font` argument to [`turtle.write()`](http://docs.python.org/2/library/turtle.html#turtle.write), from the docs:
> `turtle.write(`*arg*, *move=False*, *align="left"*, *font=("Arial", 8, "normal")*`)`
> **Parameters:**
>
> * **arg** â object to be written to the TurtleScreen
> * **move** â True/... |
C++ alternative to OS.walk | 15,141,536 | 4 | 2013-02-28T17:10:43Z | 15,141,676 | 8 | 2013-02-28T17:17:26Z | [
"c++",
"python",
"file-io"
] | I want to write a C++ program that reads a number of files from a directory, the number of files is indeterminate. I know of a Python implementation - OS.walk, that does this job perfectly :
[Python OS.walk](http://docs.python.org/2/library/os.html#os.walk)
Does anyone have any ideas of a C++ implementation of this O... | ```
#include <boost/filesystem.hpp>
#include <iostream>
int main()
{
boost::filesystem::path path = boost::filesystem::current_path();
boost::filesystem::recursive_directory_iterator itr(path);
while (itr != boost::filesystem::recursive_directory_iterator())
{
std::cout << itr->path().string() << std::endl;
... |
Region: IOError: [Errno 22] invalid mode ('w') or filename | 15,141,761 | 11 | 2013-02-28T17:22:29Z | 15,141,799 | 21 | 2013-02-28T17:24:53Z | [
"python",
"ioerror"
] | I'm not sure why, but for some reason, whenever I have "region" in the file name of the output file, it gives me this error:
**IOError: [Errno 22] invalid mode ('w') or filename: 'path\regionlog.txt'**
It does this for **"region.txt"**, **"logregion.txt"**, etc.
```
class writeTo:
def __init__(self, stdout, name... | Use forward slashes:
```
'path/regionlog.txt'
```
Or raw strings:
```
r'path\regionlog.txt'
```
Or at least escape your backslashes:
```
'path\\regionlog.txt'
```
`\r` is a carriage return.
Another option: use `os.path.join` and you won't have to worry about slashes at all:
```
output = os.path.abspath(os.path.... |
multi document insert using mongoengine into mongodb | 15,143,482 | 9 | 2013-02-28T18:58:10Z | 15,154,876 | 13 | 2013-03-01T09:54:29Z | [
"python",
"mongodb",
"flask",
"mongoengine"
] | In my flask app I am using MongoeEgine. I am trying to insert multiple documents into my places collection in my MongoDB.
My document class is defined as
```
class places(db.Document):
name = db.StringField(max_length=200, required=True)
loc = db.GeoPointField(required=True)
def __unicode__(self):
ret... | `Places.objects.insert` doesn't take a list of dictionaries it has to be `Places` instances. Normal operations would be to create individual instances of `Places` and save or insert eg:
```
Places(name="test", loc=[-87, 101]).save()
Places(name="test 2", loc=[-87, 101]).save()
```
However if you want to do a bulk ins... |
How to Multi-thread an Operation Within a Loop in Python | 15,143,837 | 17 | 2013-02-28T19:17:13Z | 15,143,994 | 40 | 2013-02-28T19:27:05Z | [
"python",
"multithreading",
"python-multithreading"
] | Say I have a very large list and I'm performing an operation like so:
```
for item in items:
try:
api.my_operation(item)
except:
print 'error with item'
```
My issue is two fold:
* There are a lot of items
* api.my\_operation takes forever to return
I'd like to use multi-threading to spin up... | First, in Python, if your code is CPU-bound, multithreading won't help, because only one thread can hold the Global Interpreter Lock, and therefore run Python code, at a time. So, you need to use processes, not threads.
This is not true if your operation "takes forever to return" because it's IO-boundâthat is, waiti... |
How to Multi-thread an Operation Within a Loop in Python | 15,143,837 | 17 | 2013-02-28T19:17:13Z | 15,144,765 | 9 | 2013-02-28T20:11:38Z | [
"python",
"multithreading",
"python-multithreading"
] | Say I have a very large list and I'm performing an operation like so:
```
for item in items:
try:
api.my_operation(item)
except:
print 'error with item'
```
My issue is two fold:
* There are a lot of items
* api.my\_operation takes forever to return
I'd like to use multi-threading to spin up... | **Edit**: forgot to mention that this works on Python 2.7.x
There's multiprocesing.pool, and the following sample illustrates how to use one of them:
```
from multiprocessing.pool import ThreadPool as Pool
# from multiprocessing import Pool
pool_size = 5 # your "parallelness"
pool = Pool(pool_size)
def worker(ite... |
boolean indexing that can produce a view to a large pandas dataframe? | 15,143,842 | 12 | 2013-02-28T19:17:19Z | 15,144,847 | 8 | 2013-02-28T20:16:14Z | [
"python",
"dataframe",
"pandas"
] | Got a large dataframe that I want to take slices of (according to multiple boolean criteria), and then modify the entries in those slices in order to change the original dataframe -- i.e. I need a `view` to the original. Problem is, fancy indexing always returns a `copy`. Thought of the `.ix` method, but boolean indexi... | Even though `df.loc[idx]` may be a copy of a portion of `df`, [**assignment** to `df.loc[idx]`](http://pandas.pydata.org/pandas-docs/stable/indexing.html#why-does-the-assignment-when-using-chained-indexing-fail) modifies `df` itself. (This is also true of `df.iloc` and `df.ix`.)
For example,
```
import pandas as pd
i... |
Error, Using deprecated class PySimpleApp after removing EPD | 15,144,168 | 2 | 2013-02-28T19:38:14Z | 15,144,343 | 7 | 2013-02-28T19:48:16Z | [
"python",
"osx",
"matplotlib",
"wxpython"
] | I am using spyder on Mac OSX 10.8.2 and I had Enthought which I uninstalled. In my code I used pyplot from matplotlib.
However I keep getting the following warning when I run the simple plot program.
```
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/backends/backend_wx.py:13... | You should use wx.App(False) instead of wx.PySimpleApp. PySimpleApp has been deprecated in wxPython 2.9. wx.App(False) does basically the same thing. |
NumPy genfromtxt: using filling_missing correctly | 15,144,352 | 7 | 2013-02-28T19:48:44Z | 15,146,029 | 7 | 2013-02-28T21:31:07Z | [
"python",
"csv",
"numpy",
"genfromtxt"
] | I am attempting to process data saved to CSV that may have missing values in an unknown number of columns (up to around 30). I am attempting to set those missing values to '0' using `genfromtxt`'s `filling_missing` argument. Here is a minimal working example for numpy 1.6.2 running in ActiveState ActivePython 2.7 32 bi... | It's not obvious from the documentation, but `filling_values="0"` works.
```
In [19]: !cat test.txt
a,b,c,d
1,2,3,4
5,,7,8
9,10,,12
In [20]: a = numpy.genfromtxt('test.txt', delimiter=',', names=True, filling_values="0")
In [21]: print a
[(1.0, 2.0, 3.0, 4.0) (5.0, 0.0, 7.0, 8.0) (9.0, 10.0, 0.0, 12.0)]
``` |
Compositing two images with python wand | 15,144,483 | 6 | 2013-02-28T19:56:12Z | 15,185,159 | 8 | 2013-03-03T11:26:38Z | [
"python",
"imagemagick",
"composition",
"magickwand",
"wand"
] | I need to use python wand (image-magick bindings for python) to create a composite image, but I'm having some trouble figuring out how to do anything other than simply copy pasting the foreground image into the background image. What I want is, given I have two images like:
`](http://docs.wand-py.org/en/0.2-maintenance/wand/image.html#wand.image.Image.composite) method:
```
import urllib2
from wand.image import Image
from wand.display import display
fg_url = 'http://i.stack.imgur.com/Mz9y0.jpg'
bg_url = 'http://i.stack.imgur.com/TAcBA.jpg'... |
In Python, is an "and" statement or all() faster? | 15,145,823 | 2 | 2013-02-28T21:17:48Z | 15,145,833 | 11 | 2013-02-28T21:18:50Z | [
"python"
] | When testing if multiple conditions are True, are `and` statements or `all()` faster? For example:
```
if '1234'.isdigit() and '4567'.isdigit() and '7890'.isdigit():
print "All are digits!"
```
or
```
if all(['1234'.isdigit(), '4567'.isdigit(), '7890'.isdigit()]):
print "All are digits!"
```
Thanks! | `and`s are faster, there is no list creation and no function call.
```
In [10]: %timeit '1234'.isdigit() and '4567'.isdigit() and '7890'.isdigit()
1000000 loops, best of 3: 186 ns per loop
In [11]: %timeit all(['1234'.isdigit(), '4567'.isdigit(), '7890'.isdigit()])
1000000 loops, best of 3: 323 ns per loop
```
`and`... |
Python passing an integer by reference | 15,148,496 | 24 | 2013-03-01T00:45:14Z | 15,148,557 | 33 | 2013-03-01T00:50:51Z | [
"python",
"function",
"pass-by-reference",
"pass-by-value"
] | How can I pass an integer by reference in Python? I want to modify the value of a variable that I am passing to the function. I have read that everything in Python is pass by value, but there has to be an easy trick. For example, in Java you could pass the reference types of `Integer`, `Long`, etc.
1. How can I pass a... | It doesn't quite work that way in python. Python passes references to objects. What you have inside your function is an object -- You're free to mutate that object (if possible). However, integers are *immutable*. One workaround is to pass the integer in a container which can be mutated:
```
def change(x):
x[0] = ... |
Python passing an integer by reference | 15,148,496 | 24 | 2013-03-01T00:45:14Z | 15,150,433 | 15 | 2013-03-01T04:21:28Z | [
"python",
"function",
"pass-by-reference",
"pass-by-value"
] | How can I pass an integer by reference in Python? I want to modify the value of a variable that I am passing to the function. I have read that everything in Python is pass by value, but there has to be an easy trick. For example, in Java you could pass the reference types of `Integer`, `Long`, etc.
1. How can I pass a... | Most cases where you would need to pass by reference are where you need to return more than one value back to the caller. A "best practice" is to use multiple return values, which is much easier to do in Python than in languages like Java.
Here's a simple example:
```
def RectToPolar(x, y):
r = (x ** 2 + y ** 2) ... |
How to specify a custom 404 view for Django using Class Based Views? | 15,149,555 | 5 | 2013-03-01T02:39:19Z | 15,149,642 | 9 | 2013-03-01T02:49:16Z | [
"python",
"django",
"http-status-code-404"
] | Using Django, you can override the default 404 page by doing this in the root `urls.py`:
```
handler404 = 'path.to.views.custom404'
```
How to do this when using Class based views? I can't figure it out and the documentation doesn't seem to say anything.
I've tried:
```
handler404 = 'path.to.view.Custom404.as_view'... | Never mind, I forgot to try this:
```
from path.to.view import Custom404
handler404 = Custom404.as_view()
```
Seems so simple now, it probably doesn't merit a question on StackOverflow. |
Functions and if - else in python. Codeacademy | 15,149,667 | 2 | 2013-03-01T02:51:33Z | 15,149,682 | 7 | 2013-03-01T02:53:32Z | [
"python",
"function"
] | Write a function, shut\_down, that takes one parameter (you can use anything you like; in this case, we'd use s for string). The shut\_down function should return "Shutting down..." when it gets "Yes", "yes", or "YES" as an argument, and "Shutdown aborted!" when it gets "No", "no", or "NO".
If it gets anything other t... | This:
```
s == "Yes" or "yes" or "YES"
```
is equivalent to this:
```
(s == "Yes") or ("yes") or ("YES")
```
Which will always return `True`, since a non-empty string is `True`.
Instead, you want to compare `s` with each string individually, like so:
```
(s == "Yes") or (s == "yes") or (s == "YES") # brackets ju... |
Python (numpy): drop columns by index | 15,149,868 | 5 | 2013-03-01T03:14:06Z | 15,149,907 | 9 | 2013-03-01T03:19:23Z | [
"python",
"numpy"
] | I've got a numpy array and would like to remove some columns based on index. Is there an in-built function for it or some elegant way for such an operation?
Something like:
```
arr = [234, 235, 23, 6, 3, 6, 23]
elim = [3, 5, 6]
arr = arr.drop[elim]
output: [234, 235, 23, 3]
``` | use `numpy.delete`, it will return a new array:
```
import numpy as np
arr = np.array([234, 235, 23, 6, 3, 6, 23])
elim = [3, 5, 6]
np.delete(arr, elim)
``` |
line 60, in make_tuple return tuple(l) TypeError: iter() returned non-iterator of type 'Vector' | 15,150,640 | 10 | 2013-03-01T04:44:06Z | 17,014,721 | 25 | 2013-06-09T22:18:54Z | [
"python",
"class",
"vector",
"iteration",
"pygame"
] | I am new to Vectors and making classes. I am trying to construct my own vector class but when i pass it through my code which is:
position += heading\*distance\_moved
where position and heading are both vectors. heading is normalized. my goal is to repeat my code until position = destination.
What is wrong with this ... | I guess you are using python 3.x, because I've got a similar error.
I'm also new on making class, but it would be nice to share what I learned :)
In 3.x, use `__next__()` instead of `next()` in the definition of classes.
The error haven't occurred after I renamed it in your code, but I got another problem, "'Vector' o... |
Execute a python script on button click | 15,151,133 | 10 | 2013-03-01T05:27:49Z | 15,151,274 | 12 | 2013-03-01T05:39:30Z | [
"javascript",
"python",
"html",
"ajax"
] | I have an HTML page with one button, and I need to execute a python script when we click on the button and return to the same HTML page with the result.
So I need do some validation on return value and perform some action.
Here is my code:
**HTML:**
```
<input type="text" name="name" id="name">
<button type="button... | You can use Ajax, which is easier with [jQuery](http://jquery.com)
```
$.ajax({
url: "/path/to/your/script",
success: function(response) {
// here you do whatever you want with the response variable
}
});
```
and you should read [the jQuery.ajax page](http://api.jquery.com/jQuery.ajax/) since it has too... |
Execute a python script on button click | 15,151,133 | 10 | 2013-03-01T05:27:49Z | 15,151,487 | 7 | 2013-03-01T05:57:25Z | [
"javascript",
"python",
"html",
"ajax"
] | I have an HTML page with one button, and I need to execute a python script when we click on the button and return to the same HTML page with the result.
So I need do some validation on return value and perform some action.
Here is my code:
**HTML:**
```
<input type="text" name="name" id="name">
<button type="button... | Make a page(or a service) in python, which can accept post or get request and process the info and return back a response. It is better if the response is in json format. Then you can use this code to make a call on the button click.
```
<input type="text" name="name" id="name">
<button type="button" id="home" onclick... |
Daemonizing a python script with python-daemon - socket trouble | 15,151,340 | 3 | 2013-03-01T05:45:50Z | 15,153,653 | 7 | 2013-03-01T08:40:42Z | [
"python",
"daemon"
] | I'm try to daemonize some code, but I'm having some trouble.
If I call the code with tklogger(), it runs just fine. However, if I call it in the daemon context, I get the following trace:
```
Traceback (most recent call last):
File "./tklogger.py", line 103, in <module>
tklogger()
File "./tklogger.py", line 4... | The act of daemonizing kills all existing sockets. Therefore, you must open your socket `s` after daemonization (inside the DaemonContext). |
Comparing MongoDB and RethinkDB Bulk Insert Performance | 15,151,554 | 22 | 2013-03-01T06:03:02Z | 15,152,148 | 45 | 2013-03-01T06:49:22Z | [
"python",
"mongodb",
"python-2.7",
"nosql",
"rethinkdb"
] | *This is my official first question here; I welcome any/all criticism of my post so that I can learn how to be a better SO citizen.*
I am vetting non-relational DBMS for storing potentially large email opt-out lists, leaning toward either MongoDB or RethinkDB, using their respective Python client libraries. The pain p... | RethinkDB currently implements batch inserts by doing a single insert at a time on the server. Since Rethink flushes every record to disk (because it's designed with safety first in mind), this has a really bad effect on workloads like this one.
We're doing two things to address this:
1. Bulk inserts will be implemen... |
List Comprehension doesn't work when normal for-loop works fine | 15,154,042 | 2 | 2013-03-01T09:05:26Z | 15,154,057 | 8 | 2013-03-01T09:06:24Z | [
"python"
] | I have trouble getting my list comprehension statement to work even though the for-loop works correctly. I'm using it to create a table with reportlab's Table class
```
# Service Table
heading = [('Service', 'Price', 'Note')]
# This doesn't work as in there is no row in the output
heading.append([(s['name'],s['price'... | Use `extend` instead of `append`:
```
heading.extend((s['name'],s['price'],s['note']) for s in services)
```
`append` creates a new element and takes whatever it gets. If it gets a list, it appends this list as a single new element.
`extend` gets an iterable and adds as many new elements as this iterable contains.
... |
Misspelling Variable Names. Best ways to avoid this sort of error? | 15,156,022 | 2 | 2013-03-01T10:54:16Z | 15,156,048 | 7 | 2013-03-01T10:55:47Z | [
"python"
] | Coming from a background of compiled languages without dynamic typing, something I find frustrating in Python is the potential for inadvertently introducing a new variable name via misspelling.
I had an example of this a few days ago where the code went something like this:
```
received = False
while not received:
... | Use a decent linter, and test your code using automated testing (unit tests, etc.). Most IDEs and text editors can be set up to run a linter automatically.
I recommend using [`flake8`](https://pypi.python.org/pypi/flake8); it combines the output of the [`pep8` style checker](http://pep8.readthedocs.org/en/latest/), th... |
Tastypie Nested Resources - cached_obj_get() takes exactly 2 arguments (1 given) | 15,157,071 | 7 | 2013-03-01T11:50:16Z | 15,159,600 | 14 | 2013-03-01T14:05:03Z | [
"python",
"django",
"python-2.7",
"tastypie"
] | I'm trying to use the example here: <http://django-tastypie.readthedocs.org/en/latest/cookbook.html#nested-resources>
for some reason i get:
> cached\_obj\_get() takes exactly 2 arguments (1 given)
even though i clearly call it with 2 arguments (exactly like in the aforementioned example.
this is my code:
```
def p... | Sorry for the confusion - there was an [API change to improve authorization](https://github.com/toastdriven/django-tastypie/commit/d850758b088761a00f60a474f5b2d683dc1ec3c0) which changed the signature for [`cached_obj_get`](https://github.com/toastdriven/django-tastypie/blob/v0.9.12/tastypie/resources.py#L1103) from:
... |
Requests library: missing file after cx_freeze | 15,157,502 | 9 | 2013-03-01T12:13:24Z | 15,224,335 | 8 | 2013-03-05T12:54:15Z | [
"python",
"python-requests",
"cx-freeze"
] | I'm building an application in python 3.3 which uses the requests library.
When I try to get a URL with SSL connection I want to verify it with verify = true.
This works perfectly when running my python scripts.
When I freeze the same scripts it crashes. It misses something and I really cant figure out how to integrat... | Looking at the requests source, it seems you can pass the path to the `cacert.pem` file as `verify=path`, instead of `verify=True`. So you don't need to modify requests for it to work.
You can pass the path of a file to include in the `include-files` parameter of the cx\_Freeze options ([docs](http://cx_freeze.readthe... |
Removing entries from a dictionary based on values | 15,158,599 | 10 | 2013-03-01T13:11:10Z | 15,158,637 | 7 | 2013-03-01T13:13:03Z | [
"python"
] | I have a dictionary with character-integer key-value pair. I want to remove all those key value pairs where the value is 0.
For example:
```
>>> hand
{'a': 0, 'i': 0, 'm': 1, 'l': 1, 'q': 0, 'u': 0}
```
I want to reduce the same dictionary to this:
```
>>> hand
{'m': 1, 'l': 1}
```
Is there an easy way to do that? | You can use a [dict comprehension](http://docs.python.org/2/tutorial/datastructures.html#dictionaries):
```
>>> { k:v for k, v in hand.items() if v }
{'m': 1, 'l': 1}
```
Or, in pre-2.7 Python, the [`dict`](http://docs.python.org/2/library/stdtypes.html#dict) constructor in combination with a [generator expression](h... |
Removing entries from a dictionary based on values | 15,158,599 | 10 | 2013-03-01T13:11:10Z | 15,158,638 | 7 | 2013-03-01T13:13:05Z | [
"python"
] | I have a dictionary with character-integer key-value pair. I want to remove all those key value pairs where the value is 0.
For example:
```
>>> hand
{'a': 0, 'i': 0, 'm': 1, 'l': 1, 'q': 0, 'u': 0}
```
I want to reduce the same dictionary to this:
```
>>> hand
{'m': 1, 'l': 1}
```
Is there an easy way to do that? | ```
hand = {k: v for k, v in hand.iteritems() if v != 0}
```
For Pre-Python 2.7:
```
hand = dict((k, v) for k, v in hand.iteritems() if v != 0)
```
In both cases you're filtering out the keys whose values are `0`, and assigning `hand` to the new dictionary. |
How to monitor events from workers in a Celery-Django application? | 15,159,394 | 8 | 2013-03-01T13:53:36Z | 15,498,635 | 12 | 2013-03-19T11:46:31Z | [
"python",
"monitor",
"django-celery"
] | According to the celery tutorial regarding [real-time monitoring of celery workers](http://docs.celeryproject.org/en/latest/userguide/monitoring.html#guide-monitoring), one can also programmatically capture the events produced by the workers and take action accordingly.
My question is how can I integrate a monitor as ... | Ok, I found a way of doing this, though I am not sure that this is the solution, but it works for me. The monitor function basically connects directly to the broker and listens to different types of events. My code looks like this:
```
from celery.events import EventReceiver
from kombu import Connection as BrokerConne... |
os.walk() ValueError: need more than 1 value to unpack | 15,159,527 | 4 | 2013-03-01T14:00:18Z | 15,159,580 | 14 | 2013-03-01T14:03:39Z | [
"python",
"scripting",
"os.walk"
] | Alright, I'm working with a Bioloid Premium humanoid robot, and Mac OS X will not recognize it. So I wrote a Python script to detect changes in my /dev/ folder because any connection on a Linux-based system is still given a reference via a file descriptor. My code should work, however, when assigning three variable to ... | `os.walk` returns an iterator that yields three-tuples, not a three-tuple:
```
for root, dirs, files in os.walk(top):
# do stuff with root, dirs, and files
```
```
In [7]: os.walk('.')
Out[7]: <generator object walk at 0x1707050>
In [8]: next(os.walk('.'))
Out[8]:
('.',
['.vim',
'.... |
If comparison statements in Python | 15,159,726 | 3 | 2013-03-01T14:11:21Z | 15,159,783 | 8 | 2013-03-01T14:14:23Z | [
"python",
"if-statement"
] | This block of code returns "cat", "dog", "hamster", *and* "unicorn", but it shouldn't return "unicorn" at all! Is there any reason for this?
```
if random.randint(0,10) < 5:
print("dog")
elif random.randint(0,10) > 5:
print("cat")
elif random.randint(0,10) == 5:
print("hamster")
else:
pri... | You're getting new random number on each comparison. What you probably meant is:
```
my_random_int = random.randint(0,10)
if my_random_int < 5:
print("dog")
elif my_random_int > 5:
print("cat")
elif my_random_int == 5:
print("hamster")
else:
print("unicorn")
``` |
Adding a background image to a plot with known corner coordinates | 15,160,123 | 12 | 2013-03-01T14:30:27Z | 15,160,269 | 17 | 2013-03-01T14:37:16Z | [
"python",
"numpy",
"matplotlib"
] | Say I am plotting a set of points with an image as a background. I've used the [Lena](http://i.stack.imgur.com/N32KD.jpg) image in the example:
```
import numpy as np
import matplotlib.pyplot as plt
from scipy.misc import imread
np.random.seed(0)
x = np.random.uniform(0.0,10.0,15)
y = np.random.uniform(0.0,10.0,15)
i... | Use the `extent` keyword of `imshow`. The order of the argument is `[left, right, bottom, top]`
```
import numpy as np
import matplotlib.pyplot as plt
from scipy.misc import imread
import matplotlib.cbook as cbook
np.random.seed(0)
x = np.random.uniform(0.0,10.0,15)
y = np.random.uniform(0.0,10.0,15)
datafile = cboo... |
Python debugger tells me value of Numpy array is "*** Newest frame" | 15,160,946 | 17 | 2013-03-01T15:14:38Z | 15,161,369 | 23 | 2013-03-01T15:36:38Z | [
"python",
"numpy",
"pdb"
] | What does this mean?
My function gets two numpy arrays from a python/c library. After that function call I turn on the debugger to find a bug, so I add the line to look at the two numpy arrays.
```
import pdb; pdb.set_trace()
```
But for the values of one of the `arrays` `pdb` only returns the message `*** Newes... | The command `d` is the [command for the debugger](http://docs.python.org/2/library/pdb.html#debugger-commands) used to go down the stack to a 'newer frame'. It seems that the parsing cannot not handle this disambiguity.
Try renaming the variable `d`. |
Installation of biopython - python 3.3 not found in registry | 15,161,315 | 6 | 2013-03-01T15:33:45Z | 15,163,523 | 9 | 2013-03-01T17:32:44Z | [
"python",
"windows-7",
"registry",
"biopython"
] | I am trying to install biopython to run with Python 3.3 on a Windows7 computer.
I have downloaded the biopython executable biopython-1.61.win32-py3.3-beta.exe. When I attempt to run the executable, however, I get the message "Python version 3.3 is required, which is not found in the registry." Python version 3.3 is pr... | Python.org provides Windows installers in two flavours, 32 bit ("win32") and 64 bit ("amd64"). You need matching library installers for your Python version. You are trying to use a 32 bit Biopython installer with a 64 bit Python.
As instructed here <http://biopython.org/wiki/Download> there are experimental 64 bit Win... |
get previous value of pandas datetime index | 15,162,605 | 9 | 2013-03-01T16:44:48Z | 15,165,894 | 8 | 2013-03-01T20:02:24Z | [
"python",
"pandas"
] | I have a pandas dataframe with datetime index
```
Date
2013-02-22 00:00:00+00:00 0.280001
2013-02-25 00:00:00+00:00 0.109999
2013-02-26 00:00:00+00:00 -0.150000
2013-02-27 00:00:00+00:00 0.130001
2013-02-28 00:00:00+00:00 0.139999
Name: MOM12
```
and want to evaluate the previous three values of the giv... | Here's one way to do it, first grab the integer location of the index key via `get_loc`:
```
In [5]: t = pd.Timestamp("2013-02-27 00:00:00+00:00")
In [6]: df1.index.get_loc(t)
Out[6]: 3
```
And then you can use `irow` (to get one location, or slice by integer location):
```
In [7]: loc = df1.index.get_loc(t)
In [8... |
Expected a character buffer object | 15,162,673 | 4 | 2013-03-01T16:47:30Z | 18,719,424 | 9 | 2013-09-10T12:50:17Z | [
"python",
"django"
] | Models in this [post](http://stackoverflow.com/questions/15137356/for-loop-in-views). In admin.py:
```
class GroupsAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['first_year', 'many other']}),
]
```
So, in this admin section I can add `first_year` to the special series of ca... | Actually, it is not necessary to transform the `year` field into Charfield, if you want to keep it Integer, as it would be impossible in many cases where you really need a number. The workaround for this 1.5 bug is to make `__unicode__` function return unicode string:
```
class First_Year(models.Model):
year = mod... |
Python/win32com - Check if Program is Open | 15,162,954 | 6 | 2013-03-01T17:01:36Z | 19,390,275 | 7 | 2013-10-15T20:19:18Z | [
"python",
"win32com"
] | I have a script where I use win32com to interact with a COM service. It works as intended when the program is already open. I connect to it using win32com.client.dynamic.Dispatch, then interact with a document that should already be open. Assuming the program is already open, I can easily check if a document is open, b... | try win32com.client.GetActiveObject() method. This is what I use in some convenience functions I've written, this one for Excel:
```
def Excel(visible=True):
'''Get running Excel instance if possible, else
return new instance.
'''
try:
excel = win32com.client.GetActiveObject("Excel.Applicati... |
Overriding list_display in Django admin with custom verbose name | 15,163,334 | 3 | 2013-03-01T17:22:19Z | 15,163,490 | 11 | 2013-03-01T17:31:03Z | [
"python",
"django"
] | I have overridden the list\_display to show inline fields like this:
```
class opportunityAdmin(admin.ModelAdmin):
list_display = ('name', 'Contact', 'Phone', 'Address', 'discovery_date', 'status' , 'outcome')
search_fields = ['name', 'tags' , 'description']
#readonly_fields = ('discovery_date','close_date... | You would need to define the `short_description` attribute on your functions: <https://docs.djangoproject.com/en/stable/ref/contrib/admin/actions/#writing-action-functions>
For example:
`Contact.short_description = 'foo'` |
pythonic way for FIFO order in Dictionary | 15,163,762 | 2 | 2013-03-01T17:44:25Z | 15,163,774 | 8 | 2013-03-01T17:45:08Z | [
"python",
"dictionary"
] | I am trying to populate a dictionary in python but I would like to preserve the order of the keys as they get in - exactly FIFO like a list would do it.
For example,
I read a file called animals.txt containing the following information:
```
animal\tconservation_status\n
dog\tdomesticated\n
tiger\tEN\n
panda\tEN\n
``... | Yes. You use a [collections.OrderedDict](http://docs.python.org/2/library/collections.html#collections.OrderedDict) instead of a regular dictionary.
```
>>> d = OrderedDict((x,x) for x in reversed(range(10)) )
>>> d
OrderedDict([(9, 9), (8, 8), (7, 7), (6, 6), (5, 5), (4, 4), (3, 3), (2, 2), (1, 1), (0, 0)])
>>> regul... |
How do I maintain row/column orientation of vectors in numpy? | 15,165,170 | 10 | 2013-03-01T19:15:38Z | 15,165,416 | 31 | 2013-03-01T19:32:24Z | [
"python",
"numpy"
] | Coming from a background of Matlab/Octave, I have been trying to learn numpy. One thing that has been tripping me up over and over is the distinction between vectors and multi-dimensional arrays. For this question I'll give a specific problem I'm having, but I'd be much obliged if someone could also explain the more ge... | First, the easy way to do what you want:
```
Y = X[:,4:]
```
Now, the reason numpy wasn't doing this when you were trying it before has to do with how arrays work in Python, and actually in most programming languages. When you write something like `a[4]`, that's accessing the fifth element of the array, not giving yo... |
Sublime Text 2 encoding error with python3 build | 15,166,076 | 8 | 2013-03-01T20:13:06Z | 15,174,760 | 27 | 2013-03-02T12:57:54Z | [
"python",
"character-encoding",
"sublimetext2"
] | When running my python3 script from Sublime Text 2, the following error occures:
```
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
```
Furthermore, when running the same script from the terminal, the problem doesn't appear.
The build system settings for Sublime ... | After some investigation and research, I figured out what the problem is:
Missing LANG env variable in the subprocess, ran by Sublime Text 2. I fixed it by just adding the LANG variable in my build settings like so:
```
{
"cmd": ["python3", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"select... |
python logging does not work at all | 15,167,348 | 7 | 2013-03-01T21:41:46Z | 15,167,862 | 14 | 2013-03-01T22:22:22Z | [
"python",
"logging"
] | I am trying to use logging in my small python project. Following the tutorial, I added the code below to my code, but the message wan't logged to the file as it was supposed to.
```
import logging
logging.basicConfig(
filename = "a.log",
filemode="w",
level = logging.DEBUG)
logging.error("Log initializatio... | You called `basicConfig()` twice at least; the first time without a filename. Clear the handlers and try again:
```
logging.getLogger('').handlers = []
logging.basicConfig(
filename = "a.log",
filemode="w",
level = logging.DEBUG)
``` |
Python, Using files as stdin and stdout for subprocess | 15,167,603 | 9 | 2013-03-01T22:02:38Z | 15,906,410 | 15 | 2013-04-09T15:42:15Z | [
"python",
"batch-file",
"subprocess",
"stdout",
"stdin"
] | Specifically, how do I replicate the following batch command using python subprocess module?:
```
myprogram<myinput.in > myoutput.out
```
If you don't know, I am trying to run myprogram using the contents of myinput.in as the standard input and myoutput.out as standard output.
(myprogram is written in c and I/O ... | The error messages from python should tell you exactly what is going wrong:
* you open `myoutput.out` read only
* it is opened as `myout` but then you use `myoutput`
Also, `shell=True` is unnecessary here.
The following should work:
```
myinput = open('myinput.in')
myoutput = open('myoutput.out', 'w')
p = subproces... |
How to create a temporary file that can be read by a subprocess? | 15,169,101 | 22 | 2013-03-02T00:18:13Z | 15,169,463 | 11 | 2013-03-02T01:04:53Z | [
"python",
"windows",
"temporary-files"
] | I'm writing a Python script that needs to write some data to a temporary file, then create a subprocess running a C++ program that will read the temporary file. I'm trying to use [`NamedTemporaryFile`](http://docs.python.org/2/library/tempfile.html#tempfile.NamedTemporaryFile) for this, but according to the docs,
> Wh... | You can always go low-level, though am not sure if it's clean enough for you:
```
fd, filename = tempfile.mkstemp()
try:
os.write(fd, someStuff)
os.close(fd)
# ...run the subprocess and wait for it to complete...
finally:
os.remove(filename)
``` |
How to create a temporary file that can be read by a subprocess? | 15,169,101 | 22 | 2013-03-02T00:18:13Z | 15,235,559 | 12 | 2013-03-05T22:40:56Z | [
"python",
"windows",
"temporary-files"
] | I'm writing a Python script that needs to write some data to a temporary file, then create a subprocess running a C++ program that will read the temporary file. I'm trying to use [`NamedTemporaryFile`](http://docs.python.org/2/library/tempfile.html#tempfile.NamedTemporaryFile) for this, but according to the docs,
> Wh... | [According](http://bugs.python.org/issue14243#msg164504) to Richard Oudkerk
> (...) the only reason that trying to reopen a `NamedTemporaryFile` fails on
> Windows is because when we reopen we need to use `O_TEMPORARY`.
and he gives an example of how to do this in Python 3.3+
```
import os, tempfile
DATA = b"hello ... |
How to create a temporary file that can be read by a subprocess? | 15,169,101 | 22 | 2013-03-02T00:18:13Z | 15,259,358 | 14 | 2013-03-06T22:27:25Z | [
"python",
"windows",
"temporary-files"
] | I'm writing a Python script that needs to write some data to a temporary file, then create a subprocess running a C++ program that will read the temporary file. I'm trying to use [`NamedTemporaryFile`](http://docs.python.org/2/library/tempfile.html#tempfile.NamedTemporaryFile) for this, but according to the docs,
> Wh... | Since nobody else appears to be interested in leaving this information out in the open...
`tempfile` does expose a function, `mkdtemp()`, which can trivialize this problem:
```
try:
temp_dir = mkdtemp()
temp_file = make_a_file_in_a_dir(temp_dir)
do_your_subprocess_stuff(temp_file)
remove_your_temp_fil... |
Checking a Python FTP connection | 15,170,503 | 5 | 2013-03-02T03:53:25Z | 15,170,571 | 12 | 2013-03-02T04:03:14Z | [
"python",
"ftplib"
] | I have a FTP connection from which I am downloading many files and processing them in between. I'd like to be able to check that my FTP connection hasn't timed out in between. So the code looks something like:
```
conn = FTP(host='blah')
conn.connect()
for item in list_of_items:
myfile = open('filename', 'w')
... | Send a NOOP command. This does nothing but check that the connection is still going and if you do it periodically it can keep the connection alive.
For example:
```
conn.voidcmd("NOOP")
```
If there is a problem with the connection then the FTP object will throw an exception. You can see from the [documentation](... |
python is not recognised as an internal or external command | 15,171,157 | 10 | 2013-03-02T05:36:19Z | 19,026,571 | 23 | 2013-09-26T11:08:30Z | [
"python",
"cmd"
] | This is a really annoying problem. I've prowled the web for solutions, but all I found was tips about changing the PATH variable, which I did, of course. My Python install directory is C:\Python27. It' a 32 bit version. Whenever I type python in the command prompt, it says that it isn't recognised as an internal or ext... | Just adding the Python path and trying again worked for me (without reboot).
MS-dos command for Python 2.7:
```
set PATH=%PATH%;C:\python27\
```
MS-dos command for Python 3.3:
```
set PATH=%PATH%;C:\python33\
```
(check if that is the folder where you installed Python). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.