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
dump csv from sqlalchemy
2,952,366
9
2010-06-01T18:44:12Z
2,952,829
15
2010-06-01T19:51:28Z
[ "python", "csv", "sqlalchemy", "python-elixir" ]
For some reason, I want to dump a table from a database (sqlite3) in the form of a csv file. I'm using a python script with elixir (based on sqlalchemy) to modify the database. I was wondering if there is any way to dump the table I use to csv. I've seen sqlalchemy [serializer](http://www.sqlalchemy.org/docs/reference...
There are numerous ways to achieve this, including a simple `os.system()` call to the `sqlite3` utility if you have that installed, but here's roughly what I'd do from Python: ``` import sqlite3 import csv con = sqlite3.connect('mydatabase.db') outfile = open('mydump.csv', 'wb') outcsv = csv.writer(outfile) cursor =...
dump csv from sqlalchemy
2,952,366
9
2010-06-01T18:44:12Z
2,952,897
17
2010-06-01T20:02:17Z
[ "python", "csv", "sqlalchemy", "python-elixir" ]
For some reason, I want to dump a table from a database (sqlite3) in the form of a csv file. I'm using a python script with elixir (based on sqlalchemy) to modify the database. I was wondering if there is any way to dump the table I use to csv. I've seen sqlalchemy [serializer](http://www.sqlalchemy.org/docs/reference...
Modifying Peter Hansen's answer here a bit, to use SQLAlchemy instead of raw db access ``` import csv outfile = open('mydump.csv', 'wb') outcsv = csv.writer(outfile) records = session.query(MyModel).all() [outcsv.writerow([getattr(curr, column.name) for column in MyTable.__mapper__.columns]) for curr in records] # or ...
dump csv from sqlalchemy
2,952,366
9
2010-06-01T18:44:12Z
13,267,149
11
2012-11-07T09:50:39Z
[ "python", "csv", "sqlalchemy", "python-elixir" ]
For some reason, I want to dump a table from a database (sqlite3) in the form of a csv file. I'm using a python script with elixir (based on sqlalchemy) to modify the database. I was wondering if there is any way to dump the table I use to csv. I've seen sqlalchemy [serializer](http://www.sqlalchemy.org/docs/reference...
I adapted the above examples to my sqlalchemy based code like this: ``` import csv import sqlalchemy as sqAl metadata = sqAl.MetaData() engine = sqAl.create_engine('sqlite:///%s' % 'data.db') metadata.bind = engine mytable = sqAl.Table('sometable', metadata, autoload=True) db_connection = engine.connect() select = ...
Problems trying to format currency with Python (Django)
2,952,790
13
2010-06-01T19:44:53Z
2,952,906
17
2010-06-01T20:03:15Z
[ "python", "django" ]
I have the following code in Django: ``` import locale locale.setlocale( locale.LC_ALL, '' ) def format_currency(i): return locale.currency(float(i), grouping=True) ``` It work on some computers in dev mode, but as soon as I try to deploy it on production I get this error: ``` Exception Type: TemplateSyntaxErr...
On the production server, try ``` locale.setlocale( locale.LC_ALL, 'en_CA.UTF-8' ) ``` instead of ``` locale.setlocale( locale.LC_ALL, '' ) ``` When you use `''`, the locale is set to the user's default (usually specified by the `LANG` environment variable). On the production server, that appears to be 'C', while a...
Is there something like bpython for Ruby?
2,952,793
20
2010-06-01T19:45:13Z
2,953,389
13
2010-06-01T21:14:20Z
[ "python", "ruby", "ide", "irb", "bpython" ]
IRb is pretty plain compared to [bpython](http://bpython-interpreter.org/screenshots/), even when using [wirble](http://www.rubyinside.com/wirble-tab-completion-and-syntax-coloring-for-irb-336.html). Is there any ruby equivalent of bpython?
You can extend irb to achieve all of bpython's functionality and more with the right gems: * wirble: for syntax highlightning (as you already know) * [bond](http://tagaholic.me/bond/): for more advanced autocompletion * [utilitybelt](http://utilitybelt.rubyforge.org/): for pastebin-like commands * [sketches](http://sk...
Is there something like bpython for Ruby?
2,952,793
20
2010-06-01T19:45:13Z
5,812,728
12
2011-04-28T01:52:40Z
[ "python", "ruby", "ide", "irb", "bpython" ]
IRb is pretty plain compared to [bpython](http://bpython-interpreter.org/screenshots/), even when using [wirble](http://www.rubyinside.com/wirble-tab-completion-and-syntax-coloring-for-irb-336.html). Is there any ruby equivalent of bpython?
Use Pry: <http://pry.github.com> It is written from scratch and let's you: * view method source code * view method documentation (not using RI so you dont have to pre-generate it) * pop in and out of different contexts * invoke at runtime, in any context * syntax highlighting * gist integration * view and replay hist...
Dragon NaturallySpeaking Programmers
2,952,899
9
2010-06-01T20:02:29Z
3,046,416
7
2010-06-15T15:03:43Z
[ "python", "speech-recognition", "speech", "naturallyspeaking" ]
Is there anyway to encorporate Dragon NaturallySpeaking into an event driven program? My boss would really like it if I used DNS to record user voice input without writing it to the screen and saving it directly to XML. I've been doing research for several days now and I can not see a way for this to happen without the...
Solution: download Natlink - <http://qh.antenna.nl/unimacro/installation/installation.html> It's not quite as flexible to use as SAPI but it covers the basics and I got almost everything that I needed out of it. Also, heads up, it and Python need to be downloaded for all users on your machine or it won't work properly ...
Python PEP8: Blank lines convention
2,953,250
8
2010-06-01T20:53:27Z
2,953,268
18
2010-06-01T20:56:14Z
[ "python", "pep8" ]
I am interested in knowing what is the Python convention for new lines between the program? For example, consider this: ``` import os def func1(): def func2(): ``` What should be the ideal new line separation between: 1. the `import` modules and the functions? 2. the functions themselves? I have read PEP8, but...
1. two blank lines between the import statements and other code 2. two blank lines between each function
taking intersection of N-many lists in python
2,953,280
6
2010-06-01T20:57:51Z
2,953,343
13
2010-06-01T21:07:15Z
[ "python", "list", "numpy", "scipy" ]
what's the easiest way to take the intersection of N-many lists in python? if I have two lists a and b, I know I can do: ``` a = set(a) b = set(b) intersect = a.intersection(b) ``` but I want to do something like a & b & c & d & ... for an arbitrary set of lists (ideally without converting to a set first, but if tha...
This works for 1 or more lists. The 0 lists case is not so easy, because it would have to return a set that contains all possible values. ``` def intersection(first, *others): return set(first).intersection(*others) ```
Is it possible to increase the response timeout in Google App Engine?
2,953,419
4
2010-06-01T21:19:40Z
2,953,468
8
2010-06-01T21:28:48Z
[ "python", "google-app-engine", "exception", "timeout", "cron-task" ]
On my local machine the script runs fine but in the cloud it 500 all the time. This is a cron task so I don't really mind if it takes 5min... < class 'google.appengine.runtime.DeadlineExceededError' >: Any idea whether it's possible to increase the timeout? Thanks, rui
You cannot go beyond 30 secs, but you can indirectly increase timeout by employing task queues - and writing task that gradually iterate through your data set and processes it. Each such task run should of course fit into timeout limit. ### EDIT To be more specific, you can use datastore query cursors to resume proce...
Pinging servers in Python
2,953,462
57
2010-06-01T21:27:21Z
2,953,515
17
2010-06-01T21:34:26Z
[ "python", "python-3.x", "ping", "icmp" ]
In Python, is there a way to ping a server through ICMP and return TRUE if the server responds, or FALSE if there is no response?
``` import subprocess ping_response = subprocess.Popen(["/bin/ping", "-c1", "-w100", "192.168.0.1"], stdout=subprocess.PIPE).stdout.read() ```
Pinging servers in Python
2,953,462
57
2010-06-01T21:27:21Z
10,402,323
63
2012-05-01T18:29:04Z
[ "python", "python-3.x", "ping", "icmp" ]
In Python, is there a way to ping a server through ICMP and return TRUE if the server responds, or FALSE if there is no response?
If you don't need to support Windows, here's a really concise way to do it: ``` import os hostname = "google.com" #example response = os.system("ping -c 1 " + hostname) #and then check the response... if response == 0: print hostname, 'is up!' else: print hostname, 'is down!' ``` This works because ping returns ...
Pinging servers in Python
2,953,462
57
2010-06-01T21:27:21Z
22,080,370
7
2014-02-27T21:06:03Z
[ "python", "python-3.x", "ping", "icmp" ]
In Python, is there a way to ping a server through ICMP and return TRUE if the server responds, or FALSE if there is no response?
A pure Python ping service as a class, Linux or Windows, which uses threads: <https://github.com/duanev/ping-python>
Pinging servers in Python
2,953,462
57
2010-06-01T21:27:21Z
32,684,938
16
2015-09-20T22:24:11Z
[ "python", "python-3.x", "ping", "icmp" ]
In Python, is there a way to ping a server through ICMP and return TRUE if the server responds, or FALSE if there is no response?
This function works in any OS ``` def ping(host): """ Returns True if host responds to a ping request """ import os, platform # Ping parameters as function of OS ping_str = "-n 1" if platform.system().lower()=="windows" else "-c 1" # Ping return os.system("ping " + ping_str + " " + h...
Python unicode Decode Error SUDs
2,953,651
3
2010-06-01T21:55:47Z
2,953,888
10
2010-06-01T22:42:29Z
[ "python", "unicode", "suds" ]
OK so I have `# -*- coding: utf-8 -*-` at the top of my script and it worked for being able to pull data from the database that had funny chars(Ñ ,Õ,é,—,–,’,…) in it and store that data into variables...but I have run into other problems, see I pull my data, organize it, and then dump it into a variables lik...
`#-*- coding: xxx -*-` has nothing to do with this error, it only applies to the encoding of the *source file* it is declared in, not the content of variables coming from a database. Your error says that you try to pass a `str` type object containing non ASCII characters to the `unicode()` constructor (which is called...
Accessing relative path in Python
2,953,828
10
2010-06-01T22:28:02Z
2,953,851
13
2010-06-01T22:33:36Z
[ "python", "path" ]
I'm running a Mac OS X environment and am used to using ~/ to provide the access to the current user's directory. For example, in my python script I'm just trying to use ``` os.chdir("/Users/aaron/Desktop/testdir/") ``` But would like to use ``` os.chdir("~/Desktop/testdir/") ``` I'm getting a no such file or dire...
You'll need to use [`os.path.expanduser(path)`](http://docs.python.org/library/os.path#os.path.expanduser) `os.chdir("~/Desktop/testdir/")` is looking for a directory named "~" in the current working directory. Also pay attention to the documentation of that function - specifically that you'll need the `$HOME` enviro...
Windows path in python
2,953,834
24
2010-06-01T22:29:06Z
2,953,843
38
2010-06-01T22:30:58Z
[ "python", "path" ]
What is the best way to represent a windows directory, for example "C:\meshes\as"? I have been trying to modify a script but it never works because I can't seem to get the directory right, I assume because of the '\' acting as escape character?
you can use always: ``` 'C:/mydir' ``` this works both in linux and windows. Other posibility is ``` 'C:\\mydir' ``` if you have problems with some names you can also try raw strings: ``` r'C:\mydir' ``` however best practice is to use the `os.path` module functions that always select the correct configuration fo...
built in function for computing overlap in Python
2,953,967
13
2010-06-01T23:03:45Z
2,953,979
43
2010-06-01T23:07:43Z
[ "python" ]
is there a built in function to compute the overlap between two discrete intervals, e.g. the overlap between [10, 15] and [20, 38]? In that case the overlap is 0. If it's [10, 20], [15, 20], the overlap is 5.
You can use max and min: ``` >>> def getOverlap(a, b): ... return max(0, min(a[1], b[1]) - max(a[0], b[0])) >>> getOverlap([10, 25], [20, 38]) 5 >>> getOverlap([10, 15], [20, 38]) 0 ```
built in function for computing overlap in Python
2,953,967
13
2010-06-01T23:03:45Z
2,953,989
8
2010-06-01T23:10:19Z
[ "python" ]
is there a built in function to compute the overlap between two discrete intervals, e.g. the overlap between [10, 15] and [20, 38]? In that case the overlap is 0. If it's [10, 20], [15, 20], the overlap is 5.
Check out pyinterval <http://code.google.com/p/pyinterval/> ``` import interval x=interval.interval[10, 15] y=interval.interval[20, 38] z=interval.interval[12,18] print(x & y) # interval() print(x & z) # interval([12.0, 15.0]) ```
Dynamically adding @property in python
2,954,331
15
2010-06-02T00:49:46Z
2,954,373
29
2010-06-02T01:02:36Z
[ "python" ]
I know that I can dynamically add an instance method to an object by doing something like: ``` import types def my_method(self): # logic of method # ... # instance is some instance of some class instance.my_method = types.MethodType(my_method, instance) ``` Later on I can call `instance.my_method()` and self will...
The `property` descriptor objects needs to live in the **class**, *not* in the **instance**, to have the effect you desire. If you don't want to alter the existing class in order to avoid altering the behavior of other instances, you'll need to make a "per-instance class", e.g.: ``` def addprop(inst, name, method): ...
Python form POST using urllib2 (also question on saving/using cookies)
2,954,381
17
2010-06-02T01:07:00Z
2,954,448
29
2010-06-02T01:28:38Z
[ "python", "cookies", "urllib2" ]
I am trying to write a function to post form data and save returned cookie info in a file so that the next time the page is visited, the cookie information is sent to the server (i.e. normal browser behavior). I wrote this relatively easily in C++ using curlib, but have spent almost an entire day trying to write this ...
There are quite a few problems with the code that you've posted. Typically you'll want to build a custom opener which can handle redirects, https, etc. otherwise you'll run into trouble. As far as the cookies themselves so, you need to call the load and save methods on your `cookiejar`, and use one of subclasses, such ...
Run python in a separate process
2,954,516
3
2010-06-02T01:49:36Z
2,954,541
10
2010-06-02T01:57:20Z
[ "python", "process" ]
I'm looking for a quick bash script or program that will allow me to kick off a python script in a separate process. What's the best way to do this? I know this is incredibly simple, just curious if there's a preferred way to do it.
Just use the ampersand (&) in order to launch the Python process in the background. Python already is executed in a separate process from the BASH script, so saying to run it "in a separate thread" doesn't make much sense -- I'm assuming you simply want it to run in the background: ``` #! /bin/bash python path/to/pyth...
python destructuring-bind dictionary contents
2,955,412
6
2010-06-02T06:17:28Z
17,074,606
9
2013-06-12T20:21:19Z
[ "python", "dictionary", "order" ]
I am trying to 'destructure' a dictionary and associate values with variables names after its keys. Something like ``` params = {'a':1,'b':2} a,b = params.values() ``` but since dictionaries are not ordered, there is no guarantee that params.values() will return values in the order of (a,b). Is there a nice way to do...
One way to do this with less repetition than Jochen's suggestion is with a helper function. This gives the flexibility to list your variable names in any order and only destructure a subset of what is in the dict: ``` pluck = lambda dict, *args: (dict[arg] for arg in args) things = {'blah': 'bleh', 'foo': 'bar'} foo,...
Python template engine
2,955,615
4
2010-06-02T07:05:44Z
2,955,794
16
2010-06-02T07:38:01Z
[ "python", "templates" ]
Could it be possible if somebody could help me get started in writing a python template engine? I'm new to python and as I learn the language I've managed to write a little MVC framework running in its own light-weight-WSGI-like server. I've managed to write a script that finds and replaces keys for values: (Obviously...
There are many powerful template languages supported by Python out there. I prefer [Jinja2](http://jinja.pocoo.org/2/). Also take a look at [Mako](http://www.makotemplates.org/) and [Genshi](http://genshi.edgewall.org/). Mako is fastest among three, but it's ideology allows to have a complex code logic right in templa...
Python - calendar.timegm() vs. time.mktime()
2,956,886
38
2010-06-02T10:42:53Z
2,956,977
7
2010-06-02T10:54:22Z
[ "python", "timezone" ]
I seem to have a hard time getting my head around this. What's the difference between `calendar.timegm()` and `time.mktime()`? Say I have a `datetime.datetime` with no tzinfo attached, shouldn't the two give the same output? Don't they both give the number of seconds between epoch and the date passed as a parameter? ...
`calendar.timegm` converts from UTC timestamp, [`time.mktime` converts from *local* time not UTC](http://docs.python.org/library/time.html#time.mktime). 8 hours difference in their results corresponds exactly to timezone of your location.
Python - calendar.timegm() vs. time.mktime()
2,956,886
38
2010-06-02T10:42:53Z
2,956,997
67
2010-06-02T10:56:53Z
[ "python", "timezone" ]
I seem to have a hard time getting my head around this. What's the difference between `calendar.timegm()` and `time.mktime()`? Say I have a `datetime.datetime` with no tzinfo attached, shouldn't the two give the same output? Don't they both give the number of seconds between epoch and the date passed as a parameter? ...
[`time.mktime()`](http://docs.python.org/library/time.html#time.mktime) assumes that the passed tuple is in local time, [`calendar.timegm()`](http://docs.python.org/library/calendar.html#calendar.timegm) assumes it's in GMT/UTC. Depending on the interpretation the tuple represents a different time, so the functions ret...
BeautifulSoup: just get inside of a tag, no matter how many enclosing tags there are
2,957,013
25
2010-06-02T10:58:49Z
2,957,181
52
2010-06-02T11:27:40Z
[ "python", "beautifulsoup" ]
I'm trying to scrape all the inner html from the `<p>` elements in a web page using BeautifulSoup. There are internal tags, but I don't care, I just want to get the internal text. For example, for: ``` <p>Red</p> <p><i>Blue</i></p> <p>Yellow</p> <p>Light <b>green</b></p> ``` How can I extract: ``` Red Blue Yellow L...
Short answer: `soup.findAll(text=True)` This has already been answered, [here on StackOverflow](http://stackoverflow.com/questions/1936466/beautifulsoup-grab-visible-webpage-text) and in the [BeautifulSoup documentation](http://www.crummy.com/software/BeautifulSoup/documentation.html#Advanced%20Topics). **UPDATE:** ...
Make 2 functions run at the same time
2,957,116
13
2010-06-02T11:16:48Z
2,957,131
26
2010-06-02T11:19:09Z
[ "python", "multithreading", "parallel-processing" ]
I am trying to make 2 functions run at the same time. ``` def func1(): print 'Working' def func2(): print 'Working' func1() func2() ``` Does anyone know how to do this?
Do this: ``` import threading from threading import Thread def func1(): print 'Working' def func2(): print 'Working' if __name__ == '__main__': Thread(target = func1).start() Thread(target = func2).start() ```
Crossed import in django
2,958,141
3
2010-06-02T13:30:16Z
2,980,900
7
2010-06-05T15:17:55Z
[ "python", "django", "django-models", "import" ]
On example, i have 2 apps: alpha and beta in alpha/models.py import of model from beta.models and in beta/models.py import of model from alpha.models manage.py validate says that ImportError: cannot import name ModelName how to solve this problem?
I have had this issue in the past there are two models that refer to one another, i.e. using a `ForeignKey` field. There is a simple way to deal with it, per the [Django documentation](http://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey): > If you need to create a relationship on a model that has not ye...
What are the advantages or difference in “assert False” and “self.assertFalse”
2,958,169
21
2010-06-02T13:33:37Z
2,958,183
19
2010-06-02T13:35:54Z
[ "python", "assert", "unit-testing" ]
I am wrting test's and I have heard some people saying to use `self.assertFalse` rather than `assert False`. Why is this and are there any advantages to be had?
`assert False` throws an exception without useful logging information. The test had an error. `self.assertFalse()` throws a test failure exception with test failure information like a message and a test name. There's a difference between an error -- test could not even run -- and a failure -- test code worked but pro...
What are the advantages or difference in “assert False” and “self.assertFalse”
2,958,169
21
2010-06-02T13:33:37Z
2,958,450
27
2010-06-02T14:04:42Z
[ "python", "assert", "unit-testing" ]
I am wrting test's and I have heard some people saying to use `self.assertFalse` rather than `assert False`. Why is this and are there any advantages to be had?
If you run ``` import unittest class Test_Unittest(unittest.TestCase): def test_assert(self): assert False def test_assertFalse(self): self.assertFalse(True) if __name__ == '__main__': unittest.main() ``` You get the same logging information, the same failure: ``` FF ===================...
Equivalent to GetTickCount() on Linux
2,958,291
26
2010-06-02T13:47:40Z
2,958,359
25
2010-06-02T13:55:08Z
[ "python", "c", "linux", "time" ]
I'm looking for an equivalent to [`GetTickCount()`](http://msdn.microsoft.com/en-us/library/ms724408%28VS.85%29.aspx) on Linux. Presently I am using Python's [`time.time()`](http://docs.python.org/library/time.html#time.time) which presumably calls through to [`gettimeofday()`](http://www.kernel.org/doc/man-pages/onli...
You can use [CLOCK\_MONOTONIC](http://www.opengroup.org/onlinepubs/000095399/functions/clock_getres.html) e.g. in C: ``` struct timespec ts; if(clock_gettime(CLOCK_MONOTONIC,&ts) != 0) { //error } ``` See this question for a Python way - <http://stackoverflow.com/questions/1205722/how-do-i-get-monotonic-time-duratio...
Python division
2,958,684
70
2010-06-02T14:33:00Z
2,958,705
7
2010-06-02T14:35:14Z
[ "python", "math", "python-2.x" ]
Can somebody explain this to me? I was trying to normalize a set of numbers from -100 to 0 to a range of 10-100 and was having problems only to notice that even with no variables at all, this does not evaluate the way I would expect it to: ``` >>> (20-10) / (100-10) 0 ``` EDIT: float division doesn't work either: ``...
You need to change it to a float BEFORE you do the division. That is: ``` float(20 - 10) / (100 - 10) ```
Python division
2,958,684
70
2010-06-02T14:33:00Z
2,958,712
11
2010-06-02T14:35:57Z
[ "python", "math", "python-2.x" ]
Can somebody explain this to me? I was trying to normalize a set of numbers from -100 to 0 to a range of 10-100 and was having problems only to notice that even with no variables at all, this does not evaluate the way I would expect it to: ``` >>> (20-10) / (100-10) 0 ``` EDIT: float division doesn't work either: ``...
You're [putting Integers in so Python is giving you an integer back](http://docs.python.org/reference/expressions.html#binary-arithmetic-operations): ``` >>> 10 / 90 0 ``` If if you cast this to a float afterwards the rounding will have already been done, in other words, 0 integer will always become 0 float. If you ...
Python division
2,958,684
70
2010-06-02T14:33:00Z
2,958,717
154
2010-06-02T14:36:53Z
[ "python", "math", "python-2.x" ]
Can somebody explain this to me? I was trying to normalize a set of numbers from -100 to 0 to a range of 10-100 and was having problems only to notice that even with no variables at all, this does not evaluate the way I would expect it to: ``` >>> (20-10) / (100-10) 0 ``` EDIT: float division doesn't work either: ``...
You're using Python 2.x, where integer divisions will truncate instead of becoming a floating point number. ``` >>> 1 / 2 0 ``` You should make one of them a `float`: ``` >>> float(10 - 20) / (100 - 10) -0.1111111111111111 ``` or `from __future__ import division`, which the forces `/` to adopt Python 3.x's behavior...
Unable to install pyodbc on Linux
2,960,339
28
2010-06-02T18:14:52Z
2,960,431
26
2010-06-02T18:27:22Z
[ "python", "linux", "centos", "pyodbc" ]
I am running Linux (2.6.18-164.15.1.el5.centos.plus) and trying to install pyodbc. I am doing pip install pyodbc and get a very long list of errors, which end in > error: command 'gcc' failed with exit status 1 I looked in **/root/.pip/pip.log** and saw the following: > InstallationError: Command /usr/local/bin/pyth...
I resolved my issue by following correct directions on <http://code.google.com/p/pyodbc/wiki/Building> which state: > On Linux, pyodbc is typically built using the unixODBC headers, so you will need unixODBC and its headers installed. On a RedHat/CentOS/Fedora box, this means you would need to install unixODBC-devel: ...
Unable to install pyodbc on Linux
2,960,339
28
2010-06-02T18:14:52Z
9,087,394
46
2012-01-31T21:44:25Z
[ "python", "linux", "centos", "pyodbc" ]
I am running Linux (2.6.18-164.15.1.el5.centos.plus) and trying to install pyodbc. I am doing pip install pyodbc and get a very long list of errors, which end in > error: command 'gcc' failed with exit status 1 I looked in **/root/.pip/pip.log** and saw the following: > InstallationError: Command /usr/local/bin/pyth...
On Ubuntu, you'll need to install unixodbc-dev ``` sudo apt-get install unixodbc-dev ``` Install Pip By using this command ``` sudo apt-get install python-pip ``` once that is installed, you should be able to install pyodbc successfully ``` pip install pyodbc ```
Putting a variable inside a string (python)
2,960,772
79
2010-06-02T19:05:52Z
2,960,791
70
2010-06-02T19:08:13Z
[ "python", "variables" ]
Hi I am quite new to python and this is probably quite a basic question but the help would be much appreciated. I would like to put an int within a string. This is what I am doing at the moment.. ``` end = smooth(data,window_len=40) plot.plot(time[0:len(end)],end) plot.savefig('hanning(40).pdf') #problem line ``` I ...
``` plot.savefig('hanning(%d).pdf' % num) ``` The `%` operator, when following a string, allows you to insert values into that string via format codes (the `%d` in this case). For more details, see the Python documentation: <https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting>
Putting a variable inside a string (python)
2,960,772
79
2010-06-02T19:05:52Z
2,962,966
154
2010-06-03T02:28:27Z
[ "python", "variables" ]
Hi I am quite new to python and this is probably quite a basic question but the help would be much appreciated. I would like to put an int within a string. This is what I am doing at the moment.. ``` end = smooth(data,window_len=40) plot.plot(time[0:len(end)],end) plot.savefig('hanning(40).pdf') #problem line ``` I ...
Oh, the many, many ways... String concatenation: ``` plot.savefig('hanning' + str(num) + '.pdf') ``` Conversion Specifier: ``` plot.savefig('hanning%s.pdf' % num) ``` Using local variable names: ``` plot.savefig('hanning%(num)s.pdf' % locals()) # Neat trick ``` Using format(): ``` plot.savefig('hanning{0}.pdf'....
How can I save all the variables in the current python session?
2,960,864
28
2010-06-02T19:17:45Z
2,961,077
31
2010-06-02T19:46:26Z
[ "python", "save" ]
I want to save all the variables in my current python environment. It seems one option is to use the 'pickle' module. However, I don't want to do this for 2 reasons: 1) I have to call pickle.dump() for each variable 2) When I want to retrieve the variables, I must remember the order in which I saved the variables, a...
If you use [shelve](http://docs.python.org/library/shelve.html), you do not have to remember the order in which the objects are pickled, since `shelve` gives you a dictionary-like object: To shelve your work: ``` import shelve T='Hiya' val=[1,2,3] filename='/tmp/shelve.out' my_shelf = shelve.open(filename,'n') # 'n...
regex in python, can this be improved upon?
2,960,969
2
2010-06-02T19:31:05Z
2,960,988
10
2010-06-02T19:33:42Z
[ "python", "regex" ]
I have this piece of code that finds words that begin with @ or #, ``` p = re.findall(r'@\w+|#\w+', str) ``` Now what irks me about this is repeating \w+. I am sure there is a way to do something like ``` p = re.findall(r'(@|#)\w+', str) ``` That will produce the same result but it doesn't, it instead returns only ...
### The solution You have two options: * Use non-capturing group: `(?:@|#)\w+` * Or even better, a character class: `[@#]\w+` ### References * [regular-expressions.info/Character Class](http://www.regular-expressions.info/charclass.html) and [Groups](http://www.regular-expressions.info/brackets.html) --- ### Unde...
virtualenv on Windows: not over-riding installed package
2,961,103
4
2010-06-02T19:51:04Z
2,963,017
9
2010-06-03T02:44:24Z
[ "python", "virtualenv" ]
My current setup is Python 2.5/ Django 1.1.1 on Windows. I want to start using Django 1.2 on some projects, but can't use it for everything. Which is just the sort of thing I've got [virtualenv](http://pypi.python.org/pypi/virtualenv) for. However, I'm running into a problem I've never encountered and it's hard to Goog...
Based on the bug you filed at bitbucket, it looks like you're using the PYTHONPATH environment variable to point to a directory with some packages, including Django 1.1.1. By design, PYTHONPATH always comes first in your sys.path, even when you have a virtualenv activated (because PYTHONPATH is under your direct and im...
Python: How to create a unique file name?
2,961,509
29
2010-06-02T20:53:04Z
2,961,629
46
2010-06-02T21:12:17Z
[ "python", "file", "unique" ]
I have a python web form with two options - **File upload** and **textarea**. I need to take the values from each and pass them to another command-line program. I can easily pass the file name with file upload options, but I am not sure how to pass the value of the textarea. I think what I need to do is: 1. Generate ...
I didn't think your question was very clear, but if all you need is a unique file name... ``` import uuid unique_filename = uuid.uuid4() ```
Python: How to create a unique file name?
2,961,509
29
2010-06-02T20:53:04Z
2,961,636
34
2010-06-02T21:13:11Z
[ "python", "file", "unique" ]
I have a python web form with two options - **File upload** and **textarea**. I need to take the values from each and pass them to another command-line program. I can easily pass the file name with file upload options, but I am not sure how to pass the value of the textarea. I think what I need to do is: 1. Generate ...
If you want to make temporary files in Python, there's a module called [tempfile](http://docs.python.org/library/tempfile.html) in Python's standard libraries. If you want to launch other programs to operate on the file, use tempfile.mkstemp() to create files, and os.fdopen() to access the file descriptors that mkstemp...
String replacement on a whole text file in Python 3.x?
2,961,524
5
2010-06-02T20:55:44Z
2,962,828
9
2010-06-03T01:38:48Z
[ "python", "string", "python-3.x", "replace" ]
How can I replace a string with another string, within a given text file. Do I just loop through readline() and run the replacement while saving out to a new file? Or is there a better way? I'm thinking that I *could* read the whole thing into memory, but I'm looking for a more elegant solution... Thanks in advance
[fileinput](http://docs.python.org/py3k/library/fileinput.html?highlight=fileinput#module-fileinput) is the module from the Python standard library that supports "what looks like in-place updating of text files" as well as various other related tasks. ``` for line in fileinput.input(['thefile.txt'], inplace=True): ...
Convert multi-dimensional list to a 1D list in Python
2,961,983
20
2010-06-02T22:08:06Z
2,961,997
28
2010-06-02T22:10:58Z
[ "python" ]
A multidimensional list like `l=[[1,2],[3,4]]` could be converted to a 1D one by doing `sum(l,[])`. Can anybody please explain how that happens? A responder said that this technique could only be used to "flatten" a 2D list -- that it wouldn't work for higher multidimensional lists. But it does, if repeated. For examp...
`sum` adds a sequence together using the `+` operator. e.g `sum([1,2,3]) == 6`. The 2nd parameter is an optional start value which defaults to 0. e.g. `sum([1,2,3], 10) == 16`. In your example it does `[] + [1,2] + [3,4]` where `+` on 2 lists concatenates them together. Therefore the result is `[1,2,3,4]` The empty l...
Convert multi-dimensional list to a 1D list in Python
2,961,983
20
2010-06-02T22:08:06Z
2,962,856
23
2010-06-03T01:47:52Z
[ "python" ]
A multidimensional list like `l=[[1,2],[3,4]]` could be converted to a 1D one by doing `sum(l,[])`. Can anybody please explain how that happens? A responder said that this technique could only be used to "flatten" a 2D list -- that it wouldn't work for higher multidimensional lists. But it does, if repeated. For examp...
If your list `nested` is, as you say, "2D" (meaning that you only want to go one level down, and all 1-level-down items of `nested` are lists), a simple list comprehension: ``` flat = [x for sublist in nested for x in sublist] ``` is the approach I'd recommend -- much more efficient than `sum`ming would be (`sum` is ...
Is PyOpenGL a good place to start learning opengl programming?
2,962,571
9
2010-06-03T00:28:13Z
2,962,599
12
2010-06-03T00:34:00Z
[ "python", "graphics", "pyopengl" ]
I want to start learning OpenGL but I don't really want to have to learn another language to do it. I already am pretty proficient in python and enjoy the language. I just want to know how close it is to the regular api? Will I be able to pretty easily follow tutorials and books without too much trouble? I know C++ gi...
With the caveat that I have done very little OpenGL programming myself, I believe that for the purposes of learning, PyOpenGL is a good choice. The main reason is that PyOpenGL, like most other OpenGL wrappers, is just that: a thin wrapper around the OpenGL API. One large benefit of PyOpenGL is that while in C you hav...
What algorithm does Python employ in fractions.gcd()?
2,962,640
9
2010-06-03T00:43:00Z
2,962,681
17
2010-06-03T00:53:46Z
[ "python", "fractions", "greatest-common-divisor" ]
I'm using the fractions module in Python v3.1 to compute the greatest common divisor. I would like to know what algorithm is used. I'm guessing the Euclidean method, but would like to be sure. The docs (<http://docs.python.org/py3k/library/fractions.html?highlight=fractions.gcd#fractions.gcd>) don't help. Can anybody c...
According to [the 3.1.2 source code online](http://svn.python.org/view/python/branches/py3k/Lib/fractions.py?revision=81486&view=markup), here's `gcd` as defined in `Python-3.1.2/Lib/fractions.py`: ``` def gcd(a, b): """Calculate the Greatest Common Divisor of a and b. Unless b==0, the result will have the sa...
How can I create a simple message box in Python?
2,963,263
53
2010-06-03T04:07:21Z
2,963,598
37
2010-06-03T05:54:46Z
[ "python", "wxpython", "tkinter" ]
I'm looking for the same effect as `alert()` in JavaScript. I wrote a simple web-based interpreter this afternoon using Twisted.web. You basically submit a block of Python code through a form, and the client comes and grabs it and executes it. I want to be able to make a simple popup message, without having to re-writ...
Have you looked at [easygui](http://easygui.sourceforge.net/)? ``` import easygui easygui.msgbox("This is a message!", title="simple gui") ```
How can I create a simple message box in Python?
2,963,263
53
2010-06-03T04:07:21Z
2,963,616
7
2010-06-03T05:59:48Z
[ "python", "wxpython", "tkinter" ]
I'm looking for the same effect as `alert()` in JavaScript. I wrote a simple web-based interpreter this afternoon using Twisted.web. You basically submit a block of Python code through a form, and the client comes and grabs it and executes it. I want to be able to make a simple popup message, without having to re-writ...
In Windows, you can use [ctypes with user32 library](http://docs.python.org/release/2.5.2/lib/ctypes-function-prototypes.html): ``` from ctypes import c_int, WINFUNCTYPE, windll from ctypes.wintypes import HWND, LPCSTR, UINT prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT) paramflags = (1, "hwnd", 0), (1, "t...
How can I create a simple message box in Python?
2,963,263
53
2010-06-03T04:07:21Z
2,965,638
9
2010-06-03T11:52:43Z
[ "python", "wxpython", "tkinter" ]
I'm looking for the same effect as `alert()` in JavaScript. I wrote a simple web-based interpreter this afternoon using Twisted.web. You basically submit a block of Python code through a form, and the client comes and grabs it and executes it. I want to be able to make a simple popup message, without having to re-writ...
On Mac, the python standard library has a module called `EasyDialogs`. There is also a (ctypes based) windows version at <http://www.averdevelopment.com/python/EasyDialogs.html> If it matters to you: it uses native dialogs and doesn't depend on Tkinter like the already mentioned `easygui`, but it might not have as muc...
How can I create a simple message box in Python?
2,963,263
53
2010-06-03T04:07:21Z
3,570,803
11
2010-08-25T22:44:20Z
[ "python", "wxpython", "tkinter" ]
I'm looking for the same effect as `alert()` in JavaScript. I wrote a simple web-based interpreter this afternoon using Twisted.web. You basically submit a block of Python code through a form, and the client comes and grabs it and executes it. I want to be able to make a simple popup message, without having to re-writ...
The code you presented is fine! You just need to explicitly create the "other window in the background" and hide it, with this code: ``` import Tkinter window = Tkinter.Tk() window.wm_withdraw() ``` Right before your messagebox.
How can I create a simple message box in Python?
2,963,263
53
2010-06-03T04:07:21Z
6,716,913
18
2011-07-16T11:03:53Z
[ "python", "wxpython", "tkinter" ]
I'm looking for the same effect as `alert()` in JavaScript. I wrote a simple web-based interpreter this afternoon using Twisted.web. You basically submit a block of Python code through a form, and the client comes and grabs it and executes it. I want to be able to make a simple popup message, without having to re-writ...
Also you can position the other window before withdrawing it so that you position your message ``` #!/usr/bin/env python from Tkinter import * import tkMessageBox window = Tk() window.wm_withdraw() #message at x:200,y:200 window.geometry("1x1+200+200")#remember its .geometry("WidthxHeight(+or-)X(+or-)Y") tkMessageB...
How can I create a simple message box in Python?
2,963,263
53
2010-06-03T04:07:21Z
15,275,420
117
2013-03-07T15:43:10Z
[ "python", "wxpython", "tkinter" ]
I'm looking for the same effect as `alert()` in JavaScript. I wrote a simple web-based interpreter this afternoon using Twisted.web. You basically submit a block of Python code through a form, and the client comes and grabs it and executes it. I want to be able to make a simple popup message, without having to re-writ...
You could use an import and single line code like this: ``` import ctypes # An included library with Python install. ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 1) ``` Or define a function (Mbox) like so: ``` import ctypes # An included library with Python install. def Mbox(title, text, style): ...
multi threading python/ruby vs java?
2,963,615
2
2010-06-03T05:59:48Z
2,965,919
8
2010-06-03T12:35:15Z
[ "java", "python", "ruby" ]
i wonder if the multi threading in python/ruby is equivalent to the one in java? by that i mean, is it as efficient? cause if you want to create a chat application that use comet technology i know that you have to use multi threading. does this mean that i can use python or ruby for that or is it better with java? ...
This is not a question about Ruby, Python or Java, but more about a specific *implementation* of Ruby, Python or Java. There are Java implementations with *extremely* efficient threading implementations and there are Java implementations with extremely *bad* threading implementations. And the same is true for Ruby and ...
Python: NameError: 'self' is not defined
2,963,654
6
2010-06-03T06:09:05Z
2,963,768
20
2010-06-03T06:37:29Z
[ "python", "google-app-engine", "nameerror" ]
I must be doing something stupid. I'm running this in Google App Engine: ``` class MainHandler(webapp.RequestHandler): def render(self, template_name, template_data): path = os.path.join(os.path.dirname(__file__), 'static/templates/%s.html' % template_name) self.response.out.write(template.render(...
The exception is happening while the class is being defined, which means that your indentation is off. Tabs in Python are equivalent to 8 spaces, so if all the preceding lines are using tabs and your tabstop is set to 4 spaces then the indentation only *looks* correct.
python win32 simulate click
2,964,051
4
2010-06-03T07:37:21Z
2,964,135
7
2010-06-03T07:54:13Z
[ "python", "winapi" ]
Let's say I've got a window for which I want to simulate a mouse click at a specific x, y coordinate. I already have the hwnd but I'm not sure how to construct the lParam. I've used SendMessage in the past to click on buttons, etc., but I knew their hwnds. Any help would be greatly appreciated. I also can't help but wo...
You can use the low level windows api thanks to ctypes. See an example below (adapted from something i didn't test it but it should be ok) ``` import ctypes MOUSEEVENTF_MOVE = 0x0001 # mouse move MOUSEEVENTF_ABSOLUTE = 0x8000 # absolute move MOUSEEVENTF_MOVEABS = MOUSEEVENTF_MOVE + MOUSEEVENTF_ABSOLUTE MOUSEEVENTF_LE...
python win32 simulate click
2,964,051
4
2010-06-03T07:37:21Z
5,916,765
7
2011-05-06T20:39:01Z
[ "python", "winapi" ]
Let's say I've got a window for which I want to simulate a mouse click at a specific x, y coordinate. I already have the hwnd but I'm not sure how to construct the lParam. I've used SendMessage in the past to click on buttons, etc., but I knew their hwnds. Any help would be greatly appreciated. I also can't help but wo...
I think this is good one for you, you can use by direct or import this to your python program. ``` """mousemacro.py defines the following functions: click() -- calls left mouse click hold() -- presses and holds left mouse button release() -- releases left mouse button rightclick() -- calls right mouse click righthol...
Django: Meaning of leading underscore in list of tuples used to define choice fields?
2,964,244
38
2010-06-03T08:12:54Z
2,964,256
54
2010-06-03T08:15:50Z
[ "python", "django", "internationalization", "tuples", "underscores" ]
I've seen a few examples defining choice fields like so: ``` COUNTRIES = ( ('fr', _('France')), ('de', _('Germany')), ... ) ``` (source: <http://code.djangoproject.com/ticket/5446> Also see: <http://djangosnippets.org/snippets/494/>) What is the meaning of the leading underscores? And why is the second v...
The leading underscore is the commonly used function alias for the one of the ugettext functions used by the internationalization (i18n) mechanics. It means that when you have i18n running, the choicefield labels will be translated into the appropriate end-user language, if a translation is available. At the top of a...
Is there a 'hello world' website for django? OR (I've installed django, now what)?
2,964,452
5
2010-06-03T08:54:12Z
2,964,507
8
2010-06-03T09:01:14Z
[ "python", "django" ]
I'm learning Python and decided to start familiarizing myself with the (defacto?) Python web framework - django. I have successfully installed the latest release of django. I want a simple 'hello world' website that will get me up and running quickly. I am already familiar with web frameworks (albeit for different lan...
Next step? The (free, online and excellent) [Django book](http://www.djangobook.com/en/2.0/).
Is there an OR filter? - Django
2,964,540
3
2010-06-03T09:08:32Z
2,964,544
7
2010-06-03T09:09:22Z
[ "python", "sql", "django", "django-models", "django-queryset" ]
is there any way of doing the following ``` Unicorn.objects.or_filter(magical=True).or_filter(unicorn_length=15).or_filter(skin_color='White').or_filter(skin_color='Blue') ``` where `or_filter` stands for an isolated match --- I remember using something similar but cannot find the function anymore! Help would be g...
You're looking for [`Q` objects](http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects).
installing paramiko on Windows
2,964,658
8
2010-06-03T09:28:36Z
2,972,313
16
2010-06-04T07:49:34Z
[ "python", "windows", "paramiko" ]
This may sound like a repeated question on SF, but I could not find a clear answer to it, yet.So. I installed Paramiko 1.7 with "setup.py install" command and while running the demo.py program, I got this error: ``` Traceback (most recent call last): File "C:\Documents and Settings\fixavier\Desktop\paramiko-1.7\dem...
Looks like your pycrypto installation is broken or not installed. Try to get a pycrypto for python2.6 installer here and try again after installing it. > <http://www.voidspace.org.uk/python/modules.shtml#pycrypto>
Forced naming of parameters in python
2,965,271
21
2010-06-03T11:00:54Z
2,965,321
8
2010-06-03T11:07:17Z
[ "python", "function", "coding-style", "argument-passing" ]
In python you may have a function definition: ``` def info(object, spacing=10, collapse=1) ``` which could be called in any of the following ways: ``` info(odbchelper) info(odbchelper, 12) info(odbchelper, collapse=0) info(spacing=15, object=odbchelper) ``` thanks to pyth...
This isn't a coding problem, it's a social problem. By creating the code you are creating a contract -- "give me these arguments in this order and I'll give you a result". Sometime later, someone is choosing to break that contract. To what end? Why would someone on your team think it's OK to make a backwards-incompatib...
Forced naming of parameters in python
2,965,271
21
2010-06-03T11:00:54Z
12,064,662
10
2012-08-21T23:54:33Z
[ "python", "function", "coding-style", "argument-passing" ]
In python you may have a function definition: ``` def info(object, spacing=10, collapse=1) ``` which could be called in any of the following ways: ``` info(odbchelper) info(odbchelper, 12) info(odbchelper, collapse=0) info(spacing=15, object=odbchelper) ``` thanks to pyth...
You can force people to use keyword arguments in Python3 by defining a function in the following way. ``` def foo(*, arg0="default0", arg1="default1", arg2="default2"): pass ``` By making the first argument a positional argument with no name you force everyone who calls the function to use the keyword arguments w...
Forced naming of parameters in python
2,965,271
21
2010-06-03T11:00:54Z
14,298,976
56
2013-01-12T23:18:49Z
[ "python", "function", "coding-style", "argument-passing" ]
In python you may have a function definition: ``` def info(object, spacing=10, collapse=1) ``` which could be called in any of the following ways: ``` info(odbchelper) info(odbchelper, 12) info(odbchelper, collapse=0) info(spacing=15, object=odbchelper) ``` thanks to pyth...
In Python 3 - Yes, you can specify `*` in the argument list. > Parameters after “\*” or “\*identifier” are keyword-only parameters and > may only be passed used keyword arguments. Sample code: ``` >>> def foo(pos, *, forcenamed): ... print(pos, forcenamed) ... >>> foo(pos=10, forcenamed=20) 10 20 >>> foo(...
Why doesn't Python require exactly four spaces per indentation level?
2,966,285
11
2010-06-03T13:19:09Z
2,966,339
29
2010-06-03T13:25:25Z
[ "python", "indentation" ]
Whitespace is signification in Python in that code blocks are defined by their indentation. Furthermore, Guido van Rossum recommends using four spaces per indentation level (see [PEP 8: Style Guide for Python Code](http://www.python.org/dev/peps/pep-0008/)). **What was the reasoning behind not requiring exactly four ...
There are no technical reasons. It would not be too hard to modify the Python interpreter to require exactly four spaces per indentation level. Here is one use case for other indentation levels: when typing into the interactive interpreter, it's very handy to use one-space indentations. It saves on typing, it's easier...
Why doesn't Python require exactly four spaces per indentation level?
2,966,285
11
2010-06-03T13:19:09Z
2,966,518
10
2010-06-03T13:44:02Z
[ "python", "indentation" ]
Whitespace is signification in Python in that code blocks are defined by their indentation. Furthermore, Guido van Rossum recommends using four spaces per indentation level (see [PEP 8: Style Guide for Python Code](http://www.python.org/dev/peps/pep-0008/)). **What was the reasoning behind not requiring exactly four ...
Another case that I just encountered on the tutor@python.org mailing list - A blind programmer who is working in Python uses a reader program - apparently the reader program isn't terribly fond of multiple spaces, so it's easier on him to use a single space. There's really no good or technical reason to require exactl...
open() in Python does not create a file if it doesn't exist
2,967,194
327
2010-06-03T15:05:54Z
2,967,244
18
2010-06-03T15:12:12Z
[ "python", "linux", "file-io", "file-permissions" ]
What is the best way to open a file as read/write if it exists, or if it does not, then create it and open it as read/write? From what I read, `file = open('myfile.dat', 'rw')` should do this, right? It is not working for me (Python 2.6.2) and I'm wondering if it is a version problem, or not supposed to work like that...
Change "rw" to "w+" Or use 'a+' for appending (not erasing existing content)
open() in Python does not create a file if it doesn't exist
2,967,194
327
2010-06-03T15:05:54Z
2,967,249
422
2010-06-03T15:12:39Z
[ "python", "linux", "file-io", "file-permissions" ]
What is the best way to open a file as read/write if it exists, or if it does not, then create it and open it as read/write? From what I read, `file = open('myfile.dat', 'rw')` should do this, right? It is not working for me (Python 2.6.2) and I'm wondering if it is a version problem, or not supposed to work like that...
You should use `file = open('myfile.dat', 'w+')`
open() in Python does not create a file if it doesn't exist
2,967,194
327
2010-06-03T15:05:54Z
2,967,291
23
2010-06-03T15:18:57Z
[ "python", "linux", "file-io", "file-permissions" ]
What is the best way to open a file as read/write if it exists, or if it does not, then create it and open it as read/write? From what I read, `file = open('myfile.dat', 'rw')` should do this, right? It is not working for me (Python 2.6.2) and I'm wondering if it is a version problem, or not supposed to work like that...
``` >>> import os >>> if os.path.exists("myfile.dat"): ... f = file("myfile.dat", "r+") ... else: ... f = file("myfile.dat", "w") ``` r+ means read/write
open() in Python does not create a file if it doesn't exist
2,967,194
327
2010-06-03T15:05:54Z
15,359,499
62
2013-03-12T11:06:48Z
[ "python", "linux", "file-io", "file-permissions" ]
What is the best way to open a file as read/write if it exists, or if it does not, then create it and open it as read/write? From what I read, `file = open('myfile.dat', 'rw')` should do this, right? It is not working for me (Python 2.6.2) and I'm wondering if it is a version problem, or not supposed to work like that...
The advantage of the following approach is that the file is **properly closed** at the block's end, even if an exception is raised on the way. It's equivalent to `try-finally`, but much shorter. ``` with open("file.dat","a+") as f: f.write(...) ... ``` > **a+** Opens a file for both appending and reading. The...
open() in Python does not create a file if it doesn't exist
2,967,194
327
2010-06-03T15:05:54Z
30,021,479
11
2015-05-04T01:49:42Z
[ "python", "linux", "file-io", "file-permissions" ]
What is the best way to open a file as read/write if it exists, or if it does not, then create it and open it as read/write? From what I read, `file = open('myfile.dat', 'rw')` should do this, right? It is not working for me (Python 2.6.2) and I'm wondering if it is a version problem, or not supposed to work like that...
Good practice is to use the following: ``` import os writepath = 'some/path/to/file.txt' mode = 'a' if os.path.exists(writepath) else 'w' with open(writepath, mode) as f: f.write('Hello, world!\n') ```
gcc error trying to install PIL in a Python2.6 virtualenv
2,967,224
41
2010-06-03T15:10:28Z
2,967,565
80
2010-06-03T15:47:20Z
[ "python", "gcc", "python-imaging-library", "virtualenv" ]
I have created a virtualenv with the --no-site-packages option. I get an error trying to install PIL: <http://pastebin.com/SVqxs1sC> ``` ... error: command '/usr/bin/gcc' failed with exit status 1 ---------------------------------------- Command /home/dustin/.virtualenvs/django1.2/bin/python -c "import setuptools; _...
You need to install python-dev package. ``` sudo apt-get install python-dev ```
Dendrogram generated by scipy-cluster does not show
2,967,858
12
2010-06-03T16:21:44Z
3,811,834
16
2010-09-28T10:34:50Z
[ "python", "osx", "matplotlib", "scipy", "dendrogram" ]
I am using [scipy-cluster](http://code.google.com/p/scipy-cluster/) to generate a hierarchical clustering on some data. As a final step of the application, I call the [`dendrogram`](http://users.soe.ucsc.edu/~eads/cluster.html#-dendrogram) function to plot the clustering. I am running on Mac OS X Snow Leopard using the...
I had the same issue on Ubuntu 10.04. In order to get graphics to display from ipython interactive console, start it with "-pylab" switch, which enables the interactive use of matplotlib: ``` ipython -pylab ``` To get your graphics to display during the execution of a standalone script, use matplotlib.pyplot.show cal...
Is there an R equivalent of the pythonic "if __name__ == "__main__": main()"?
2,968,220
33
2010-06-03T17:13:20Z
2,968,404
30
2010-06-03T17:38:44Z
[ "python" ]
The objective is to have two simple ways to source some code, say func.R, containing a function. Calling `R CMD BATCH func.R` initializes the function and evaluates is. Within a session, issuing `source("func.R")` simply initializes the function. Any idea?
I think that the `interactive()` function might work. This function returns `TRUE` when R is being used interactively and `FALSE` otherwise. So just use `if(interactive())`
How do i program a simple IRC bot in python?
2,968,408
16
2010-06-03T17:39:08Z
2,968,416
11
2010-06-03T17:40:13Z
[ "python", "sockets", "irc", "connect", "bots" ]
I need help writing a basic IRC bot that just connects to a channel.. is anyone able to explain me this? I have managed to get it to connect to the IRC server but i am unable to join a channel and log on. The code i have thus far is: ``` import sockethost = 'irc.freenode.org' port = 6667 join_sock = socket.socket() jo...
It'd probably be easiest to base it on twisted's implementation of the IRC protocol. Take a look at : <http://github.com/brosner/bosnobot> for inspiration.
How do i program a simple IRC bot in python?
2,968,408
16
2010-06-03T17:39:08Z
2,969,441
39
2010-06-03T20:17:06Z
[ "python", "sockets", "irc", "connect", "bots" ]
I need help writing a basic IRC bot that just connects to a channel.. is anyone able to explain me this? I have managed to get it to connect to the IRC server but i am unable to join a channel and log on. The code i have thus far is: ``` import sockethost = 'irc.freenode.org' port = 6667 join_sock = socket.socket() jo...
To connect to an IRC channel, you must send certain IRC protocol specific commands to the IRC server before you can do it. When you connect to the server you must wait until the server has sent all data (MOTD and whatnot), then you must send the PASS command. ``` PASS <some_secret_password> ``` What follows is the N...
How do i program a simple IRC bot in python?
2,968,408
16
2010-06-03T17:39:08Z
12,219,119
13
2012-08-31T16:16:53Z
[ "python", "sockets", "irc", "connect", "bots" ]
I need help writing a basic IRC bot that just connects to a channel.. is anyone able to explain me this? I have managed to get it to connect to the IRC server but i am unable to join a channel and log on. The code i have thus far is: ``` import sockethost = 'irc.freenode.org' port = 6667 join_sock = socket.socket() jo...
I used this as the MAIN IRC code: ``` import socket import sys server = "server" #settings channel = "#channel" botnick = "botname" irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #defines the socket print "connecting to:"+server irc.connect((server, 6667)) ...
2 techniques for including files in a Python distribution: which is better?
2,968,701
10
2010-06-03T18:26:40Z
2,969,087
18
2010-06-03T19:24:01Z
[ "python", "distribution", "distutils" ]
I'm working on packaging a small Python project as a zip or egg file so that it can be distributed. I've come across 2 ways to include the project's config files, both of which seem to produce identical results. **Method 1:** Include this code in setup.py: ``` from distutils.core import setup setup(name='ProjectNam...
MANIFEST.in controls what files are put into the distribution zip file when you call `python setup.py sdist`. It does *not* control what is installed. `data_files` (or better `package_data`) controls what files are installed (and I think also makes sure files are included in the zip file). Use MANIFEST.in for files you...
Python "string_escape" vs "unicode_escape"
2,969,044
13
2010-06-03T19:18:47Z
3,001,998
15
2010-06-08T23:06:46Z
[ "python", "encoding", "quotes", "escaping" ]
[According to the docs](http://docs.python.org/library/codecs.html#standard-encodings), the builtin string encoding `string_escape`: > Produce[s] a string that is suitable as string literal in Python source code ...while the `unicode_escape`: > Produce[s] a string that is suitable as Unicode literal in Python source...
According to my interpretation of the implementation of `unicode-escape` and the unicode `repr` in the CPython 2.6.5 source, yes; the only difference between `repr(unicode_string)` and `unicode_string.encode('unicode-escape')` is the inclusion of wrapping quotes and escaping whichever quote was used. They are both dri...
NTLM authentication in Python
2,969,481
16
2010-06-03T20:21:46Z
3,635,164
10
2010-09-03T11:10:37Z
[ "python", "authentication", "ntlm" ]
I'm trying to implement NTLM authentication on IIS (Windows Server 2003) from Windows 7 with python. LAN Manager Authentication Level: Send NTLM response only. Client machine and server are in the same domain. Domain controller (AD) is on another server (also running Windows Server 2003). I receive 401.1 - Unautho...
I've found out what was wrong. I should keeping the connection alive. That's the goods! Now this problem is solved. ``` class WindoewNtlmMessageGenerator: def __init__(self,user=None): import win32api,sspi if not user: user = win32api.GetUserName() self.sspi_client = sspi.ClientAuth(...
How do I add space between the ticklabels and the axes in matplotlib?
2,969,867
23
2010-06-03T21:19:24Z
2,970,494
22
2010-06-03T23:22:17Z
[ "python", "matplotlib" ]
I've increased the font of my ticklabels successfully, but now they're too close to the axis. I'd like to add a little breathing room between the ticklabels and the axis.
It looks like matplotlib respects these settings as rcParams: ``` pylab.rcParams['xtick.major.pad']='8' pylab.rcParams['ytick.major.pad']='8' ``` Set those *before* you create any figures and you should be fine. I've looked at the source code and there doesn't appear to be any other way to set them programmatically....
How do I add space between the ticklabels and the axes in matplotlib?
2,969,867
23
2010-06-03T21:19:24Z
2,982,893
11
2010-06-06T02:27:09Z
[ "python", "matplotlib" ]
I've increased the font of my ticklabels successfully, but now they're too close to the axis. I'd like to add a little breathing room between the ticklabels and the axis.
This can be done using `set_pad` but you then have to reset the label... ``` for tick in ax.get_xaxis().get_major_ticks(): tick.set_pad(8.) tick.label1 = tick._get_text1() ```
How do I add space between the ticklabels and the axes in matplotlib?
2,969,867
23
2010-06-03T21:19:24Z
29,524,883
19
2015-04-08T20:37:19Z
[ "python", "matplotlib" ]
I've increased the font of my ticklabels successfully, but now they're too close to the axis. I'd like to add a little breathing room between the ticklabels and the axis.
If you don't want to change the spacing globally (by editing your rcParams), and want a cleaner approach, try this: `ax.tick_params(axis='both', which='major', pad=15)` or for just x axis `ax.tick_params(axis='x', which='major', pad=15)`
Removing minimize/maximize buttons in Tkinter
2,969,870
5
2010-06-03T21:20:33Z
2,970,757
17
2010-06-04T00:30:19Z
[ "python", "windows", "tkinter", "manager" ]
I have a python program which opens a new windows to display some 'about' information. This window has its own close button, and I have made it non-resizeable. However, the buttons to maximize and minimize it are still there, and I want them gone. I am using Tkinter, wrapping all the info to display in the Tk class. ...
In general, what decorations the WM (window manager) decides to display can not be easily dictated by a toolkit like Tkinter. So let me summarize what I know plus what I found: ``` import Tkinter as tk root= tk.Tk() root.title("wm min/max") # this removes the maximize button root.resizable(0,0) # # if on MS Window...
Change embedded image type in APIC ID3 tag via Mutagen
2,970,473
4
2010-06-03T23:16:33Z
2,970,873
7
2010-06-04T01:03:55Z
[ "python", "mp3", "id3", "mutagen", "apic" ]
I have a large music library which I have just spent around 30 hours organizing. For some of the MP3 files, I embedded the cover art image as type 0 (Other) and I'd like to change it to type 3 (Front Cover). Is there a way to do this in Python, specifically in Mutagen?
Here's how I was able to pull it off. First, get access to the file in Mutagen: ``` audio = MP3("filename.mp3") ``` Then, get a reference to the tag you're looking for: ``` picturetag = audio.tags['APIC:Folder.jpg'] ``` Then, modify the `type` attribute: ``` picturetag.type = 3 ``` Then, assign it back into the ...
string count with overlapping occurrences
2,970,520
30
2010-06-03T23:29:05Z
2,970,542
36
2010-06-03T23:35:39Z
[ "python", "string", "search" ]
What's the best way to count the number of occurrences of a given string, including overlap in python? is it the most obvious way: ``` def function(string, str_to_search_for): count = 0 for x in xrange(len(string) - len(str_to_search_for) + 1): if string[x:x+len(str_to_search_for)] == str_to_sea...
Well, this *might* be faster since it does the comparing in C: ``` def occurrences(string, sub): count = start = 0 while True: start = string.find(sub, start) + 1 if start > 0: count+=1 else: return count ```
string count with overlapping occurrences
2,970,520
30
2010-06-03T23:29:05Z
11,706,065
21
2012-07-29T02:04:16Z
[ "python", "string", "search" ]
What's the best way to count the number of occurrences of a given string, including overlap in python? is it the most obvious way: ``` def function(string, str_to_search_for): count = 0 for x in xrange(len(string) - len(str_to_search_for) + 1): if string[x:x+len(str_to_search_for)] == str_to_sea...
``` >>> import re >>> text = '1011101111' >>> len(re.findall('(?=11)', text)) 5 ``` If you didn't want to load the whole list of matches into memory, which would never be a problem! you could do this if you really wanted: ``` >>> sum(1 for _ in re.finditer('(?=11)', text)) 5 ``` As a function (`re.escape` makes sure...
Upload and parse csv file with google app engine
2,970,599
7
2010-06-03T23:48:12Z
2,970,785
8
2010-06-04T00:41:15Z
[ "python", "google-app-engine", "csv" ]
I'm wondering if anyone with a better understanding of python and gae can help me with this. I am uploading a csv file from a form to the gae datastore. ``` class CSVImport(webapp.RequestHandler): def post(self): csv_file = self.request.get('csv_import') fileReader = csv.reader(csv_file) for row in fi...
I can't think of a clearer explanation than what the Google engineer you mentioned said. So let's break it down a bit. The Python `csv` module operates on file-like objects, that is a file or something that behaves like a Python file. Hence, csv.reader() expects to get a file object as it's only required parameter. T...
Upload and parse csv file with google app engine
2,970,599
7
2010-06-03T23:48:12Z
2,970,801
12
2010-06-04T00:44:50Z
[ "python", "google-app-engine", "csv" ]
I'm wondering if anyone with a better understanding of python and gae can help me with this. I am uploading a csv file from a form to the gae datastore. ``` class CSVImport(webapp.RequestHandler): def post(self): csv_file = self.request.get('csv_import') fileReader = csv.reader(csv_file) for row in fi...
Short answer, try this: ``` fileReader = csv.reader(csv_file.split("\n")) ``` Long answer, consider the following: ``` for thing in stuff: print thing.strip().split(",") ``` If stuff is a file pointer, each thing is a line. If stuff is a list, each thing is an item. If stuff is a string, each thing is a character...
What are "named tuples" in Python?
2,970,608
476
2010-06-03T23:50:16Z
2,970,698
22
2010-06-04T00:12:23Z
[ "python", "tuples", "namedtuple" ]
Reading the [changes in Python 3.1](http://docs.python.org/py3k/whatsnew/3.1.html#new-improved-and-deprecated-modules), I found something... unexpected: > The sys.version\_info tuple is now a **named tuple**: I never heard about named tuples before, and I thought elements could either be indexed by numbers (like in t...
named tuples allow backward compatibility with code that checks for the version like this ``` >>> sys.version_info[0:2] (3, 1) ``` while allowing future code to be more explicit by using this syntax ``` >>> sys.version_info.major 3 >>> sys.version_info.minor 1 ```
What are "named tuples" in Python?
2,970,608
476
2010-06-03T23:50:16Z
2,970,722
677
2010-06-04T00:19:37Z
[ "python", "tuples", "namedtuple" ]
Reading the [changes in Python 3.1](http://docs.python.org/py3k/whatsnew/3.1.html#new-improved-and-deprecated-modules), I found something... unexpected: > The sys.version\_info tuple is now a **named tuple**: I never heard about named tuples before, and I thought elements could either be indexed by numbers (like in t...
Named tuples are basically easy to create, lightweight object types. Named tuple instances can be referenced using object like variable deferencing or the standard tuple syntax. They can be used similarly to `struct` or other common record types, except that they are immutable. They were added in Python 2.6 and Python ...
What are "named tuples" in Python?
2,970,608
476
2010-06-03T23:50:16Z
2,972,898
31
2010-06-04T09:32:28Z
[ "python", "tuples", "namedtuple" ]
Reading the [changes in Python 3.1](http://docs.python.org/py3k/whatsnew/3.1.html#new-improved-and-deprecated-modules), I found something... unexpected: > The sys.version\_info tuple is now a **named tuple**: I never heard about named tuples before, and I thought elements could either be indexed by numbers (like in t...
namedtuples are a great feature, they are perfect container for data. When you have to "store" data you would use tuples or dictionaries, like: ``` user = dict(name="John", age=20) ``` or: ``` user = ("John", 20) ``` The dictionary approach is overwhelming, since dict are mutable and slower than tuples. On the othe...
What are "named tuples" in Python?
2,970,608
476
2010-06-03T23:50:16Z
13,700,868
55
2012-12-04T10:30:39Z
[ "python", "tuples", "namedtuple" ]
Reading the [changes in Python 3.1](http://docs.python.org/py3k/whatsnew/3.1.html#new-improved-and-deprecated-modules), I found something... unexpected: > The sys.version\_info tuple is now a **named tuple**: I never heard about named tuples before, and I thought elements could either be indexed by numbers (like in t...
[namedtuple](http://docs.python.org/2/library/collections.html#collections.namedtuple) is a **factory function** for making a tuple class. With that class we can create tuples that are callable by name also. ``` import collections #Create a namedtuple class with names "a" "b" "c" Row = collections.namedtuple("Row", [...
What are "named tuples" in Python?
2,970,608
476
2010-06-03T23:50:16Z
34,573,457
15
2016-01-03T04:54:41Z
[ "python", "tuples", "namedtuple" ]
Reading the [changes in Python 3.1](http://docs.python.org/py3k/whatsnew/3.1.html#new-improved-and-deprecated-modules), I found something... unexpected: > The sys.version\_info tuple is now a **named tuple**: I never heard about named tuples before, and I thought elements could either be indexed by numbers (like in t...
> # What are named tuples? To understand named tuples, you first need to know what a tuple is. A tuple is essentially an immutable (can't be changed in-place in memory) list. Here's how you might use a regular tuple: ``` >>> student_tuple = 'Lisa', 'Simpson', 'A' >>> student_tuple ('Lisa', 'Simpson', 'A') >>> studen...
pythonic way to do something N times without an index variable?
2,970,780
85
2010-06-04T00:39:15Z
2,970,789
59
2010-06-04T00:42:08Z
[ "coding-style", "for-loop", "python" ]
Every day I love python more and more. Today, I was writing some code like: ``` for i in xrange(N): do_something() ``` I had to do something N times. But each time didn't depend on the value of `i` (index variable). I realized that I was creating a variable I never used (`i`), and I thought "There surely is a mo...
A slightly faster approach than looping on `xrange(N)` is: ``` import itertools for _ in itertools.repeat(None, N): do_something() ```
pythonic way to do something N times without an index variable?
2,970,780
85
2010-06-04T00:39:15Z
2,970,791
29
2010-06-04T00:42:13Z
[ "coding-style", "for-loop", "python" ]
Every day I love python more and more. Today, I was writing some code like: ``` for i in xrange(N): do_something() ``` I had to do something N times. But each time didn't depend on the value of `i` (index variable). I realized that I was creating a variable I never used (`i`), and I thought "There surely is a mo...
Use the \_ variable, as I learned when I asked this [question](http://stackoverflow.com/questions/1885868/pythonic-way-to-read-a-set-number-of-lines-from-a-file), for example: ``` # A long way to do integer exponentiation num = 2 power = 3 product = 1 for _ in xrange(power): product *= num print product ```
pythonic way to do something N times without an index variable?
2,970,780
85
2010-06-04T00:39:15Z
2,970,875
16
2010-06-04T01:04:39Z
[ "coding-style", "for-loop", "python" ]
Every day I love python more and more. Today, I was writing some code like: ``` for i in xrange(N): do_something() ``` I had to do something N times. But each time didn't depend on the value of `i` (index variable). I realized that I was creating a variable I never used (`i`), and I thought "There surely is a mo...
I just use `for _ in range(n)`, it's straight to the point. It's going to generate the entire list for huge numbers in Python 2, but if you're using Python 3 it's not a problem.
pythonic way to do something N times without an index variable?
2,970,780
85
2010-06-04T00:39:15Z
2,976,490
7
2010-06-04T17:44:09Z
[ "coding-style", "for-loop", "python" ]
Every day I love python more and more. Today, I was writing some code like: ``` for i in xrange(N): do_something() ``` I had to do something N times. But each time didn't depend on the value of `i` (index variable). I realized that I was creating a variable I never used (`i`), and I thought "There surely is a mo...
Assume that you've defined **do\_something** as a function, and you'd like to perform it **N** times. Maybe you can try the following: ``` todos = [do_something] * N for doit in todos: doit() ```