title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Python multiprocessing and a shared counter
2,080,660
31
2010-01-17T10:26:42Z
2,080,668
37
2010-01-17T10:29:54Z
[ "python", "multiprocessing" ]
I'm having troubles with the multiprocessing module. I'm using a Pool of workers with its map method to load data from lots of files and for each of them I analyze data with with a custom function. Each time a file has been processed I would like to have a counter updated so that I can keep track of how many files rema...
The problem is that the `counter` variable is not shared between your processes: each separate process is creating it's own local instance and incrementing that. See [this section](http://docs.python.org/library/multiprocessing.html#sharing-state-between-processes) of the documentation for some techniques you can empl...
Python multiprocessing and a shared counter
2,080,660
31
2010-01-17T10:26:42Z
21,681,534
18
2014-02-10T15:42:38Z
[ "python", "multiprocessing" ]
I'm having troubles with the multiprocessing module. I'm using a Pool of workers with its map method to load data from lots of files and for each of them I analyze data with with a custom function. Each time a file has been processed I would like to have a counter updated so that I can keep track of how many files rema...
Counter class without the race-condition bug: ``` class Counter(object): def __init__(self): self.val = multiprocessing.Value('i', 0) def increment(self, n=1): with self.val.get_lock(): self.val.value += n @property def value(self): return self.val.value ```
How to conduct buffer overflow in PHP/Python?
2,081,281
5
2010-01-17T14:27:04Z
2,081,520
8
2010-01-17T15:47:54Z
[ "php", "python", "buffer-overflow" ]
Here is an example in c: ``` #include <stdio.h> #include <string.h> void bad() { printf("Oh shit really bad~!\r\n"); } void foo() { char overme[4] = "WOW"; *(int*)(overme+8) = (int)bad; } int main() { foo(); } ```
The fact that Python and PHP are interpreted like suggested by others isn't actually the point. The point is that almost all of the APIs and language semantics that they expose are heavily error-checked making it impossible to have exploitable undefined behavior. Even if you compile the languages, it would still be imp...
Web scraping with Python
2,081,586
164
2010-01-17T16:06:53Z
2,081,606
7
2010-01-17T16:13:38Z
[ "python", "screen-scraping" ]
I'd like to grab daily sunrise/sunset times from a web site. Is it possible to scrape web content with Python? what are the modules used? Is there any tutorial available?
You can use [urllib2](http://docs.python.org/library/urllib2.html) to make the HTTP requests, and then you'll have web content. You can get it like this: ``` import urllib2 response = urllib2.urlopen('http://example.com') html = response.read() ``` [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) is a...
Web scraping with Python
2,081,586
164
2010-01-17T16:06:53Z
2,082,025
166
2010-01-17T18:08:41Z
[ "python", "screen-scraping" ]
I'd like to grab daily sunrise/sunset times from a web site. Is it possible to scrape web content with Python? what are the modules used? Is there any tutorial available?
Use urllib2 in combination with the brilliant [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) library: ``` import urllib2 from BeautifulSoup import BeautifulSoup # or if you're using BeautifulSoup4: # from bs4 import BeautifulSoup soup = BeautifulSoup(urllib2.urlopen('http://example.com').read()) for ...
Web scraping with Python
2,081,586
164
2010-01-17T16:06:53Z
8,600,787
16
2011-12-22T07:46:36Z
[ "python", "screen-scraping" ]
I'd like to grab daily sunrise/sunset times from a web site. Is it possible to scrape web content with Python? what are the modules used? Is there any tutorial available?
I collected together scripts from my web scraping work into [this library](http://code.google.com/p/webscraping). Example script for your case: ``` from webscraping import download, xpath D = download.Download() html = D.get('http://example.com') for row in xpath.search(html, '//table[@class="spad"]/tbody/tr'): ...
Web scraping with Python
2,081,586
164
2010-01-17T16:06:53Z
8,603,040
55
2011-12-22T11:12:48Z
[ "python", "screen-scraping" ]
I'd like to grab daily sunrise/sunset times from a web site. Is it possible to scrape web content with Python? what are the modules used? Is there any tutorial available?
I'd really recommend Scrapy, for reasons being elaborated in [this question - "Is it worth learning Scrapy?"](http://stackoverflow.com/questions/6283271/is-it-worth-learning-scrapy). Quote from the answer: > * Scrapy crawling is fastest than mechanize because uses asynchronous operations (on top of Twisted). > * Scra...
Web scraping with Python
2,081,586
164
2010-01-17T16:06:53Z
16,661,996
10
2013-05-21T04:09:58Z
[ "python", "screen-scraping" ]
I'd like to grab daily sunrise/sunset times from a web site. Is it possible to scrape web content with Python? what are the modules used? Is there any tutorial available?
I would strongly suggest checking out [pyquery](https://pypi.python.org/pypi/pyquery). It uses jquery-like (aka css-like) syntax which makes things really easy for those coming from that background. For your case, it would be something like: ``` from pyquery import * html = PyQuery(url='http://www.example.com/') trs...
What exactly do "u" and "r" string flags do in Python, and what are raw string literals?
2,081,640
240
2010-01-17T16:22:57Z
2,081,652
14
2010-01-17T16:25:51Z
[ "python", "unicode", "rawstring" ]
While asking [this question](http://stackoverflow.com/questions/2081622/python-raw-strings-and-unicode-how-to-use-web-for-input-as-regexp-patterns), I realized I didn't know much about raw strings. For somebody claiming to be a Django trainer, this sucks. I know what an encoding is, and I know what `u` alone does sinc...
A "u" prefix denotes the value has type `unicode` rather than `str`. Raw string literals, with an "r" prefix, escape any escape sequences within them, so `len(r"\n")` is 2. Because they escape escape sequences, you cannot end a string literal with a single backslash: that's not a valid escape sequence (e.g. `r"\"`). ...
What exactly do "u" and "r" string flags do in Python, and what are raw string literals?
2,081,640
240
2010-01-17T16:22:57Z
2,081,655
72
2010-01-17T16:26:17Z
[ "python", "unicode", "rawstring" ]
While asking [this question](http://stackoverflow.com/questions/2081622/python-raw-strings-and-unicode-how-to-use-web-for-input-as-regexp-patterns), I realized I didn't know much about raw strings. For somebody claiming to be a Django trainer, this sucks. I know what an encoding is, and I know what `u` alone does sinc...
There are two types of string in python: the traditional `str` type and the newer `unicode` type. If you type a string literal without the `u` in front you get the old `str` type which stores 8-bit characters, and with the `u` in front you get the newer `unicode` type that can store any Unicode character. The `r` does...
What exactly do "u" and "r" string flags do in Python, and what are raw string literals?
2,081,640
240
2010-01-17T16:22:57Z
2,081,708
271
2010-01-17T16:38:39Z
[ "python", "unicode", "rawstring" ]
While asking [this question](http://stackoverflow.com/questions/2081622/python-raw-strings-and-unicode-how-to-use-web-for-input-as-regexp-patterns), I realized I didn't know much about raw strings. For somebody claiming to be a Django trainer, this sucks. I know what an encoding is, and I know what `u` alone does sinc...
There's not really any "raw *string*"; there are raw *string literals*, which are exactly the string literals marked by a `'r'` before the opening quote. A "raw string literal" is a slightly different syntax for a string literal, in which a backslash, `\`, is taken as meaning "just a backslash" (except when it comes r...
What exactly do "u" and "r" string flags do in Python, and what are raw string literals?
2,081,640
240
2010-01-17T16:22:57Z
9,576,583
19
2012-03-06T01:21:38Z
[ "python", "unicode", "rawstring" ]
While asking [this question](http://stackoverflow.com/questions/2081622/python-raw-strings-and-unicode-how-to-use-web-for-input-as-regexp-patterns), I realized I didn't know much about raw strings. For somebody claiming to be a Django trainer, this sucks. I know what an encoding is, and I know what `u` alone does sinc...
'raw string' means it is stored as it appears. for example, '\' is just a backslash instead of an escaping.
Approaching refactoring
2,081,745
7
2010-01-17T16:50:51Z
2,081,774
7
2010-01-17T16:58:56Z
[ "python", "unit-testing", "qt", "refactoring", "separation-of-concerns" ]
I have a very data-centric application, written in Python / PyQt. I'm planning to do some refactoring to really separate the UI from the core, mainly because there aren't any real tests in place yet, and that clearly has to change. There is some separation already, and I think I've done quite a few things the right wa...
If you have not done so already, read "Working Effectively with Legacy Code" by Michael Feathers - it deals with exactly this sort of situation, and offers a wealth of techniques for dealing with it. One key point he makes is to try and get some tests in place before refactoring. Since it is not suitable for unit test...
Python list : How to sort by timestamp? ( App Engine related )
2,081,754
2
2010-01-17T16:53:54Z
2,081,760
10
2010-01-17T16:55:49Z
[ "python", "google-app-engine" ]
I have ten entities in my Feed model ( this is an App Engine model) ``` class Feed(db.Model): sometext = db.StringProperty() timestamp = db.DateTimeProperty(auto_now=True) list_of_keys = ["key1","key2","key3".... "key10"] ``` so i call my entities using db.key() method: ``` feeds = db.keys(list_of_keys) # this ...
``` import operator ... for feed in sorted(feeds, key=operator.attrgetter('timestamp'), reverse=True): print humanizeTimeDiff(feed.timestamp) ```
Reading specific lines only (Python)
2,081,836
85
2010-01-17T17:14:11Z
2,081,861
70
2010-01-17T17:18:47Z
[ "python", "file", "line" ]
I'm using a for loop to read a file, but I only want to read specific lines, say line #26 and #30. Is there any built-in feature to achieve this? Thanks
The quick answer: ``` f=open('filename') lines=f.readlines() print lines[25] print lines[29] ``` or: ``` lines=[25, 29] i=0 f=open('filename') for line in f: if i in lines: print i i+=1 ``` There is a more elegant solution for extracting many lines: [linecache](http://docs.python.org/library/linecac...
Reading specific lines only (Python)
2,081,836
85
2010-01-17T17:14:11Z
2,081,880
111
2010-01-17T17:23:01Z
[ "python", "file", "line" ]
I'm using a for loop to read a file, but I only want to read specific lines, say line #26 and #30. Is there any built-in feature to achieve this? Thanks
If the file to read is big, and you don't want to read the whole file in memory at once: ``` fp = open("file") for i, line in enumerate(fp): if i == 25: # 26th line elif i == 29: # 30th line elif i > 29: break fp.close() ``` Note that `i == n-1` for the `n`th line. --- In Python ...
Reading specific lines only (Python)
2,081,836
85
2010-01-17T17:14:11Z
2,082,131
18
2010-01-17T18:42:19Z
[ "python", "file", "line" ]
I'm using a for loop to read a file, but I only want to read specific lines, say line #26 and #30. Is there any built-in feature to achieve this? Thanks
A fast and compact approach could be: ``` def picklines(thefile, whatlines): return [x for i, x in enumerate(thefile) if i in whatlines] ``` this accepts any open file-like object `thefile` (leaving up to the caller whether it should be opened from a disk file, or via e.g a socket, or other file-like stream) and a ...
Reading specific lines only (Python)
2,081,836
85
2010-01-17T17:14:11Z
3,990,042
10
2010-10-21T17:07:39Z
[ "python", "file", "line" ]
I'm using a for loop to read a file, but I only want to read specific lines, say line #26 and #30. Is there any built-in feature to achieve this? Thanks
if you want line 7 ``` line = open("file.txt", "r").readlines()[7] ```
Reading specific lines only (Python)
2,081,836
85
2010-01-17T17:14:11Z
16,432,254
12
2013-05-08T03:38:48Z
[ "python", "file", "line" ]
I'm using a for loop to read a file, but I only want to read specific lines, say line #26 and #30. Is there any built-in feature to achieve this? Thanks
For the sake of offering another solution: ``` import linecache linecache.getline('Sample.txt', Number_of_Line) ``` I hope this is quick and easy :)
Simplest way to integrate python gui app with c console app
2,082,028
3
2010-01-17T18:09:12Z
2,082,040
10
2010-01-17T18:13:08Z
[ "python", "c", "user-interface", "integrate" ]
I have a c console app which converts a c file to a html file, the c file location is passed to the program as a command line argument.(the app is for the windows platform) What I would like to do is have a python gui app to allow the user to select a file and pass the location of the file to the c app for processing....
You probably want the [subprocess](http://docs.python.org/library/subprocess.html) module. At the very minimum: ``` import subprocess retcode = subprocess.call(["/path/to/myCprogram", "/path/to/file.c"]) if retcode == 0: print "success!" ``` This will run the program with the arguments, and then return its return...
Case insensitive dictionary
2,082,152
37
2010-01-17T18:48:20Z
2,082,169
29
2010-01-17T18:50:55Z
[ "python" ]
I'd like my dictionary to be case insensitive. I have this example code: ``` text = "practice changing the color" words = {'color': 'colour', 'practice': 'practise'} def replace(words,text): keys = words.keys() for i in keys: text= text.replace(i ,words[i]) return text text = replace...
If I understand you correctly and you want a way to key dictionaries in a non case-sensitive fashion, one way would be to subclass dict and overload the setter / getter: ``` class CaseInsensitiveDict(dict): def __setitem__(self, key, value): super(CaseInsensitiveDict, self).__setitem__(key.lower(), value) ...
Case insensitive dictionary
2,082,152
37
2010-01-17T18:48:20Z
16,817,943
21
2013-05-29T15:24:45Z
[ "python" ]
I'd like my dictionary to be case insensitive. I have this example code: ``` text = "practice changing the color" words = {'color': 'colour', 'practice': 'practise'} def replace(words,text): keys = words.keys() for i in keys: text= text.replace(i ,words[i]) return text text = replace...
Just for the record. I found an awesome impementation on [Requests](http://docs.python-requests.org/): <https://github.com/kennethreitz/requests/blob/v1.2.3/requests/structures.py#L37>
Case insensitive dictionary
2,082,152
37
2010-01-17T18:48:20Z
32,888,599
16
2015-10-01T13:16:54Z
[ "python" ]
I'd like my dictionary to be case insensitive. I have this example code: ``` text = "practice changing the color" words = {'color': 'colour', 'practice': 'practise'} def replace(words,text): keys = words.keys() for i in keys: text= text.replace(i ,words[i]) return text text = replace...
The [currently approved answer](http://stackoverflow.com/a/2082169/277172) doesn't work for **a lot** of cases, so it cannot be used as a drop-in `dict` replacement. Some tricky points in getting a proper `dict` replacement: * overloading all of the methods that involve keys * properly handling non-string keys * prope...
How to export C# methods?
2,082,159
15
2010-01-17T18:49:24Z
2,082,202
22
2010-01-17T19:01:36Z
[ "c#", "python", "methods", "export", "python.net" ]
How can we export C# methods? I have a dll and I want to use its methods in the Python language with the ctypes module. Because I need to use the ctypes module, I need to export the C# methods for them to be visible in Python. So, how can I export the C# methods (like they do in C++)?
Contrary to popular belief, this *is* possible. See [here](http://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports).
Reading input from raw_input() without having the prompt overwritten by other threads in Python
2,082,387
10
2010-01-17T19:55:47Z
4,653,306
21
2011-01-11T01:22:25Z
[ "python", "multithreading", "raw-input" ]
I'm trying to let the user input commands at a console using raw\_input(), this works fine. The problem is I have background threads that occasionally output log-information to the screen and when they do they mess up the input prompt (since the output go wherever the cursor happens to be at the moment). This is a sma...
I recently encountered this problem, and would like to leave this solution here for future reference. These solutions clear the pending raw\_input (readline) text from the terminal, print the new text, then reprint to the terminal what was in the raw\_input buffer. This first program is pretty simple, but only works c...
real time subprocess.Popen via stdout and PIPE
2,082,850
14
2010-01-17T22:03:03Z
2,083,432
9
2010-01-18T01:30:31Z
[ "python", "logging", "subprocess", "pipe", "popen" ]
I am trying to grab stdout from a subprocess,Popen call and although I am achieving this easily by doing: ``` cmd = subprocess.Popen('ls -l', shell=True, stdout=PIPE) for line in cmd.stdout.readlines(): print line ``` I would like to grab stdout in "real time". With the above method, PIPE is waiting to grab all t...
To get output "in real time", `subprocess` is unsuitable because it can't defeat the other process's buffering strategies. That's the reason I always recommend, whenever such "real time" output grabbing is desired (quite a frequent question on stack overflow!), to use instead [pexpect](http://www.noah.org/wiki/Pexpect)...
real time subprocess.Popen via stdout and PIPE
2,082,850
14
2010-01-17T22:03:03Z
2,345,019
17
2010-02-26T21:41:31Z
[ "python", "logging", "subprocess", "pipe", "popen" ]
I am trying to grab stdout from a subprocess,Popen call and although I am achieving this easily by doing: ``` cmd = subprocess.Popen('ls -l', shell=True, stdout=PIPE) for line in cmd.stdout.readlines(): print line ``` I would like to grab stdout in "real time". With the above method, PIPE is waiting to grab all t...
Your interpreter is buffering. Add a call to sys.stdout.flush() after your print statement.
Cannot change global variables in a function through an exec() statement?
2,083,353
11
2010-01-18T01:05:37Z
2,083,374
18
2010-01-18T01:12:36Z
[ "python", "exec", "global" ]
Why can I not change global variables from inside a function, using exec()? It works fine when the assignment statement is outside of exec(). Here is an example of my problem: ``` >>> myvar = 'test' >>> def myfunc(): ... global myvar ... exec('myvar = "changed!"') ... print(myvar) ... >>> myfunc() test >>...
Per [the docs](http://docs.python.org/reference/simple_stmts.html#the-exec-statement), the `exec` statement takes two optional expressions, defaulting to `globals()` and `locals()`, and always performs changes (if any) in the `locals()` one. So, just be more explicit/specific/precise...: ``` >>> def myfunc(): ... e...
Is there any difference between UserDict and Dict?
2,083,504
3
2010-01-18T01:56:43Z
2,083,524
8
2010-01-18T02:04:11Z
[ "python" ]
If I want a class to have a dictionary behavior, why should I inherit from `dict` or `UserDict`?
You can inherit from `dict` in any Python that's version 2.2 or better, but you'll have to override every single method of interest -- for example, your override of `__getitem__` will **not** be used by `get` unless you also override that one, and so on, and so forth. The `UserDict.DictMixin` mix-in goes back a lot fu...
How to retry after exception in python?
2,083,987
85
2010-01-18T05:00:19Z
2,083,996
145
2010-01-18T05:02:20Z
[ "python" ]
I have a loop starting with `for i in range(0, 100)`. Normally it runs correctly, but sometimes it fails due to network conditions. Currently I have it set so that on failure, it will `continue` in the except clause (continue on to the next number for `i`). Is it possible for me to reassign the same number to `i` and ...
Do a `while True` inside your for loop, put your `try` code inside, and break from that `while` loop only when your code succeeds. ``` for i in range(0,100): while True: try: # do stuff except SomeSpecificException: continue break ```
How to retry after exception in python?
2,083,987
85
2010-01-18T05:00:19Z
7,663,441
63
2011-10-05T15:03:37Z
[ "python" ]
I have a loop starting with `for i in range(0, 100)`. Normally it runs correctly, but sometimes it fails due to network conditions. Currently I have it set so that on failure, it will `continue` in the except clause (continue on to the next number for `i`). Is it possible for me to reassign the same number to `i` and ...
I prefer to limit the number of retries, so that if there's a problem with that specific item you will eventually continue onto the next one, thus: ``` for i in range(100): for attempt in range(10): try: # do thing except: # perhaps reconnect, etc. else: break else: # we failed al...
How to retry after exception in python?
2,083,987
85
2010-01-18T05:00:19Z
25,912,659
25
2014-09-18T12:29:43Z
[ "python" ]
I have a loop starting with `for i in range(0, 100)`. Normally it runs correctly, but sometimes it fails due to network conditions. Currently I have it set so that on failure, it will `continue` in the except clause (continue on to the next number for `i`). Is it possible for me to reassign the same number to `i` and ...
The [retrying package](https://pypi.python.org/pypi/retrying) is a nice way to retry a block of code on failure. For example: ``` @retry(wait_random_min=1000, wait_random_max=2000) def wait_random_1_to_2_s(): print "Randomly wait 1 to 2 seconds between retries" ```
Create a .csv file with values from a Python list
2,084,069
64
2010-01-18T05:34:08Z
2,084,135
87
2010-01-18T05:53:25Z
[ "python", "csv", "xlrd" ]
I am trying to create a .csv file with the values from a Python list. When I print the values in the list they are all unicode (?), i.e. they look something like this ``` [u'value 1', u'value 2', ...] ``` If I iterate through the values in the list i.e. `for v in mylist: print v` they appear to be plain text. And I ...
``` import csv myfile = open(..., 'wb') wr = csv.writer(myfile, quoting=csv.QUOTE_ALL) wr.writerow(mylist) ```
Create a .csv file with values from a Python list
2,084,069
64
2010-01-18T05:34:08Z
2,084,136
10
2010-01-18T05:53:30Z
[ "python", "csv", "xlrd" ]
I am trying to create a .csv file with the values from a Python list. When I print the values in the list they are all unicode (?), i.e. they look something like this ``` [u'value 1', u'value 2', ...] ``` If I iterate through the values in the list i.e. `for v in mylist: print v` they appear to be plain text. And I ...
Use python's `csv` module for reading and writing comma or tab-delimited files. The csv module is preferred because it gives you good control over quoting. For example, here is the worked example for you: ``` import csv data = ["value %d" % i for i in range(1,4)] out = csv.writer(open("myfile.csv","w"), delimiter=',...
Create a .csv file with values from a Python list
2,084,069
64
2010-01-18T05:34:08Z
21,872,153
40
2014-02-19T05:48:28Z
[ "python", "csv", "xlrd" ]
I am trying to create a .csv file with the values from a Python list. When I print the values in the list they are all unicode (?), i.e. they look something like this ``` [u'value 1', u'value 2', ...] ``` If I iterate through the values in the list i.e. `for v in mylist: print v` they appear to be plain text. And I ...
Here is a secure version of Alex Martelli's: ``` import csv with open('filename', 'wb') as myfile: wr = csv.writer(myfile, quoting=csv.QUOTE_ALL) wr.writerow(mylist) ```
md5 module error
2,084,407
5
2010-01-18T07:13:23Z
2,084,423
7
2010-01-18T07:17:22Z
[ "python", "module", "md5", "ply" ]
I'm using an older version of PLY that uses the md5 module (among others): ``` import re, types, sys, cStringIO, md5, os.path ``` ... although the script runs but not without this error: ``` DeprecationWarning: the md5 module is deprecated; use hashlib instead ``` How do I fix it so the error goes away? Thanks
i think the warning message is quite straightforward. you need to ``` from hashlib import md5 ``` or you can use python < 2.5, <http://docs.python.org/library/md5.html>
clear terminal in python
2,084,508
91
2010-01-18T07:34:58Z
2,084,521
47
2010-01-18T07:38:09Z
[ "python" ]
Does any standard "comes with batteries" method exist to clear the terminal screen from a python script, or do I have to go curses (the libraries, not the words) ?
What about escape sequences? ``` print(chr(27) + "[2J") ```
clear terminal in python
2,084,508
91
2010-01-18T07:34:58Z
2,084,560
22
2010-01-18T07:50:16Z
[ "python" ]
Does any standard "comes with batteries" method exist to clear the terminal screen from a python script, or do I have to go curses (the libraries, not the words) ?
If you are on a Linux/UNIX system then printing the ANSI escape sequence to clear the screen should do the job. You will also want to move cursor to the top of the screen. This will work on any terminal that supports ANSI. ``` import sys sys.stderr.write("\x1b[2J\x1b[H") ``` This will not work on Windows unless ANSI ...
clear terminal in python
2,084,508
91
2010-01-18T07:34:58Z
2,084,628
160
2010-01-18T08:09:07Z
[ "python" ]
Does any standard "comes with batteries" method exist to clear the terminal screen from a python script, or do I have to go curses (the libraries, not the words) ?
A simple and cross-platform solution would be to use either the `cls` command on Windows, or `clear` on Unix systems. Used with [`os.system`](http://docs.python.org/3/library/os.html#os.system), this makes a nice one-liner: ``` import os os.system('cls' if os.name == 'nt' else 'clear') ```
clear terminal in python
2,084,508
91
2010-01-18T07:34:58Z
23,075,152
10
2014-04-15T05:14:02Z
[ "python" ]
Does any standard "comes with batteries" method exist to clear the terminal screen from a python script, or do I have to go curses (the libraries, not the words) ?
As a wise person once posted, for at least Linux, you can do the Python equivalent of this, which you can use on the command-line. It will clear the screen more than the Linux `clear` command (such that you can't scroll up to see your text): ``` printf "\033c" ``` For Windows you can just use `cls`. Here's a Python ...
clear terminal in python
2,084,508
91
2010-01-18T07:34:58Z
26,639,250
20
2014-10-29T19:44:33Z
[ "python" ]
Does any standard "comes with batteries" method exist to clear the terminal screen from a python script, or do I have to go curses (the libraries, not the words) ?
Why hasn't anyone talked about just simply doing `Ctrl`+`L`. Surely the simplest way of clearing screen.
How to extract links from a webpage using lxml, XPath and Python?
2,084,670
5
2010-01-18T08:22:26Z
2,084,852
8
2010-01-18T09:03:58Z
[ "python", "screen-scraping", "hyperlink", "lxml", "extraction" ]
I've got this xpath query: ``` /html/body//tbody/tr[*]/td[*]/a[@title]/@href ``` It extracts all the links with the title attribute - and gives the `href` in [FireFox's Xpath checker add-on](https://addons.mozilla.org/en-US/firefox/addon/1095). However, I cannot seem to use it with `lxml`. ``` from lxml import etre...
I was able to make it work with the following code: ``` from lxml import html, etree from StringIO import StringIO html_string = '''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"> <head/> <body> <table border="1"> <tbody> <t...
timeout for urllib2.urlopen() in pre Python 2.6 versions
2,084,782
28
2010-01-18T08:49:58Z
2,086,596
57
2010-01-18T14:19:07Z
[ "python", "urllib2", "urlopen" ]
The [urllib2 documentation](http://docs.python.org/library/urllib2.html) says that *timeout* parameter was added in Python 2.6. Unfortunately my code base has been running on Python 2.5 and 2.4 platforms. Is there any alternate way to simulate the timeout? All I want to do is allow the code to talk the remote server f...
you can set a global timeout for all socket operations (including HTTP requests) by using: [`socket.setdefaulttimeout()`](http://docs.python.org/library/socket.html#socket.setdefaulttimeout) like this: ``` import urllib2 import socket socket.setdefaulttimeout(30) f = urllib2.urlopen('http://www.python.org/') ``` in...
How can I create 1000 files that I can use to test a script?
2,084,832
8
2010-01-18T09:00:37Z
2,084,946
7
2010-01-18T09:20:05Z
[ "python", "perl", "shell", "scripting" ]
I would like to create 1000+ text files with some text to test a script, how to create this much if text files at a go using shell script or Perl. Please could anyone help me.
``` for i in {0001..1000} do echo "some text" > "file_${i}.txt" done ``` or if you want to use Python <2.6 ``` for x in range(1000): open("file%03d.txt" % x,"w").write("some text") ```
Vim's Omnicompletion with Python just doesn't work
2,084,875
46
2010-01-18T09:08:03Z
2,086,309
11
2010-01-18T13:35:29Z
[ "python", "vim", "autocomplete", "omnicomplete" ]
I've searched around for an hour, both on Stack Overflow and elsewhere. Alas! Please help. Vim's omnicompletion just *doesn't work*. 1. I have Vim 7.2 compiled with Python support. 2. `filetype plugin on` is in my `.vimrc`. 3. When a `.py` file is open, `:echo &omnifunc` prints `pythoncomplete#Complete`. 4. I'm workin...
What module contains the symbol you are trying to complete? Is it in the python stdlib? Or is it a third-party module? Make sure that the module/package is in the PYTHONPATH. In Vim, do: ``` :python import sys :python print sys.path ``` To add the module's directory: ``` :python sys.path.append("/path/to/directory...
Vim's Omnicompletion with Python just doesn't work
2,084,875
46
2010-01-18T09:08:03Z
2,245,120
8
2010-02-11T14:38:15Z
[ "python", "vim", "autocomplete", "omnicomplete" ]
I've searched around for an hour, both on Stack Overflow and elsewhere. Alas! Please help. Vim's omnicompletion just *doesn't work*. 1. I have Vim 7.2 compiled with Python support. 2. `filetype plugin on` is in my `.vimrc`. 3. When a `.py` file is open, `:echo &omnifunc` prints `pythoncomplete#Complete`. 4. I'm workin...
Since you were prudent and made certain your code is reachable by the PYTHONPATH, per codeape's suggestion, is there a possibility that you are running into the [`import` bug for Vim Python omni-complete](http://groups.google.com/group/vim_dev/browse_thread/thread/58191d176ebd9722/d9cd31cee304b7df?pli=1)? This bug stil...
Vim's Omnicompletion with Python just doesn't work
2,084,875
46
2010-01-18T09:08:03Z
6,895,757
9
2011-08-01T08:15:04Z
[ "python", "vim", "autocomplete", "omnicomplete" ]
I've searched around for an hour, both on Stack Overflow and elsewhere. Alas! Please help. Vim's omnicompletion just *doesn't work*. 1. I have Vim 7.2 compiled with Python support. 2. `filetype plugin on` is in my `.vimrc`. 3. When a `.py` file is open, `:echo &omnifunc` prints `pythoncomplete#Complete`. 4. I'm workin...
Sounds like the questioner has long since gone to the dark side\*, but for what it's worth I've just had this symptom, and in my case the cause was that a module I was using relied on Python 2.7 but my version of Vim was compiled with Python 2.5. To diagnose I tried `:python import mymodule`, which failed with an erro...
Error Handling in Python with SUDS
2,085,128
11
2010-01-18T09:56:21Z
2,085,187
9
2010-01-18T10:06:00Z
[ "python", "web-services", "suds" ]
I have been trying to control a camera through a wsdl file using SUDS. I have got the code working but I want to place error handling into the script. I have tried different exceptions but am unable to get the script working. When I enter an invalid coordinate I get an error. The code I am using is below followed by th...
If you want to catch that exception you should put ``` try: result = client.service.AbsoluteMove(token, dest, speed) except suds.WebFault as detail: ... ```
Error Handling in Python with SUDS
2,085,128
11
2010-01-18T09:56:21Z
7,712,443
14
2011-10-10T12:02:31Z
[ "python", "web-services", "suds" ]
I have been trying to control a camera through a wsdl file using SUDS. I have got the code working but I want to place error handling into the script. I have tried different exceptions but am unable to get the script working. When I enter an invalid coordinate I get an error. The code I am using is below followed by th...
If you handled all exceptions and errors in your code and your code is working fine but still you are getting below message with your correct output. Msg : "No handlers could be found for logger `suds.client` " Then a simple solution is to add this line ``` logging.getLogger('suds.client').setLevel(logging.CRITICAL)...
populating data from xml file to a sqlite database using python
2,085,430
5
2010-01-18T10:55:11Z
2,088,934
7
2010-01-18T20:22:27Z
[ "python", "xml", "database", "sqlite", "parsing" ]
I have a question related to some guidances to solve a problem. I have with me an xml file, I have to populate it into a database system (whatever, it might be sqlite, mysql) using scripting language: Python. Does anyone have any idea on how to proceed? * Which technologies I need to read further? * Which environment...
I recommend you study on [ElementTree](http://effbot.org/zone/element-index.htm) for parsing your XML file into memory (parse it all, then emit it all to a SQL DB, is probably easier, but element-tree also allows incremental operation if your file is huge) -- it's part of the standard Python library as module [xml.etre...
Querying a view in SQLAlchemy
2,085,592
3
2010-01-18T11:24:54Z
2,098,162
7
2010-01-20T00:06:36Z
[ "python", "postgresql", "sqlalchemy" ]
I want to know if SQLAlchemy has problems querying a view. If I query the view with normal SQL on the server like: ``` SELECT * FROM ViewMyTable WHERE index1 = '608_56_56'; ``` I get a whole bunch of records. But with SQLAlchemy I get only the first one. But in the count is the correct number. I have no idea why. Th...
if you've mapped `ViewMyTable`, the query will only return rows that have a fully non-NULL primary key. This behavior is specific to versions 0.5 and lower - on 0.6, if any of the columns have a non-NULL in the primary key, the row is turned into an instance. Specify the flag `allow_null_pks=True` to your mappers to en...
specifying a list as a command line argument in python
2,086,556
14
2010-01-18T14:13:45Z
2,086,615
19
2010-01-18T14:22:58Z
[ "python" ]
I am using getopt to process a command line optional argument, which should accept a list. Something like this: ``` foo.py --my_list=[1, 2, 3, 4,5] ``` But this trims everything after "[1," My questions are: A) Is there a way to specify a list without converting it into a string? (using getopt) B) If I am to conver...
There are two options that I can think of: * Use [optparse](http://docs.python.org/library/optparse.html), and use [`append`](http://docs.python.org/library/optparse.html#other-actions) action to specify what you want to do as: `foo.py --my_list=1 --my_list=2 ...`. * Specify your commandline as `foo.py --my_list='1,2,...
specifying a list as a command line argument in python
2,086,556
14
2010-01-18T14:13:45Z
21,163,749
7
2014-01-16T13:55:58Z
[ "python" ]
I am using getopt to process a command line optional argument, which should accept a list. Something like this: ``` foo.py --my_list=[1, 2, 3, 4,5] ``` But this trims everything after "[1," My questions are: A) Is there a way to specify a list without converting it into a string? (using getopt) B) If I am to conver...
If I can't use a standard parser (optparse or argparse) to my application then I use the ast.literal\_eval function to parse input arguments of type list as follows: ``` import sys, ast inputList = ast.literal_eval( sys.argv[1] ) print type( inputList ) print inputList ``` Let suppose that this code is stored in tes...
How can I determine if a python script is executed from crontab?
2,086,961
4
2010-01-18T15:17:06Z
2,086,972
7
2010-01-18T15:17:56Z
[ "python", "unix", "terminal", "cron" ]
I would like to know how can I determine if a python script is executed from crontab? I don't want a solution that will require adding a parameter because I want to be able to detect this even from an imported module (not the main script).
Check its PPID - the ID of its parent process. Compare that to the cron pid; If they are the same, it was invoked by the crontab. This can be done by: ``` $ sudo ps -Af | grep cron | grep -v grep root 6363 1 0 10:17 ? 00:00:00 /usr/sbin/cron ``` The PID of the cron process in this example is 6363. It is worth me...
How can I determine if a python script is executed from crontab?
2,086,961
4
2010-01-18T15:17:06Z
2,087,031
18
2010-01-18T15:26:29Z
[ "python", "unix", "terminal", "cron" ]
I would like to know how can I determine if a python script is executed from crontab? I don't want a solution that will require adding a parameter because I want to be able to detect this even from an imported module (not the main script).
Not quite what you asked, but maybe what you want is `os.isatty(sys.stdout.fileno())`, which tells if `stdout` is connected to (roughly speaking) a terminal. It will be false if you pipe the output to a file or another process, or if the process is run from cron.
Can I use `pip` instead of `easy_install` for `python setup.py install` dependency resolution?
2,087,148
74
2010-01-18T15:40:17Z
2,090,124
74
2010-01-19T00:05:39Z
[ "python", "easy-install", "pip" ]
`python setup.py install` will automatically install packages listed in `requires=[]` using `easy_install`. How do I get it to use `pip` instead?
You can `pip install` a file perhaps by `python setup.py sdist` first. You can also `pip install -e .` which is like `python setup.py develop`.
Can I use `pip` instead of `easy_install` for `python setup.py install` dependency resolution?
2,087,148
74
2010-01-18T15:40:17Z
24,000,174
50
2014-06-02T17:33:47Z
[ "python", "easy-install", "pip" ]
`python setup.py install` will automatically install packages listed in `requires=[]` using `easy_install`. How do I get it to use `pip` instead?
Yes you can. You can install a package from a tarball or a folder, on the web or your computer. For example: ### Install from tarball on web ``` pip install https://pypi.python.org/packages/source/r/requests/requests-2.3.0.tar.gz ``` ### Install from local tarball ``` wget https://pypi.python.org/packages/source/r/...
Commit in git only if tests pass
2,087,216
32
2010-01-18T15:47:51Z
2,088,074
26
2010-01-18T17:54:41Z
[ "python", "unit-testing", "git", "githooks" ]
I've recently started using git, and also begun unit testing (using Python's `unittest` module). I'd like to run my tests each time I commit, and only commit if they pass. I'm guessing I need to use `pre-commit` in `/hooks`, and I've managed to make it run the tests, but I can't seem to find a way to stop the commit i...
I would check to make sure that each step of the way, your script returns a non-zero exit code on failure. Check to see if your `python3.1 foo.py --test` returns a non-zero exit code if a test fails. Check to make sure your `make test` command returns a non-zero exit code. And finally, check that your `pre-commit` hook...
Decode HTML entities in Python string?
2,087,370
128
2010-01-18T16:08:52Z
2,087,433
252
2010-01-18T16:17:50Z
[ "python", "html", "html-entities" ]
I'm parsing some HTML with Beautiful Soup 3, but it contains HTML entities which Beautiful Soup 3 doesn't automatically decode for me: ``` >>> from BeautifulSoup import BeautifulSoup >>> soup = BeautifulSoup("<p>&pound;682m</p>") >>> text = soup.find("p").string >>> print text &pound;682m ``` How can I decode the H...
### Python 3.4+ `HTMLParser.unescape` is deprecated, and [was supposed to be removed in 3.5](https://github.com/python/cpython/blob/3.5/Lib/html/parser.py#L466-L470), although it was left in by mistake. It will be removed from the language soon. Instead, use `html.unescape()`: ``` import html print(html.unescape('&po...
Decode HTML entities in Python string?
2,087,370
128
2010-01-18T16:08:52Z
2,087,446
53
2010-01-18T16:19:14Z
[ "python", "html", "html-entities" ]
I'm parsing some HTML with Beautiful Soup 3, but it contains HTML entities which Beautiful Soup 3 doesn't automatically decode for me: ``` >>> from BeautifulSoup import BeautifulSoup >>> soup = BeautifulSoup("<p>&pound;682m</p>") >>> text = soup.find("p").string >>> print text &pound;682m ``` How can I decode the H...
Beautiful Soup handles entity conversion. In Beautiful Soup 3, you'll need to specify the `convertEntities` argument to the `BeautifulSoup` constructor (see the ['Entity Conversion'](http://www.crummy.com/software/BeautifulSoup/bs3/documentation.html#Entity%20Conversion) section of the archived docs). In Beautiful Soup...
Can a Python package depend on a specific version control revision of another Python package?
2,087,492
9
2010-01-18T16:25:37Z
2,163,919
12
2010-01-29T17:47:02Z
[ "python", "setuptools", "distutils", "easy-install", "pip" ]
Some useful Python packages are broken on pypi, and the only acceptable version is a particular revision in a revision control system. Can that be expressed in `setup.py` e.g `requires = 'svn://example.org/useful.package/trunk@1234'` ?
You need to do two things. First, require the exact version you want, e.g.: ``` install_requires = "useful.package==1.9dev-r1234" ``` and then include a `dependency_links` setting specifying where to find it: ``` dependency_links = ["svn://example.org/useful.package/trunk@1234#egg=useful.package-1.9dev-r1234"] ``` ...
Get kwargs Inside Function
2,088,056
11
2010-01-18T17:52:23Z
2,088,101
13
2010-01-18T18:00:04Z
[ "python", "introspection", "kwargs" ]
If I have a python function like so: ``` def some_func(arg1, arg2, arg3=1, arg4=2): ``` Is there a way to determine which arguments were passed by keyword from inside the function? **EDIT** For those asking why I need this, I have no real reason, it came up in a conversation and curiosity got the better of me.
No, there is no way to do it in Python code with this signature -- if you need this information, you need to change the function's signature. If you look at the Python C API, you'll see that the actual way arguments are passed to a normal Python function is always as a tuple plus a dict -- i.e., the way that's a direc...
Get kwargs Inside Function
2,088,056
11
2010-01-18T17:52:23Z
2,088,136
8
2010-01-18T18:05:59Z
[ "python", "introspection", "kwargs" ]
If I have a python function like so: ``` def some_func(arg1, arg2, arg3=1, arg4=2): ``` Is there a way to determine which arguments were passed by keyword from inside the function? **EDIT** For those asking why I need this, I have no real reason, it came up in a conversation and curiosity got the better of me.
Here's my solution via decorators: ``` def showargs(function): def inner(*args, **kwargs): return function((args, kwargs), *args, **kwargs) return inner @showargs def some_func(info, arg1, arg2, arg3=1, arg4=2): print arg1,arg2,arg3,arg4 return info In [226]: some_func(1,2,3, arg4=4) 1 2 3 4 ...
Installing PIL (Python Imaging Library) in Win7 64 bits, Python 2.6.4
2,088,304
61
2010-01-18T18:34:35Z
2,088,575
20
2010-01-18T19:15:22Z
[ "python", "python-imaging-library", "windows-7-x64" ]
I'm trying to install said library for use with Python. I tried downloading the executable installer for Windows, which runs, but says it doesn't find a Python installation. Then tried registering (<http://effbot.org/zone/python-register.htm>) Python, but the script says it can't register (although the keys appear in m...
Compiling PIL on Windows x64 is apparently a bit of a pain. (Well, compiling anything on Windows is a bit of a pain in my experience. But still.) As well as PIL itself you'll need to build many dependencies. See [these notes](http://mail.python.org/pipermail/image-sig/2009-March/005448.html) from the mailing list too. ...
Installing PIL (Python Imaging Library) in Win7 64 bits, Python 2.6.4
2,088,304
61
2010-01-18T18:34:35Z
3,308,907
29
2010-07-22T12:40:30Z
[ "python", "python-imaging-library", "windows-7-x64" ]
I'm trying to install said library for use with Python. I tried downloading the executable installer for Windows, which runs, but says it doesn't find a Python installation. Then tried registering (<http://effbot.org/zone/python-register.htm>) Python, but the script says it can't register (although the keys appear in m...
I've just had the same problem (with Python 2.7 and PIL for this versions, but the solution should work also for 2.6) and the way to solve it is to copy all the registry keys from: ``` HKEY_LOCAL_MACHINE\SOFTWARE\Python ``` to ``` HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python ``` Worked for me solution found at t...
Installing PIL (Python Imaging Library) in Win7 64 bits, Python 2.6.4
2,088,304
61
2010-01-18T18:34:35Z
4,579,917
116
2011-01-02T18:54:51Z
[ "python", "python-imaging-library", "windows-7-x64" ]
I'm trying to install said library for use with Python. I tried downloading the executable installer for Windows, which runs, but says it doesn't find a Python installation. Then tried registering (<http://effbot.org/zone/python-register.htm>) Python, but the script says it can't register (although the keys appear in m...
I found a working win7 binary here: [Unofficial Windows Binaries for Python Extension Packages](http://www.lfd.uci.edu/~gohlke/pythonlibs/) It's from Christoph Gohlke at UC Irvine. There are binaries for python 2.5, 2.6, 2.7 , 3.1 and 3.2 for both 32bit and 64 bit windows. There are a whole lot of other compiled pack...
Integrate stiff ODEs with Python
2,088,473
14
2010-01-18T18:57:33Z
2,104,485
10
2010-01-20T19:58:01Z
[ "python", "scipy", "pygsl" ]
I'm looking for a good library that will integrate stiff ODEs in Python. The issue is, scipy's odeint gives me good solutions *sometimes*, but the slightest change in the initial conditions causes it to fall down and give up. The same problem is solved quite happily by MATLAB's stiff solvers (ode15s and ode23s), but I ...
Python can call C. The industry standard is [LSODE](https://computation.llnl.gov/casc/nsde/pubs/u113855.pdf) in ODEPACK. It is public-domain. You can download the [C version](http://www.koders.com/c/fidC42AC8E93AF65E48DBF9A2548B3D8D8642724CBD.aspx). These solvers are extremely tricky, so it's best to use some well-test...
Integrate stiff ODEs with Python
2,088,473
14
2010-01-18T18:57:33Z
2,243,962
15
2010-02-11T11:01:28Z
[ "python", "scipy", "pygsl" ]
I'm looking for a good library that will integrate stiff ODEs in Python. The issue is, scipy's odeint gives me good solutions *sometimes*, but the slightest change in the initial conditions causes it to fall down and give up. The same problem is solved quite happily by MATLAB's stiff solvers (ode15s and ode23s), but I ...
If you can solve your problem with Matlab's `ode15s`, you should be able to solve it with the `vode` solver of scipy. To simulate `ode15s`, I use the following settings: ``` ode15s = scipy.integrate.ode(f) ode15s.set_integrator('vode', method='bdf', order=15, nsteps=3000) ode15s.set_initial_value(u0, t0) ``` and then...
How do I force Python to be 32-bit on Snow Leopard and other 32-bit/64-bit questions
2,088,569
36
2010-01-18T19:13:50Z
2,088,593
24
2010-01-18T19:18:13Z
[ "python", "osx-snow-leopard", "32bit-64bit" ]
When I run the following from a bash shell on my Mac: ``` $ file /usr/bin/python ``` I get the following three lines: ``` /usr/bin/python (for architecture x86_64): Mach-O 64-bit executable x86_64 /usr/bin/python (for architecture i386): Mach-O executable i386 /usr/bin/python (for architecture ppc7400): Mach-O e...
<http://www.jaharmi.com/2009/08/29/python_32_bit_execution_on_snow_leopard> `$ defaults write com.apple.versioner.python Prefer-32-Bit -bool yes`
How do I force Python to be 32-bit on Snow Leopard and other 32-bit/64-bit questions
2,088,569
36
2010-01-18T19:13:50Z
2,088,618
30
2010-01-18T19:21:54Z
[ "python", "osx-snow-leopard", "32bit-64bit" ]
When I run the following from a bash shell on my Mac: ``` $ file /usr/bin/python ``` I get the following three lines: ``` /usr/bin/python (for architecture x86_64): Mach-O 64-bit executable x86_64 /usr/bin/python (for architecture i386): Mach-O executable i386 /usr/bin/python (for architecture ppc7400): Mach-O e...
1. You can find out a lot about the Python version you're running via the `platform` module (the `sys` module also has a few simple helpers) 2. On Mac OS X, you can run a "fat binary" with your chosen architecture with, for example, arch -i386 /usr/bin/python I do **not** recommend altering /usr/lib/python itself ...
How do I force Python to be 32-bit on Snow Leopard and other 32-bit/64-bit questions
2,088,569
36
2010-01-18T19:13:50Z
3,059,113
19
2010-06-17T05:33:01Z
[ "python", "osx-snow-leopard", "32bit-64bit" ]
When I run the following from a bash shell on my Mac: ``` $ file /usr/bin/python ``` I get the following three lines: ``` /usr/bin/python (for architecture x86_64): Mach-O 64-bit executable x86_64 /usr/bin/python (for architecture i386): Mach-O executable i386 /usr/bin/python (for architecture ppc7400): Mach-O e...
**Fix for use with virtualenv on Snow Leopard** danielrsmith's answer works for me when I am not using virtualenv, but virtualenv makes a copy of the python executable which causes it not to work: ``` $ which python /Users/cogg/.virtualenvs/tweakeats/bin/python $ python [...] >>> import sys >>> sys.maxint 9223372036...
Sorting CSV in Python
2,089,036
5
2010-01-18T20:38:35Z
2,089,080
10
2010-01-18T20:45:16Z
[ "python", "sorting", "csv" ]
I assumed sorting a CSV file on multiple text/numeric fields using Python would be a problem that was already solved. But I can't find any example code anywhere, except for specific code focusing on sorting date fields. How would one go about sorting a relatively large CSV file (tens of thousand lines) on multiple fie...
Python's sort works in-memory only; however, tens of thousands of lines should fit in memory easily on a modern machine. So: ``` import csv def sortcsvbymanyfields(csvfilename, themanyfieldscolumnnumbers): with open(csvfilename, 'rb') as f: readit = csv.reader(f) thedata = list(readit) thedata.sort(key=op...
attribute 'tzinfo' of 'datetime.datetime' objects is not writable
2,089,419
19
2010-01-18T21:41:38Z
2,089,496
32
2010-01-18T21:52:01Z
[ "python", "google-app-engine", "datetime", "tzinfo" ]
How do I set the timezone of a datetime instance that just came out of the datastore? When it first comes out it is in UTC. I want to change it to EST. I'm trying, for example: ``` class Book( db.Model ): creationTime = db.DateTimeProperty() ``` When a Book is retrieved, I want to set its tzinfo immediately: `...
`datetime`'s objects are immutable, so you never change any of their attributes -- you make a **new** object with some attributes the same, and some different, and assign it to whatever you need to assign it to. I.e., in your case, instead of ``` book.creationTime.tzinfo = EST ``` you have to code ``` book.creation...
SQLAlchemy Column to Row Transformation and vice versa -- is it possible?
2,089,661
4
2010-01-18T22:24:05Z
2,093,103
8
2010-01-19T11:35:26Z
[ "python", "orm", "sqlalchemy", "pivot-table", "transformation" ]
I'm looking for a SQLAlchemy only solution for converting a dict received from a form submission into a series of rows in the database, one for each field submitted. This is to handle preferences and settings that vary widely across applications. But, it's very likely applicable to creating pivot table like functionali...
Here is a slightly modified example from [documentation](http://www.sqlalchemy.org/docs/reference/ext/associationproxy.html#building-complex-views) to work with such table structure mapped to dictionary in model: ``` from sqlalchemy import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm.c...
Printing correct time using timezones, Python
2,089,706
9
2010-01-18T22:34:12Z
2,090,122
13
2010-01-19T00:04:56Z
[ "python", "datetime", "tzinfo" ]
[Extends](http://stackoverflow.com/questions/2089419/attribute-tzinfo-of-datetime-datetime-objects-is-not-writable) Ok, we are not having a good day today. When you attach the correct tzinfo object to a datetime instance, and then you strftime() it, it STILL comes out in UTC, seemingly ignoring the beautiful tzinfo o...
`.replace` does no computation: it simply **replaces** one or more field in the new returned object, while copying all others from the object it's called on. If I understand your situation correctly, you start with a datetime object which you *know* (through other means) is UTC, but doesn't know that itself (is has a ...
How can I process xml asynchronously in python?
2,090,096
6
2010-01-18T23:59:58Z
2,090,259
7
2010-01-19T00:35:06Z
[ "python", "xml", "multithreading", "sax" ]
I have a large XML data file (>160M) to process, and it seems like SAX/expat/pulldom parsing is the way to go. I'd like to have a thread that sifts through the nodes and pushes nodes to be processed onto a queue, and then other worker threads pull the next available node off the queue and process it. I have the follow...
I'm not too sure about this problem. I'm guessing the call to ParseFile is blocking and only the parsing thread is being run because of the GIL. A way around this would be to use [`multiprocessing`](http://docs.python.org/library/multiprocessing.html) instead. It's designed to work with queues, anyway. You make a [`Pr...
How can I process xml asynchronously in python?
2,090,096
6
2010-01-18T23:59:58Z
2,090,329
7
2010-01-19T00:51:53Z
[ "python", "xml", "multithreading", "sax" ]
I have a large XML data file (>160M) to process, and it seems like SAX/expat/pulldom parsing is the way to go. I'd like to have a thread that sifts through the nodes and pushes nodes to be processed onto a queue, and then other worker threads pull the next available node off the queue and process it. I have the follow...
[`ParseFile`](http://docs.python.org/library/pyexpat.html?highlight=parsefile#xml.parsers.expat.xmlparser.ParseFile), as you've noticed, just "gulps down" everything -- no good for the *incremental* parsing you want to do! So, just feed the file to the parser a bit at a time, making sure to conditionally yield control ...
Symbolic Group Names (like in Python) in Ruby Regular Expression
2,090,424
7
2010-01-19T01:14:54Z
2,090,471
11
2010-01-19T01:27:26Z
[ "python", "ruby", "regex" ]
Came across this handy regular expression utility in Python (I am a beginner in Python). e.g. By using the regexp ``` (?P<id>[a-zA-Z_]\w*) ``` I can refer to the matched data as ``` m.group('id') ``` (Full documentation: look for "symbolic group name" [here](http://docs.python.org/library/re.html)) In Ruby, we can...
Older Ruby releases didn't have named groups (tx Alan for pointing this out in a comment!), but, if you're using Ruby 1.9...: `(?<name>subexp)` expresses a named group in Ruby expressions too; `\k<name>` is the way you back-reference a named group in substitution, if that's what you're looking for!
Symbolic Group Names (like in Python) in Ruby Regular Expression
2,090,424
7
2010-01-19T01:14:54Z
2,090,811
10
2010-01-19T03:14:16Z
[ "python", "ruby", "regex" ]
Came across this handy regular expression utility in Python (I am a beginner in Python). e.g. By using the regexp ``` (?P<id>[a-zA-Z_]\w*) ``` I can refer to the matched data as ``` m.group('id') ``` (Full documentation: look for "symbolic group name" [here](http://docs.python.org/library/re.html)) In Ruby, we can...
Ruby 1.9 introduced named captures: ``` m = /(?<prefix>[A-Z]+)(?<hyphen>-?)(?<digits>\d+)/.match("THX1138.") m.names # => ["prefix", "hyphen", "digits"] m.captures # => ["THX", "", "1138"] m[:prefix] # => "THX" ``` You can use `\k<prefix>`, etc, for back-references.
Python Window Activation
2,090,464
8
2010-01-19T01:25:50Z
2,091,530
18
2010-01-19T06:21:50Z
[ "python", "windows" ]
How would I programmatically activate a window in Windows using Python? I'm sending keystrokes to it and at the moment I'm just making sure it's the last application used then sending the keystroke Alt+Tab to switch over to it from the DOS console. Is there a better way (since I've learned by experience that this way i...
You can use the win32gui module to do that. First you need to get a valid handle on your window. You can use the `win32gui.FindWindow` if you know the window class name or the exact title. If not, you can enumerate the windows with the `win32gui.EnumWindows` and try to find the right one. Once you have the handle, you...
ValueError: no such test method in <class 'myapp.tests.SessionTestCase'>: runTest
2,090,479
9
2010-01-19T01:29:46Z
16,211,735
21
2013-04-25T09:57:20Z
[ "python", "unit-testing" ]
I have a test case: ``` class LoginTestCase(unittest.TestCase): ... ``` I'd like to use it in a different test case: ``` class EditProfileTestCase(unittest.TestCase): def __init__(self): self.t = LoginTestCase() self.t.login() ``` This raises: ``` ValueError: no such test method in <class 'LoginTest:...
The confusion with "runTest" is mostly based on the fact that this works: ``` class MyTest(unittest.TestCase): def test_001(self): print "ok" if __name__ == "__main__": unittest.main() ``` So there is no "runTest" in that class and all of the test-functions are being called. However if you look at th...
ValueError: no such test method in <class 'myapp.tests.SessionTestCase'>: runTest
2,090,479
9
2010-01-19T01:29:46Z
26,900,524
10
2014-11-13T02:49:35Z
[ "python", "unit-testing" ]
I have a test case: ``` class LoginTestCase(unittest.TestCase): ... ``` I'd like to use it in a different test case: ``` class EditProfileTestCase(unittest.TestCase): def __init__(self): self.t = LoginTestCase() self.t.login() ``` This raises: ``` ValueError: no such test method in <class 'LoginTest:...
Here's some '**deep black magic**': ``` suite = unittest.TestLoader().loadTestsFromTestCase(Test_MyTests) unittest.TextTestRunner(verbosity=3).run(suite) ``` Very handy if you just want to test run your unit tests from a shell (i.e., [IPython](http://ipython.org/)).
What version of Python should I use if I'm a new to Python?
2,090,820
18
2010-01-19T03:15:32Z
2,090,836
12
2010-01-19T03:20:40Z
[ "python" ]
If I'm absolutely new to Python and am literally reading about printing statements to console, variable types, collections, etc: > What version of Python should I use? I'm aware that there is an abundance of 3rd party libraries for Python 2.6.x, but I'm scared I'll learn some things that won't carry over well into Py...
It's really going to depend on what you want to do. Generally speaking Python 3 "isn't ready yet", in the sense that few libraries support Python 3. This will end up greatly limiting what you can accomplish with the language as a beginner. On the other hand, if you think you'll be spending your time on more "pure prog...
What version of Python should I use if I'm a new to Python?
2,090,820
18
2010-01-19T03:15:32Z
2,090,843
18
2010-01-19T03:21:49Z
[ "python" ]
If I'm absolutely new to Python and am literally reading about printing statements to console, variable types, collections, etc: > What version of Python should I use? I'm aware that there is an abundance of 3rd party libraries for Python 2.6.x, but I'm scared I'll learn some things that won't carry over well into Py...
Python 2.6 (and 2.5, 2.4) are what you will find installed on most machines (Linux) and what you will **find most code written in**. Therefore I'd start with Python 2.6.
python datetime localization
2,090,840
7
2010-01-19T03:21:25Z
2,090,861
7
2010-01-19T03:28:10Z
[ "python" ]
What do I need to do (modules to load, locale methods to invoke, etc.) so that when I call: ``` datetime.date(2009,1,16).strftime("%A %Y-%b-%d") ``` instead of getting: ``` Out[20]: 'Friday 2009-Jan-16' ``` i get spanish/french/german/... output ``` Out[20]: 'Viernes 2009-Ene-16' ``` without having to change my w...
[`locale.setlocale()`](http://docs.python.org/library/locale.html#locale.setlocale)
Run a C++ Program from Django Framework
2,091,294
2
2010-01-19T05:27:42Z
2,091,306
9
2010-01-19T05:30:06Z
[ "c++", "python", "django" ]
I need to run a C++ Program from Django Framework. In a sense, I get inputs from UI in views.py . Once I have these inputs, I need to process the input using my C++ program and use those results. Is it possible ?
Compile that C++ program to executable and call with [subprocess](http://docs.python.org/library/subprocess.html) module from python
Python and SQLite: insert into table
2,092,757
25
2010-01-19T10:31:36Z
2,092,785
22
2010-01-19T10:36:03Z
[ "python", "sqlite", "list", "insert" ]
I have a list that has 3 rows each representing a table row: ``` >>> print list [laks,444,M] [kam,445,M] [kam,445,M] ``` How to insert this list into a table? My table structure is: ``` tablename(name varchar[100], age int, sex char[1]) ``` Or should I use something other than list? Here is the actual code part: ...
``` conn = sqlite3.connect('/path/to/your/sqlite_file.db') c = conn.cursor() for item in my_list: c.execute('insert into tablename values (?,?,?)', item) ```
Python and SQLite: insert into table
2,092,757
25
2010-01-19T10:31:36Z
6,019,743
44
2011-05-16T15:35:37Z
[ "python", "sqlite", "list", "insert" ]
I have a list that has 3 rows each representing a table row: ``` >>> print list [laks,444,M] [kam,445,M] [kam,445,M] ``` How to insert this list into a table? My table structure is: ``` tablename(name varchar[100], age int, sex char[1]) ``` Or should I use something other than list? Here is the actual code part: ...
there's a better way ``` # Larger example rows = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00), ('2006-04-06', 'SELL', 'IBM', 500, 53.00)] c.executemany('insert into stocks values (?,?,?,?,?)', rows) connection.commit() ```
Python functional programming snippets
2,093,388
9
2010-01-19T12:24:55Z
2,093,942
7
2010-01-19T13:59:41Z
[ "python", "functional-programming" ]
I've seen some elegant python snippets using list comprehension and map reduce. Can you share some of these code or a web site. Thanks.
Python is not lisp. Please don't try to make it look that way. It only reduces one of python's biggest strengths, which is its readability and understandability later on. If you like functional programming, learn [Haskell](http://haskell.org/), [ML](http://en.wikipedia.org/wiki/ML_%28programming_language%29), or [F#](...
Is it possible to implement a "change password at next logon" type feature in the django admin?
2,093,593
12
2010-01-19T13:04:53Z
5,570,717
18
2011-04-06T17:46:27Z
[ "python", "django" ]
I want to be able to set an option in the user's settings that forces them to change their password upon the next login to the admin interface. Is this possible? How would it go about being implemented? I'm using the default auth model right now but not opposed to modifying or changing it. Thanks for any help.
I'm actually in the process of doing this myself. You need three components: a user profile (if not already in use on your site), a middleware component, and a pre\_save signal. My code for this is in an app named 'accounts'. ``` # myproject/accounts/models.py from django.db import models from django.db.models impor...
Is it possible to implement a "change password at next logon" type feature in the django admin?
2,093,593
12
2010-01-19T13:04:53Z
13,138,005
8
2012-10-30T11:26:43Z
[ "python", "django" ]
I want to be able to set an option in the user's settings that forces them to change their password upon the next login to the admin interface. Is this possible? How would it go about being implemented? I'm using the default auth model right now but not opposed to modifying or changing it. Thanks for any help.
I have used Chris Pratt's solution, with a little change: instead of using a middleware, that'd be executed for every page with the consequent resource use, I figured I'd just intercept the login view. In my urls.py I have added this to my urlpatterns: ``` url(r'^accounts/login/$', 'userbase.views.force_pwd_login'), ...
Serializing objects containing django querysets
2,093,840
4
2010-01-19T13:41:09Z
2,095,925
9
2010-01-19T18:23:35Z
[ "python", "django", "json" ]
Django provides tools to serialize querysets (django.core.serializers), but what about serializing querysets living inside other objects (like dictionaries)? I want to serialize the following dictionary: ``` dictionary = { 'alfa': queryset1, 'beta': queryset2, } ``` I decided to do this using **simplejson** (comes w...
The correct way to do this would be: ``` from django.utils import simplejson from django.core import serializers from django.db.models.query import QuerySet class HandleQuerySets(simplejson.JSONEncoder): """ simplejson.JSONEncoder extension: handle querysets """ def default(self, obj): if isinstanc...
Why can't Python decorators be chained across definitions?
2,094,008
8
2010-01-19T14:09:27Z
2,094,286
9
2010-01-19T14:50:48Z
[ "python", "decorator" ]
Why arn't the following two scripts equivalent? (Taken from another question: [Understanding Python Decorators](http://stackoverflow.com/questions/739654/understanding-python-decorators)) ``` def makebold(fn): def wrapped(): return "<b>" + fn() + "</b>" return wrapped def makeitalic(fn): def wrap...
The problem with the second example is that ``` @makebold def makeitalic(fn): def wrapped(): return "<i>" + fn() + "</i>" return wrapped ``` is trying to decorate `makeitalic`, the decorator, and not `wrapped`, the function it returns. You can do what I think you intend with something like this: ```...
How can I configure Geany to compile and run my Python programs?
2,094,105
7
2010-01-19T14:27:26Z
2,094,530
7
2010-01-19T15:23:56Z
[ "python", "geany" ]
Under the Build menu, I can see 'Execute' option, but it is greyed out. The only option available is 'Set Includes and Arguments'. When I click that both fields are already filled out. What do I have to write there? ![alt text](http://imgur.com/MXFfW.png)
I don't need to configure anything in geany, I just hit F5 and current module is executed. Are you sure, that your file is recognized as python source file? Which version of geany are you using (I am using svn version, which is pretty stable, damn, it's rock solid stable ;-))? I have slightly more developed configurat...
split a string in python
2,094,176
12
2010-01-19T14:38:36Z
2,094,199
19
2010-01-19T14:41:04Z
[ "python", "string" ]
All, I have a string in python say `a="Show details1\nShow details2\nShow details3\nShow details4\nShow details5\n"` How do we split the above with the delimiter `\n` (a newline). The result should be as `['Show details1', 'Show details2', ..., 'Show details5']`
Use `a.splitlines()`. This will return you a list of the separate lines. To get your "should be" result, add `" ".join(a.splitlines())`, and to get all in lower case as shown, the whole enchilada looks like `" ".join(a.splitlines()).lower()`.
split a string in python
2,094,176
12
2010-01-19T14:38:36Z
2,094,840
14
2010-01-19T15:59:35Z
[ "python", "string" ]
All, I have a string in python say `a="Show details1\nShow details2\nShow details3\nShow details4\nShow details5\n"` How do we split the above with the delimiter `\n` (a newline). The result should be as `['Show details1', 'Show details2', ..., 'Show details5']`
If you are concerned only with the trailing newline, you can do: ``` a.rstrip().split('\n') ``` See, str.lstrip() and str.strip() for variations. If you are more generally concerned by superfluous newlines producing empty items, you can do: ``` filter(None, a.split('\n')) ```
How do I declare an attribute in Python without a value?
2,094,658
12
2010-01-19T15:40:23Z
2,094,681
10
2010-01-19T15:42:50Z
[ "python", "class" ]
In C# I would go: ``` string UserName; string Password; ``` But now, in Python: ``` class User: UserName Password ``` I recieve an error that UserName isn't defined. I can't declare a variable without a variable?
First of all, you should rewrite like this: ``` class User(object): def __init__(self, username, password): self.username = username self.password = password ``` This way, username and password are instance variables instead of class variables (in your example, they are class variables -- all instance varia...
How do I declare an attribute in Python without a value?
2,094,658
12
2010-01-19T15:40:23Z
2,094,690
23
2010-01-19T15:43:29Z
[ "python", "class" ]
In C# I would go: ``` string UserName; string Password; ``` But now, in Python: ``` class User: UserName Password ``` I recieve an error that UserName isn't defined. I can't declare a variable without a variable?
In Python, and many other languages, there is a value that means "no value". In Python, that value is `None`. So you could do something like this: ``` class User: UserName = None PassWord = None ``` Those sure sound like instance variables though, and not class variables, so maybe do this: ``` class User(objec...
Python re.sub question
2,094,975
12
2010-01-19T16:20:39Z
2,095,007
8
2010-01-19T16:24:46Z
[ "python", "regex" ]
Greetings all, I'm not sure if this is possible but I'd like to use matched groups in a regex substitution to call variables. ``` a = 'foo' b = 'bar' text = 'find a replacement for me [[:a:]] and [[:b:]]' desired_output = 'find a replacement for me foo and bar' re.sub('\[\[:(.+):\]\]',group(1),text) #is not valid ...
Sounds like overkill. Why not just do something like ``` text = "find a replacement for me %(a)s and %(b)s"%dict(a='foo', b='bar') ``` ?
Python re.sub question
2,094,975
12
2010-01-19T16:20:39Z
2,095,012
22
2010-01-19T16:25:26Z
[ "python", "regex" ]
Greetings all, I'm not sure if this is possible but I'd like to use matched groups in a regex substitution to call variables. ``` a = 'foo' b = 'bar' text = 'find a replacement for me [[:a:]] and [[:b:]]' desired_output = 'find a replacement for me foo and bar' re.sub('\[\[:(.+):\]\]',group(1),text) #is not valid ...
You can specify a callback when using re.sub, which has access to the groups: <http://docs.python.org/library/re.html#text-munging> ``` a = 'foo' b = 'bar' text = 'find a replacement for me [[:a:]] and [[:b:]]' desired_output = 'find a replacement for me foo and bar' def repl(m): contents = m.group(1) if co...