title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
how to ask user input a string with a timeout embeded in python on windows machine?
2,554,187
<p>want to ask user to input something but not want to wait forever. There is a solution for Linux, <a href="http://stackoverflow.com/questions/1335507/keyboard-input-with-timeout-in-python">http://stackoverflow.com/questions/1335507/keyboard-input-with-timeout-in-python</a>, but I am in windows environment. anybody ca...
3
2010-03-31T15:21:15Z
2,554,457
<p>Credit to <a href="http://bytes.com/topic/python/answers/36171-need-function-like-raw_input-but-time-limit" rel="nofollow">Alex Martelli</a></p> <blockquote> <p>Unfortunately, on Windows, select.select works only on sockets, not ordinary files nor the console. So, if you want to run on Windows, you need a...
2
2010-03-31T15:59:49Z
[ "python" ]
How to send EOF to stdin in paramiko?
2,554,292
<p>I would like to execute some program through ssh and redirect its input from a file. The behaviour of the following code:</p> <pre><code>channel.exec_command('cat') with open('mumu', 'r') as f: text = f.read() nbytes = 0 while nbytes &lt; len(text): sent = channel.send(text[nbytes:]) if ...
4
2010-03-31T15:36:00Z
2,554,398
<p>Call <a href="http://docs.paramiko.org/en/2.0/api/channel.html#paramiko.channel.Channel.shutdown" rel="nofollow"><code>shutdown()</code></a> (or <code>shutdown_write()</code>) on the channel.</p>
4
2010-03-31T15:52:31Z
[ "python", "stdin", "eof", "paramiko" ]
How to send EOF to stdin in paramiko?
2,554,292
<p>I would like to execute some program through ssh and redirect its input from a file. The behaviour of the following code:</p> <pre><code>channel.exec_command('cat') with open('mumu', 'r') as f: text = f.read() nbytes = 0 while nbytes &lt; len(text): sent = channel.send(text[nbytes:]) if ...
4
2010-03-31T15:36:00Z
3,093,171
<p>Call the method: <code>channel.shutdown_write()</code>.</p>
4
2010-06-22T12:41:31Z
[ "python", "stdin", "eof", "paramiko" ]
Parsing a file with hierarchical structure in Python
2,554,474
<p>I'm trying to parse the output from a tool into a data structure but I'm having some difficulty getting things right. The file looks like this:</p> <pre><code> Fruits Apple Auxiliary Core Extras Banana Something Coconut Vegetables Eggplant Rutabaga </code></pre> <p>You can see t...
1
2010-03-31T16:03:11Z
2,554,559
<p>so you don't want the deepest level right? I don't know if i get you correct, but nevertheless, here's one approach</p> <pre><code>d=[] for line in open("file"): if not line.startswith(" "): if line.startswith(" "): d.append(p+"/"+line.strip()) elif line.startswith(" "): ...
1
2010-03-31T16:12:31Z
[ "python", "data-structures", "file-io" ]
Parsing a file with hierarchical structure in Python
2,554,474
<p>I'm trying to parse the output from a tool into a data structure but I'm having some difficulty getting things right. The file looks like this:</p> <pre><code> Fruits Apple Auxiliary Core Extras Banana Something Coconut Vegetables Eggplant Rutabaga </code></pre> <p>You can see t...
1
2010-03-31T16:03:11Z
2,554,619
<p>This assumes your input file is 'datafile.txt', you only use whitespaces to indent, you specify your indent_string per level and your level 0 starts without any indent (no whitespace on lowest indent at all). All this contraints can be removed with little effort. But basic layout should be clear: </p> <pre><code>im...
0
2010-03-31T16:19:33Z
[ "python", "data-structures", "file-io" ]
Parsing a file with hierarchical structure in Python
2,554,474
<p>I'm trying to parse the output from a tool into a data structure but I'm having some difficulty getting things right. The file looks like this:</p> <pre><code> Fruits Apple Auxiliary Core Extras Banana Something Coconut Vegetables Eggplant Rutabaga </code></pre> <p>You can see t...
1
2010-03-31T16:03:11Z
2,554,631
<pre><code>&gt;&gt;&gt; with open("food.txt") as f: ... res = [] ... s=[] ... for line in f: ... line=line.rstrip() ... x=len(line) ... line=line.lstrip() ... indent = x-len(line) ... s=s[:indent/2]+[line] ... res.append("/".join(s)) ... print res ... ['F...
3
2010-03-31T16:21:25Z
[ "python", "data-structures", "file-io" ]
Parsing a file with hierarchical structure in Python
2,554,474
<p>I'm trying to parse the output from a tool into a data structure but I'm having some difficulty getting things right. The file looks like this:</p> <pre><code> Fruits Apple Auxiliary Core Extras Banana Something Coconut Vegetables Eggplant Rutabaga </code></pre> <p>You can see t...
1
2010-03-31T16:03:11Z
2,554,646
<p>You could do something like this:</p> <pre><code>builder, outlist = [], [] current_spacing = 0 with open('input.txt') as f: for line in f: stripped = line.lstrip() num_spaces = len(line) - len(stripped) if num_spaces == current_spacing: builder.pop() elif num_spaces ...
0
2010-03-31T16:25:09Z
[ "python", "data-structures", "file-io" ]
Asynchronous subprocess on Windows
2,554,514
<p>First of all, the overall problem I am solving is a bit more complicated than I am showing here, so please do not tell me 'use threads with blocking' as it would not solve my actual situation without a fair, FAIR bit of rewriting and refactoring.</p> <p>I have several applications which are not mine to modify, whic...
4
2010-03-31T16:06:48Z
2,557,481
<p>What about using Twisted's FD's? <a href="http://twistedmatrix.com/documents/8.1.0/api/twisted.internet.fdesc.html" rel="nofollow">http://twistedmatrix.com/documents/8.1.0/api/twisted.internet.fdesc.html</a></p> <p>It's not asynchronous but it is non-blocking. For asynchronous stuff, can you port to using Twisted?<...
0
2010-04-01T00:47:31Z
[ "python", "asynchronous", "subprocess" ]
Asynchronous subprocess on Windows
2,554,514
<p>First of all, the overall problem I am solving is a bit more complicated than I am showing here, so please do not tell me 'use threads with blocking' as it would not solve my actual situation without a fair, FAIR bit of rewriting and refactoring.</p> <p>I have several applications which are not mine to modify, whic...
4
2010-03-31T16:06:48Z
2,557,948
<p>Can't you just do a non-blocking read from pA.stdout and pB.stdout? You will have a tight busy loop to manage?</p> <p><a href="http://stackoverflow.com/questions/375427/non-blocking-read-on-a-stream-in-python">http://stackoverflow.com/questions/375427/non-blocking-read-on-a-stream-in-python</a></p>
0
2010-04-01T03:17:30Z
[ "python", "asynchronous", "subprocess" ]
Asynchronous subprocess on Windows
2,554,514
<p>First of all, the overall problem I am solving is a bit more complicated than I am showing here, so please do not tell me 'use threads with blocking' as it would not solve my actual situation without a fair, FAIR bit of rewriting and refactoring.</p> <p>I have several applications which are not mine to modify, whic...
4
2010-03-31T16:06:48Z
2,575,695
<p>How bad is it to have to use threads? I encountered much the same problem and eventually decided to use threads to gather up all the data on a sub-process's stdout and stderr and put it onto a thread-safe queue which which the main thread can read in a blocking fashion, without having to worry about the threading go...
4
2010-04-04T19:59:07Z
[ "python", "asynchronous", "subprocess" ]
Asynchronous subprocess on Windows
2,554,514
<p>First of all, the overall problem I am solving is a bit more complicated than I am showing here, so please do not tell me 'use threads with blocking' as it would not solve my actual situation without a fair, FAIR bit of rewriting and refactoring.</p> <p>I have several applications which are not mine to modify, whic...
4
2010-03-31T16:06:48Z
2,596,008
<p>I assume that the process pipeline will not deadlock if it only uses stdin and stdout; and the problem you're trying to solve is how to make it not deadlock if they write to stderr (and have to deal with stderr possibly getting backed up).</p> <p>If you're letting multiple processes write to stderr, you have to wat...
1
2010-04-07T21:17:00Z
[ "python", "asynchronous", "subprocess" ]
Python: why does str() on some text from a UTF-8 file give a UnicodeDecodeError?
2,554,545
<p>I'm processing a UTF-8 file in Python, and have used simplejson to load it into a dictionary. However, I'm getting a UnicodeDecodeError when I try to turn one of the dictionary values into a string:</p> <pre><code>f = open('my_json.json', 'r') master_dictionary = json.load(f) #some json wrangling, then it fails on ...
5
2010-03-31T16:10:59Z
2,554,629
<p>One way to make this work would be to set the default encoding to UTF-8 explicitly, like:</p> <pre><code>import sys sys.setdefaultencoding("utf-8") </code></pre> <p>This could lead to unintended consequences if you don't want everything to be unicode by default.</p> <p>A cleaner way could be to use the <code>unic...
2
2010-03-31T16:21:13Z
[ "python", "character-encoding" ]
Python: why does str() on some text from a UTF-8 file give a UnicodeDecodeError?
2,554,545
<p>I'm processing a UTF-8 file in Python, and have used simplejson to load it into a dictionary. However, I'm getting a UnicodeDecodeError when I try to turn one of the dictionary values into a string:</p> <pre><code>f = open('my_json.json', 'r') master_dictionary = json.load(f) #some json wrangling, then it fails on ...
5
2010-03-31T16:10:59Z
2,554,633
<p>Python 2.x uses ASCII by default. Use <code>unicode.encode()</code> if you want to turn a <code>unicode</code> into a <code>str</code>:</p> <pre><code>v_dict['code'].encode('utf-8') </code></pre>
6
2010-03-31T16:22:05Z
[ "python", "character-encoding" ]
What is the analog for .Net InvalidOperationException in Python?
2,554,722
<p>What is the analog for .Net <code>InvalidOperationException</code> in <code>Python</code>?</p>
11
2010-03-31T16:37:53Z
2,554,808
<p>I'd probably go between one of two options:</p> <ol> <li><p>A custom exception, best defined as follows:</p> <p><code>class InvalidOperationException(Exception): pass</code></p></li> <li><p>Just using <code>Exception</code></p></li> </ol> <p>I don't believe there's a direct analogue; Python seems to have a very...
3
2010-03-31T16:46:37Z
[ ".net", "python", "exception", "invalidoperationexception" ]
What is the analog for .Net InvalidOperationException in Python?
2,554,722
<p>What is the analog for .Net <code>InvalidOperationException</code> in <code>Python</code>?</p>
11
2010-03-31T16:37:53Z
2,554,816
<p>There's no direct equivalent. Usually <code>ValueError</code> or <code>TypeError</code> suffices, perhaps a <code>RuntimeError</code> or <code>NotImplementedError</code> if neither of those fit well.</p>
7
2010-03-31T16:47:22Z
[ ".net", "python", "exception", "invalidoperationexception" ]
What is the analog for .Net InvalidOperationException in Python?
2,554,722
<p>What is the analog for .Net <code>InvalidOperationException</code> in <code>Python</code>?</p>
11
2010-03-31T16:37:53Z
2,556,939
<p>I'll partially agree with Chris R -- define your own:</p> <pre><code> class InvalidOperationException(Exception): pass </code></pre> <p>You get much benefit from defining your own exceptions this way, including building a hierarchy to fit your needs:</p> <pre><code> class MyExceptionBase(Exception): pass ...
2
2010-03-31T22:31:06Z
[ ".net", "python", "exception", "invalidoperationexception" ]
custom format specifications in python
2,554,758
<p>in python, how can a custom format-specification be added, to a class ? for example, if i write a matrix class, i would like to define a '%M' (or some such) which would then dump the entire contents of the matrix...</p> <p>thanks</p>
2
2010-03-31T16:41:51Z
2,554,780
<p>Defining the <code>__str__()</code>/<code>__unicode__()</code> and/or <code>__repr__()</code> methods will let you use the existing <code>%s</code> and <code>%r</code> format specifiers as you like.</p>
5
2010-03-31T16:43:48Z
[ "python", "format", "specifications" ]
custom format specifications in python
2,554,758
<p>in python, how can a custom format-specification be added, to a class ? for example, if i write a matrix class, i would like to define a '%M' (or some such) which would then dump the entire contents of the matrix...</p> <p>thanks</p>
2
2010-03-31T16:41:51Z
2,555,037
<p>I don't believe that it's possible to define a new format specifier for print. You might be able to add a method to your class that sets a format that you use, and define the <strong>str</strong> method of the class to adjust it's output according to how it was set. Then the main print statement would still use a '...
0
2010-03-31T17:18:56Z
[ "python", "format", "specifications" ]
custom format specifications in python
2,554,758
<p>in python, how can a custom format-specification be added, to a class ? for example, if i write a matrix class, i would like to define a '%M' (or some such) which would then dump the entire contents of the matrix...</p> <p>thanks</p>
2
2010-03-31T16:41:51Z
2,555,409
<p>If you really want to use custom specifiers you cannot do this in way that compatible with the rest of the Python language and standard library. <strong>Take advantage of what Python already supplies (<code>%s</code> and <code>%r</code>) and customise it for your needs by overriding <code>__str__()</code> or <code>_...
0
2010-03-31T18:20:13Z
[ "python", "format", "specifications" ]
How can I have my python file show its mercurial tag or revision as the module version?
2,554,990
<p>I'd like to add a --version command line option to my python application that will show the <em>right</em> version depending on the tagged status of the command:</p> <p>If the file comes from a version whose short hex ID was <code>abcdef01</code> that was tagged <code>TAG</code>, <code>--version</code> should show ...
3
2010-03-31T17:11:39Z
2,555,014
<p>Once you activate the <a href="http://mercurial.selenic.com/wiki/KeywordExtension" rel="nofollow">keyword extension</a>, you can have it in a variable which can be carved up for the hash.</p>
1
2010-03-31T17:14:26Z
[ "python", "mercurial", "keyword" ]
How can I have my python file show its mercurial tag or revision as the module version?
2,554,990
<p>I'd like to add a --version command line option to my python application that will show the <em>right</em> version depending on the tagged status of the command:</p> <p>If the file comes from a version whose short hex ID was <code>abcdef01</code> that was tagged <code>TAG</code>, <code>--version</code> should show ...
3
2010-03-31T17:11:39Z
2,555,412
<p>Someone pointed out the KeywordExtension, and that's definitely one route to go.</p> <p>For a little more control you can create an 'update' writes what you want into a <code>version</code> file which you don't add to the repository itself. Something like this in your repo's hgrc:</p> <pre><code>[hooks] update = ...
1
2010-03-31T18:21:00Z
[ "python", "mercurial", "keyword" ]
python sqlite3 syntax error when copying a row
2,555,302
<p>I'm having trouble copying a row from one table to another using sqlite3 in python (2.6.1 don't ask). I can specify one column, but if I add a second, it gives me an error.</p> <pre><code>import sqlite3 conn = sqlite3.connect("database.db") cursor = conn.cursor() #this works: cursor.execute("insert into table2 (n...
0
2010-03-31T18:06:20Z
2,555,316
<p>You shouldn't have the parentheses after <code>select</code>. It should be:</p> <pre><code>insert into table2 (name, title) select name, title from table1 </code></pre>
1
2010-03-31T18:07:50Z
[ "python", "sqlite", "sqlite3" ]
good __eq__, __lt__, ..., __hash__ methods for image class?
2,555,338
<p>I create the following class:</p> <pre><code>class Image(object): def __init__(self, extension, data, urls=None, user_data=None): self._extension = extension self._data = data self._urls = urls self._user_data = user_data self._hex_digest = hashlib.sha1(self._data).hexDig...
2
2010-03-31T18:10:41Z
2,555,422
<p>Do you really need the images to be ordered? If not, I would drop the <code>__lt__</code> method. For <code>__hash__</code>, remember that two unequal objects can have the same hash value, so you can just pick one of your attributes (or use a tuple of multiple attributes) to derive the hash code. Ex:</p> <pre><cod...
5
2010-03-31T18:22:04Z
[ "python" ]
good __eq__, __lt__, ..., __hash__ methods for image class?
2,555,338
<p>I create the following class:</p> <pre><code>class Image(object): def __init__(self, extension, data, urls=None, user_data=None): self._extension = extension self._data = data self._urls = urls self._user_data = user_data self._hex_digest = hashlib.sha1(self._data).hexDig...
2
2010-03-31T18:10:41Z
2,555,435
<p>Have you looked the rules for dictionary comparison? </p> <p>Check here: <a href="http://docs.python.org/reference/expressions.html#notin" rel="nofollow">http://docs.python.org/reference/expressions.html#notin</a> </p> <p>This is not well-defined (yet). It may be defined in a "What's New" document.</p> <p>Howe...
1
2010-03-31T18:23:58Z
[ "python" ]
Including libraries in project. Best practice
2,555,393
<p>I'm writing a Python open-source app. My app uses some open source Python libraries. These libraries in turn use other open-source libraries.</p> <p>I intend to release my code at Sourceforge or Google Code but do I need to include the sources of the other libraries? Is this a good practice? ...or should I simply w...
1
2010-03-31T18:18:14Z
2,555,428
<p>Normally you would just include the libraries in the final released version, but not necessarily include them in the source releases.</p>
1
2010-03-31T18:23:01Z
[ "python", "distribution" ]
Including libraries in project. Best practice
2,555,393
<p>I'm writing a Python open-source app. My app uses some open source Python libraries. These libraries in turn use other open-source libraries.</p> <p>I intend to release my code at Sourceforge or Google Code but do I need to include the sources of the other libraries? Is this a good practice? ...or should I simply w...
1
2010-03-31T18:18:14Z
2,555,451
<p>I think the most common practice is to inform your user which libraries and version numbers your code uses in something like a README.txt file. You can create a Python Egg package for you code that includes the library dependencies (if they have eggs as well), that can be download with your package upon installatio...
1
2010-03-31T18:26:31Z
[ "python", "distribution" ]
Including libraries in project. Best practice
2,555,393
<p>I'm writing a Python open-source app. My app uses some open source Python libraries. These libraries in turn use other open-source libraries.</p> <p>I intend to release my code at Sourceforge or Google Code but do I need to include the sources of the other libraries? Is this a good practice? ...or should I simply w...
1
2010-03-31T18:18:14Z
2,555,599
<p>In general (for Python): don't ship the source of other libraries which you depend upon in your code. </p> <p>Just state the required dependencies (complete with minimum required version, installation instructions etc) on a website and in instructions shipped with the source.</p>
1
2010-03-31T18:45:33Z
[ "python", "distribution" ]
Including libraries in project. Best practice
2,555,393
<p>I'm writing a Python open-source app. My app uses some open source Python libraries. These libraries in turn use other open-source libraries.</p> <p>I intend to release my code at Sourceforge or Google Code but do I need to include the sources of the other libraries? Is this a good practice? ...or should I simply w...
1
2010-03-31T18:18:14Z
2,555,674
<p>Use the pip requirements text file.</p> <p>Just name the packages [and optionally version]</p> <p>Ask the users to execute the following command in the README. (If you provide an install script, then you should call this within that; In that case you should also use <a href="http://pypi.python.org/pypi/virtualenv"...
3
2010-03-31T18:55:40Z
[ "python", "distribution" ]
Including libraries in project. Best practice
2,555,393
<p>I'm writing a Python open-source app. My app uses some open source Python libraries. These libraries in turn use other open-source libraries.</p> <p>I intend to release my code at Sourceforge or Google Code but do I need to include the sources of the other libraries? Is this a good practice? ...or should I simply w...
1
2010-03-31T18:18:14Z
2,555,736
<p>As others say, do not include the libraries, state the requirements in documentation. This way your project can use the libraries users already have, sometimes provided by their operating system distribution.</p> <p>But then, keep in mind those external dependencies, that may exist in different versions or even con...
3
2010-03-31T19:04:47Z
[ "python", "distribution" ]
trying to use code_swarm but Im having some python scripting problems with perforce on osx
2,555,481
<p>I am having issues running this:</p> <pre><code>link-mbp:codeswarm-0.1 benb$ python convert_logs/convert_logs.py -perforce-path Traceback (most recent call last): File “convert_logs/convert_logs.py”, line 408, in main() File “convert_logs/convert_logs.py”, line 350, in main files = run_marshal(’p4 -G desc...
2
2010-03-31T18:31:00Z
6,437,314
<p>I had the exact same problem. Not being an expert on python I debugged the script using a print-statement on line 350 like this:</p> <pre><code>for changelist in changelists: print changelist # &lt;-- here files = run_marshal('p4 -G describe -s "' + changelist['change'] + '"') </code></pre> <p>This reveale...
0
2011-06-22T08:55:52Z
[ "python", "osx", "perforce", "code-swarm" ]
What could cause Django to start failing its own tests after an OS and Django reinstall?
2,555,629
<p>I had to reinstall my OS, and so, I reinstalled django 1.1. Since reinstalling, when I run tests in my app, I get several failures from django.contrib.auth.</p> <p>Logs: <a href="http://dpaste.com/178153/" rel="nofollow">http://dpaste.com/178153/</a></p> <p>I asked on #django, and no one is too sure what the cause...
0
2010-03-31T18:49:56Z
2,555,783
<p>These look like <code>django.contib.auth</code> failures. Are including <code>django.contib.auth</code> in your installed apps? Have you changed either the <a href="http://docs.djangoproject.com/en/1.1/ref/settings/#middleware-classes" rel="nofollow"><code>MIDDLEWARE_CLASSES</code></a> or <a href="http://docs.django...
0
2010-03-31T19:14:19Z
[ "python", "django", "testing" ]
What could cause Django to start failing its own tests after an OS and Django reinstall?
2,555,629
<p>I had to reinstall my OS, and so, I reinstalled django 1.1. Since reinstalling, when I run tests in my app, I get several failures from django.contrib.auth.</p> <p>Logs: <a href="http://dpaste.com/178153/" rel="nofollow">http://dpaste.com/178153/</a></p> <p>I asked on #django, and no one is too sure what the cause...
0
2010-03-31T18:49:56Z
2,571,445
<p>Asking on #django again reveals this is a known bug to do with python 2.6.5 which came with the new version of my OS, and Django 1.1.1.</p> <p>It has been <a href="http://code.djangoproject.com/changeset/11821" rel="nofollow">patched</a> in the development version.</p>
0
2010-04-03T14:06:19Z
[ "python", "django", "testing" ]
Q on Python serialization/deserialization
2,555,705
<p>What chances do I have to instantiate, keep and serialize/deserialize to/from binary data Python classes reflecting this pattern (adopted from RFC 2246 [TLS]):</p> <pre><code> enum { apple, orange } VariantTag; struct { uint16 number; opaque string&lt;0..10&gt;; /* variable length */ } V1; ...
1
2010-03-31T19:01:08Z
2,566,727
<p>Two suggestions:</p> <ol> <li>For the variable length structure use a fixed format and just slice the result.</li> <li>Use struct.Struct</li> </ol> <p>e.g. If I've understood your formats correctly (is the length byte that appeared in your example but wasn't mentioned originally present in the other variant also?)...
0
2010-04-02T12:56:38Z
[ "python", "serialization", "binary" ]
Right way to create [self]respawning app in python
2,555,857
<p>I am using jabber bot written in python to log some MUC talks. Sometimes it drops on some network or XMPP problems. In this case I have to start it again by myself. The goal is to make it "self-respawning".</p> <p>I have some variants about how to do it.</p> <ol> <li>Bot is one process. Another process monitors it...
2
2010-03-31T19:26:08Z
2,556,336
<p>If you're using something like ubuntu, try looking into <a href="http://upstart.ubuntu.com" rel="nofollow">upstart</a> and its automatic daemonization and "respawn" feature. Here's a good <a href="http://dustin.github.com/2010/02/28/running-processes.html" rel="nofollow">general blogpost about running vs. starting p...
4
2010-03-31T20:43:59Z
[ "python", "daemon", "xmpp", "spawn" ]
Python dealing with dates and times
2,555,904
<p>I'm looking for a solution to the following:</p> <p>Given today's date, figure out what month was before. So 2 should return for today, since it is currently March, the third month of the year. 12 should return for January.</p> <p>Then based on that, I need to be able to iterate through a directory and find all fi...
4
2010-03-31T19:32:08Z
2,555,960
<p>Simplest, where <code>adate</code> is an instance of <code>datetime.date</code>:</p> <pre><code>def previousmonth(adate): m = adate.month - 1 return m if m else 12 </code></pre> <p>There's no real way in most Unix filesystems to determine when a file was created, as they just don't keep that information ar...
3
2010-03-31T19:40:42Z
[ "python", "datetime" ]
Python dealing with dates and times
2,555,904
<p>I'm looking for a solution to the following:</p> <p>Given today's date, figure out what month was before. So 2 should return for today, since it is currently March, the third month of the year. 12 should return for January.</p> <p>Then based on that, I need to be able to iterate through a directory and find all fi...
4
2010-03-31T19:32:08Z
2,555,961
<p><a href="http://docs.python.org/library/datetime.html" rel="nofollow">http://docs.python.org/library/datetime.html</a></p> <p>First of the previous month from a date</p> <pre><code>def first_of( today ) yr_mn = today.year*12 + (today.month-1) - 1 return datetime.date( year= yr_mn//12, month= yr_mn%12+1, da...
0
2010-03-31T19:40:44Z
[ "python", "datetime" ]
Python dealing with dates and times
2,555,904
<p>I'm looking for a solution to the following:</p> <p>Given today's date, figure out what month was before. So 2 should return for today, since it is currently March, the third month of the year. 12 should return for January.</p> <p>Then based on that, I need to be able to iterate through a directory and find all fi...
4
2010-03-31T19:32:08Z
2,555,967
<p>There are several parts being asked about here...</p> <ul> <li><p>You can get the current month by using <code>datetime</code> as so: <code>datetime.datetime.now().month</code>. From there you can just subtract one and turn 0 into 12. Python datetime doc: <a href="http://docs.python.org/library/datetime.html" re...
1
2010-03-31T19:41:55Z
[ "python", "datetime" ]
Python dealing with dates and times
2,555,904
<p>I'm looking for a solution to the following:</p> <p>Given today's date, figure out what month was before. So 2 should return for today, since it is currently March, the third month of the year. 12 should return for January.</p> <p>Then based on that, I need to be able to iterate through a directory and find all fi...
4
2010-03-31T19:32:08Z
2,555,980
<p>It's fairly easy to find the previous month - see, for example, Alex Martelli's answer - but to find the most recently created file in that month is a bit harder:</p> <pre><code>from datetime import date import os def filesLastMonth(directory): """ Given a directory, returns a tuple containing 1. A lis...
2
2010-03-31T19:43:52Z
[ "python", "datetime" ]
Python dealing with dates and times
2,555,904
<p>I'm looking for a solution to the following:</p> <p>Given today's date, figure out what month was before. So 2 should return for today, since it is currently March, the third month of the year. 12 should return for January.</p> <p>Then based on that, I need to be able to iterate through a directory and find all fi...
4
2010-03-31T19:32:08Z
2,557,786
<p>Date manipulation is made trivial with a library like Labix's python-dateutil.</p> <p>You want to do something like this:</p> <pre><code>In [8]: from dateutil.relativedelta import relativedelta In [9]: from datetime import date In [10]: d = date(2010,2,12) In [11]: print (d-relativedelta(months=1)).month 1 In ...
0
2010-04-01T02:28:48Z
[ "python", "datetime" ]
how to get internet explorer address bar for python
2,555,905
<p>i need grab to internet explorer address bar. how to get address bar url for python ? (i need second part other browsers grabbing address bar but internet explorer is urgently).</p> <p>Thanks.</p>
1
2010-03-31T19:32:09Z
2,555,974
<p>Would something like this not work?</p> <pre><code>import win32gui def get_current_window_title(): cur_hwnd = win32gui.GetForegroundWindow() win_title = win32gui.GetWindowText(cur_hwnd) return win_title </code></pre>
1
2010-03-31T19:43:08Z
[ "python", "internet-explorer", "pywin32" ]
how to get internet explorer address bar for python
2,555,905
<p>i need grab to internet explorer address bar. how to get address bar url for python ? (i need second part other browsers grabbing address bar but internet explorer is urgently).</p> <p>Thanks.</p>
1
2010-03-31T19:32:09Z
2,559,279
<p>The following works for me.</p> <pre><code>from win32com.client import Dispatch SHELL = Dispatch("Shell.Application") def get_ie(shell): for win in shell.Windows(): if win.Name == "Windows Internet Explorer": return win return None def main(): ie = get_ie(SHELL) if ie: ...
3
2010-04-01T09:11:10Z
[ "python", "internet-explorer", "pywin32" ]
How to replace the last occurence of an expression in a string
2,556,108
<p>Is there a quick way in Python to replace strings by starting from the end? For example:</p> <pre><code>&gt;&gt;&gt; def rreplace(old, new, occurence) &gt;&gt;&gt; ... # Code to replace the last occurences of old by new &gt;&gt;&gt; '&lt;div&gt;&lt;div&gt;Hello&lt;/div&gt;&lt;/div&gt;'.rreplace('&lt;/div&gt;',...
49
2010-03-31T20:07:23Z
2,556,156
<p>I'm not going to pretend that this is the most efficient way of doing it, but it's a simple way. It reverses all the strings in question, performs an ordinary replacement using <code>str.replace</code> on the reversed strings, then reverses the result back the right way round:</p> <pre><code>&gt;&gt;&gt; def rrepla...
5
2010-03-31T20:16:14Z
[ "python" ]
How to replace the last occurence of an expression in a string
2,556,108
<p>Is there a quick way in Python to replace strings by starting from the end? For example:</p> <pre><code>&gt;&gt;&gt; def rreplace(old, new, occurence) &gt;&gt;&gt; ... # Code to replace the last occurences of old by new &gt;&gt;&gt; '&lt;div&gt;&lt;div&gt;Hello&lt;/div&gt;&lt;/div&gt;'.rreplace('&lt;/div&gt;',...
49
2010-03-31T20:07:23Z
2,556,252
<pre><code>&gt;&gt;&gt; def rreplace(s, old, new, occurrence): ... li = s.rsplit(old, occurrence) ... return new.join(li) ... &gt;&gt;&gt; s '1232425' &gt;&gt;&gt; rreplace(s, '2', ' ', 2) '123 4 5' &gt;&gt;&gt; rreplace(s, '2', ' ', 3) '1 3 4 5' &gt;&gt;&gt; rreplace(s, '2', ' ', 4) '1 3 4 5' &gt;&gt;&gt; rreplace(...
84
2010-03-31T20:29:35Z
[ "python" ]
How to replace the last occurence of an expression in a string
2,556,108
<p>Is there a quick way in Python to replace strings by starting from the end? For example:</p> <pre><code>&gt;&gt;&gt; def rreplace(old, new, occurence) &gt;&gt;&gt; ... # Code to replace the last occurences of old by new &gt;&gt;&gt; '&lt;div&gt;&lt;div&gt;Hello&lt;/div&gt;&lt;/div&gt;'.rreplace('&lt;/div&gt;',...
49
2010-03-31T20:07:23Z
2,556,593
<p>Here is a recursive solution to the problem:</p> <pre><code>def rreplace(s, old, new, occurence = 1): if occurence == 0: return s left, found, right = s.rpartition(old) if found == "": return right else: return rreplace(left, old, new, occurence - 1) + new + right </code><...
1
2010-03-31T21:26:42Z
[ "python" ]
How to replace the last occurence of an expression in a string
2,556,108
<p>Is there a quick way in Python to replace strings by starting from the end? For example:</p> <pre><code>&gt;&gt;&gt; def rreplace(old, new, occurence) &gt;&gt;&gt; ... # Code to replace the last occurences of old by new &gt;&gt;&gt; '&lt;div&gt;&lt;div&gt;Hello&lt;/div&gt;&lt;/div&gt;'.rreplace('&lt;/div&gt;',...
49
2010-03-31T20:07:23Z
12,517,323
<p>If you know that the 'old' string does not contain any special characters you can do it with a regex:</p> <pre><code>In [44]: s = '&lt;div&gt;&lt;div&gt;Hello&lt;/div&gt;&lt;/div&gt;' In [45]: import re In [46]: re.sub(r'(.*)&lt;/div&gt;', r'\1&lt;/bad&gt;', s) Out[46]: '&lt;div&gt;&lt;div&gt;Hello&lt;/div&gt;&lt...
2
2012-09-20T16:57:22Z
[ "python" ]
Why does setting this member in C fail?
2,556,172
<p>I'm writing a Python wrapper for a C++ library, and I'm getting a <em>really</em> weird when trying to set a struct's field in C. If I have a struct like this:</p> <pre><code>struct Thing { PyOBJECT_HEAD unsigned int val; }; </code></pre> <p>And have two functions like this:</p> <pre><code>static PyObjec...
2
2010-03-31T20:18:33Z
2,556,200
<p>Shouldn't it be:</p> <pre><code>if (on) self-&gt;val |= mask; else self-&gt;val &amp;= ~mask; </code></pre>
1
2010-03-31T20:22:18Z
[ "python", "c" ]
Why does setting this member in C fail?
2,556,172
<p>I'm writing a Python wrapper for a C++ library, and I'm getting a <em>really</em> weird when trying to set a struct's field in C. If I have a struct like this:</p> <pre><code>struct Thing { PyOBJECT_HEAD unsigned int val; }; </code></pre> <p>And have two functions like this:</p> <pre><code>static PyObjec...
2
2010-03-31T20:18:33Z
2,556,249
<p>Is it possible that passing the address of a bool PyArg_ParseTuple is causing your trouble? The "i" format will write an int sized thing.</p> <p>What kind of machine are you running on?</p>
3
2010-03-31T20:29:13Z
[ "python", "c" ]
How to send mail in hotmail using Python?
2,556,533
<p>Is there a way to login my hotmail account and send mails with a Python program?</p>
3
2010-03-31T21:17:15Z
2,556,693
<p>You can try using their <a href="http://techblissonline.com/hotmail-pop3-and-smtp-settings/" rel="nofollow">SMTP server</a>:</p> <ul> <li>User name: Your Windows Live ID, for example yourname@hotmail.com</li> <li>Password: The password you usually use to sign in to Hotmail or Windows Live</li> <li>SMTP server: smtp...
2
2010-03-31T21:45:46Z
[ "python", "hotmail" ]
What does represent the hexadecimal integer showed on print/repr in Python?
2,556,799
<p>In an interactive session like the following one:</p> <pre><code>&gt;&gt;&gt; f=open('test.txt','w') &gt;&gt;&gt; f &lt;open file 'test.txt', mode 'w' at 0x6e610&gt; </code></pre> <p>what does <strong>0x6e610</strong> represent and what could I do with that hexadecimal number in Python?</p>
1
2010-03-31T22:04:48Z
2,556,809
<p>It's the ID of the object, which (in standard Python) is its address in memory.</p> <p>You can also get it via the <code>id(obj)</code> function.</p> <p>You can use IDs to tell whether two references refer to the same object - when you say <code>if x is y</code> in Python, you're comparing IDs.</p>
3
2010-03-31T22:06:06Z
[ "python", "core" ]
What does represent the hexadecimal integer showed on print/repr in Python?
2,556,799
<p>In an interactive session like the following one:</p> <pre><code>&gt;&gt;&gt; f=open('test.txt','w') &gt;&gt;&gt; f &lt;open file 'test.txt', mode 'w' at 0x6e610&gt; </code></pre> <p>what does <strong>0x6e610</strong> represent and what could I do with that hexadecimal number in Python?</p>
1
2010-03-31T22:04:48Z
2,556,819
<pre><code>&gt;&gt;&gt; f=open('test.txt') &gt;&gt;&gt; f &lt;open file 'test.txt', mode 'r' at 0x10047c938&gt; &gt;&gt;&gt; hex(id(f)) '0x10047c938' </code></pre> <p>Have a look at <a href="http://docs.python.org/library/functions.html#id" rel="nofollow">id in the official documentation</a>:</p> <p><em>Return the â€...
5
2010-03-31T22:07:44Z
[ "python", "core" ]
sqlite & python - only pulls the first result
2,556,849
<p>This is pretty strange (admitedly, this is my first attempt with python / sqlite), but I can seem to get all of the rows if I do a <em>fetchAll()</em>, but other than that - no matter what I try, always ends up in the db only returning the first row - the second iteration stops because a null is returned. Wondering ...
2
2010-03-31T22:13:34Z
2,556,865
<p>You are reusing the same cursor to execute two different queries. Try using two different cursors and see if that solves your problem.</p>
4
2010-03-31T22:17:38Z
[ "python", "sqlite" ]
sqlite & python - only pulls the first result
2,556,849
<p>This is pretty strange (admitedly, this is my first attempt with python / sqlite), but I can seem to get all of the rows if I do a <em>fetchAll()</em>, but other than that - no matter what I try, always ends up in the db only returning the first row - the second iteration stops because a null is returned. Wondering ...
2
2010-03-31T22:13:34Z
2,556,890
<p>If I'm not mistaken, the second time you call execute on a Cursor, the result of the previous call is discarded.</p> <p>That's why you can use fetchall, because that returns all the results, before you call execute again.</p> <p>For the update, use a second Cursor, to avoid invalidating the results on the first.</...
2
2010-03-31T22:21:54Z
[ "python", "sqlite" ]
What to put in a python module docstring?
2,557,110
<p>Ok, so I've read both <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> and <a href="http://www.python.org/dev/peps/pep-0257/">PEP 257</a>, and I've written lots of docstrings for functions and classes, but I'm a little unsure about what should go in a module docstring. I figured, at a minimum, it should...
65
2010-03-31T23:04:34Z
2,557,196
<p>Think about somebody doing <code>help(yourmodule)</code> at the interactive interpreter's prompt -- what do they <strong>want</strong> to know? (Other methods of extracting and displaying the information are roughly equivalent to <code>help</code> in terms of amount of information). So if you have in <code>x.py</c...
75
2010-03-31T23:28:02Z
[ "python", "documentation", "module" ]
What to put in a python module docstring?
2,557,110
<p>Ok, so I've read both <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> and <a href="http://www.python.org/dev/peps/pep-0257/">PEP 257</a>, and I've written lots of docstrings for functions and classes, but I'm a little unsure about what should go in a module docstring. I figured, at a minimum, it should...
65
2010-03-31T23:04:34Z
7,373,383
<p>To quote the <a href="http://www.python.org/dev/peps/pep-0257/#multi-line-docstrings">specifications</a>:</p> <blockquote> <p>The docstring of a <b>script</b> (a stand-alone program) should be usable as its "usage" message, printed when the script is invoked with incorrect or missing arguments (or perhaps with ...
21
2011-09-10T17:30:14Z
[ "python", "documentation", "module" ]
How do I change the default format of log messages in python app engine?
2,557,168
<p>I would like to log the module and classname by default in log messages from my request handlers.</p> <p>The usual way to do this seems to be to set a custom format string by calling <code>logging.basicConfig</code>, but this can only be called once and has already been called by the time my code runs.</p> <p>Anot...
6
2010-03-31T23:21:20Z
2,557,316
<p>I cooked this up by reading the <code>logging</code> module's <code>__init__.py</code>. I don't know if this is proper, but it seems to work:</p> <pre><code>import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', ...
6
2010-04-01T00:02:41Z
[ "python", "google-app-engine", "logging" ]
Exposing python api over the network for an iphone application
2,557,179
<p>I have functionality built in python on a central server. I wish to expose this api over the network to an iphone application. What would be the best way to do that?</p> <p>Is it possible to create web services in python and have the iphone app use those? If so could anyone give me pointers as to how to create web ...
3
2010-03-31T23:22:33Z
2,557,212
<p>Simplest is <a href="http://docs.python.org/library/xmlrpclib.html?highlight=xmlrpclib#module-xmlrpclib" rel="nofollow">xmlrpclib</a>, if the app you want to consume this service can speak XML-RPC.</p> <p>According to <a href="http://stackoverflow.com/questions/147062/does-iphone-support-xml-rpc">this SO question</...
2
2010-03-31T23:32:06Z
[ "iphone", "python", "web-services" ]
Exposing python api over the network for an iphone application
2,557,179
<p>I have functionality built in python on a central server. I wish to expose this api over the network to an iphone application. What would be the best way to do that?</p> <p>Is it possible to create web services in python and have the iphone app use those? If so could anyone give me pointers as to how to create web ...
3
2010-03-31T23:22:33Z
2,557,296
<p>Look at using a REST style web service for that. I am currently working on an iPhone app that uses a Pylons based web service that the app uses to fetch JSON encoded data. So far it works like a charm.</p> <p>I'm not sure what library or framework you are using, but here is a little information on Pylons REST contr...
1
2010-03-31T23:57:33Z
[ "iphone", "python", "web-services" ]
python dict.fromkeys() returns empty
2,557,193
<p>I wrote the following function. It returns an empty dictionary when it should not. The code works on the command line without function. However I cannot see what is wrong with the function, so I have to appeal to your collective intelligence.</p> <pre><code>def enter_users_into_dict(userlist): newusr = {} n...
2
2010-03-31T23:27:09Z
2,557,201
<p>You need to collapse the function's body to</p> <pre><code>def enter_users_into_dict(userlist): return dict.fromkeys(userlist, 0) </code></pre> <p><code>fromkeys</code> is a class method, thus doesn't affect any instance it may be called on (it's best to call it on the class -- that's clearer!), rather it <str...
3
2010-03-31T23:29:36Z
[ "python", "dictionary", "fromkeys" ]
python dict.fromkeys() returns empty
2,557,193
<p>I wrote the following function. It returns an empty dictionary when it should not. The code works on the command line without function. However I cannot see what is wrong with the function, so I have to appeal to your collective intelligence.</p> <pre><code>def enter_users_into_dict(userlist): newusr = {} n...
2
2010-03-31T23:27:09Z
2,557,202
<p>fromkeys is a class method, meaning</p> <pre><code>newusr.fromkeys(userlist, 0) </code></pre> <p>is exactly the same as calling</p> <pre><code>dict.fromkeys(userlist, 0) </code></pre> <p>Both which <em>return</em> a dictionary of the keys in userlist. You need to assign it to something. Try this instead.</p> <p...
11
2010-03-31T23:30:05Z
[ "python", "dictionary", "fromkeys" ]
python dict.fromkeys() returns empty
2,557,193
<p>I wrote the following function. It returns an empty dictionary when it should not. The code works on the command line without function. However I cannot see what is wrong with the function, so I have to appeal to your collective intelligence.</p> <pre><code>def enter_users_into_dict(userlist): newusr = {} n...
2
2010-03-31T23:27:09Z
2,557,203
<p>It should be:</p> <pre><code>def enter_users_into_dict(userlist): return dict.fromkeys(userlist, 0) </code></pre> <p>From the <a href="http://docs.python.org/library/stdtypes.html#dict.fromkeys" rel="nofollow">documentation</a>:</p> <blockquote> <p><code>fromkeys()</code> is a <strong>class method</strong>...
2
2010-03-31T23:30:10Z
[ "python", "dictionary", "fromkeys" ]
delete Task / PeriodicTask in celery
2,557,424
<p>How can I delete a regular Task or PeriodicTask in celery?</p>
8
2010-04-01T00:30:08Z
2,558,783
<p>You <code>revoke</code> the task: See <a href="http://docs.celeryproject.org/en/latest/reference/celery.app.control.html#celery.app.control.Control.revoke" rel="nofollow">documentation</a>:</p> <pre><code>Control.revoke(task_id, destination=None, terminate=False, signal='SIGTERM', **kwargs) Tell all (or specifi...
15
2010-04-01T07:23:25Z
[ "python", "rabbitmq", "celery" ]
What is a good SOAP client library for python on App Engine?
2,557,461
<p>I have read that SUDS doesn't work on App Engine. <a href="http://osdir.com/ml/fedora-suds-list/2010-03/msg00004.html" rel="nofollow">http://osdir.com/ml/fedora-suds-list/2010-03/msg00004.html</a></p> <p>Can anyone confirm or refute this? Can you suggest an alternative for calling SOAP services from App Engine's p...
6
2010-04-01T00:40:41Z
2,557,707
<p>Have you tried <a href="http://effbot.org/downloads/#elementsoap" rel="nofollow">ElementSoap</a>? It seems like a good option.</p>
3
2010-04-01T01:56:52Z
[ "python", "google-app-engine", "soap" ]
What is a good SOAP client library for python on App Engine?
2,557,461
<p>I have read that SUDS doesn't work on App Engine. <a href="http://osdir.com/ml/fedora-suds-list/2010-03/msg00004.html" rel="nofollow">http://osdir.com/ml/fedora-suds-list/2010-03/msg00004.html</a></p> <p>Can anyone confirm or refute this? Can you suggest an alternative for calling SOAP services from App Engine's p...
6
2010-04-01T00:40:41Z
2,752,998
<p><a href="http://code.google.com/p/google-api-adwords-python-lib/" rel="nofollow">http://code.google.com/p/google-api-adwords-python-lib/</a> This is a soap library from Google. I have not had time to test it,</p>
1
2010-05-02T09:33:01Z
[ "python", "google-app-engine", "soap" ]
When I run Django on Dreamhost using SQLite, why do I get an OperationalError telling me that a table doesn’t exist?
2,557,710
<p>I had a Django site running on Dreamhost. Although I used SQLite when developing locally, I initially used MySQL on Dreamhost, because that’s what <a href="http://wiki.dreamhost.com/Django" rel="nofollow">the wiki page</a> said to do, and because if I’m using an ORM, I might as well take advantage of it by runni...
0
2010-04-01T01:57:51Z
2,557,711
<p>It turned out that on the server, the <code>DATABASE_NAME</code> setting required a full path, e.g.</p> <pre><code>DATABASE_NAME = '/home/USERNAME/SITE/DJANGOPROJECT/DATABASE.db' </code></pre> <p>Locally (and I guess for manage.py on the server), just a filename was fine, e.g.</p> <pre><code>DATABASE_NAME = 'DATA...
1
2010-04-01T01:59:33Z
[ "python", "django", "sqlite", "dreamhost" ]
Search and get a line in Python
2,557,808
<p>Is there a way to search, from a string, a line containing another string and retrieve the entire line?</p> <p>For example:</p> <pre><code>string = qwertyuiop asdfghjkl zxcvbnm token qwerty asdfghjklñ retrieve_line("token") = "token qwerty" </code></pre>
8
2010-04-01T02:39:10Z
2,557,824
<p>With regular expressions</p> <pre><code>import re s=""" qwertyuiop asdfghjkl zxcvbnm token qwerty asdfghjklñ """ &gt;&gt;&gt; items=re.findall("token.*$",s,re.MULTILINE) &gt;&gt;&gt; for x in items: ... print x ... token qwerty </code></pre>
3
2010-04-01T02:42:50Z
[ "python", "string", "search", "line" ]
Search and get a line in Python
2,557,808
<p>Is there a way to search, from a string, a line containing another string and retrieve the entire line?</p> <p>For example:</p> <pre><code>string = qwertyuiop asdfghjkl zxcvbnm token qwerty asdfghjklñ retrieve_line("token") = "token qwerty" </code></pre>
8
2010-04-01T02:39:10Z
2,557,837
<p>you mentioned "entire line" , so i assumed mystring is the entire line.</p> <pre><code>if "token" in mystring: print mystring </code></pre> <p>however if you want to just get "token qwerty",</p> <pre><code>&gt;&gt;&gt; mystring=""" ... qwertyuiop ... asdfghjkl ... ... zxcvbnm ... token qwerty ...
13
2010-04-01T02:45:57Z
[ "python", "string", "search", "line" ]
Search and get a line in Python
2,557,808
<p>Is there a way to search, from a string, a line containing another string and retrieve the entire line?</p> <p>For example:</p> <pre><code>string = qwertyuiop asdfghjkl zxcvbnm token qwerty asdfghjklñ retrieve_line("token") = "token qwerty" </code></pre>
8
2010-04-01T02:39:10Z
2,557,946
<p>If you prefer a one-liner:</p> <pre><code>matched_lines = [line for line in my_string.split('\n') if "substring" in line] </code></pre>
5
2010-04-01T03:17:08Z
[ "python", "string", "search", "line" ]
Search and get a line in Python
2,557,808
<p>Is there a way to search, from a string, a line containing another string and retrieve the entire line?</p> <p>For example:</p> <pre><code>string = qwertyuiop asdfghjkl zxcvbnm token qwerty asdfghjklñ retrieve_line("token") = "token qwerty" </code></pre>
8
2010-04-01T02:39:10Z
40,072,228
<pre><code>items=re.findall("token.*$",s,re.MULTILINE) &gt;&gt;&gt; for x in items: </code></pre> <p>you can also get the line if there are other characters before token</p> <pre><code>items=re.findall("^.*token.*$",s,re.MULTILINE) </code></pre> <p>The above works like grep token on unix and keyword 'in' or .contain...
0
2016-10-16T15:54:34Z
[ "python", "string", "search", "line" ]
Please explain this python behavior
2,557,891
<pre><code>class SomeClass(object): def __init__(self, key_text_pairs = None): ..... for key, text in key_text_pairs: ...... ...... x = SomeClass([(1, "abc",), (2, "fff",)]) </code></pre> <p>The value of key_text_pairs inside the <strong>init</strong> is None even if I pass...
2
2010-04-01T03:00:54Z
2,557,905
<p>So just looking at that code, is what you posted exactly what you want? Specifically, if you're passing in a list that looks like:</p> <p><code>[1, 2, 3]</code></p> <p>Then I don't think you want to try to extract it like this:</p> <p><code>for key, text in key_text_pairs</code></p> <p>You can extract a list of...
0
2010-04-01T03:06:16Z
[ "python", "initialization" ]
Please explain this python behavior
2,557,891
<pre><code>class SomeClass(object): def __init__(self, key_text_pairs = None): ..... for key, text in key_text_pairs: ...... ...... x = SomeClass([(1, "abc",), (2, "fff",)]) </code></pre> <p>The value of key_text_pairs inside the <strong>init</strong> is None even if I pass...
2
2010-04-01T03:00:54Z
2,557,911
<p>Could you post a traceback?</p> <p>This is what I get when I run the code:</p> <pre><code>In [1]: class SomeClass(object): ...: def __init__(self, key_text_pairs = None): ...: for key, text in key_text_pairs: ...: print "key:", key, "text", text ...: ...: ...
0
2010-04-01T03:06:42Z
[ "python", "initialization" ]
Please explain this python behavior
2,557,891
<pre><code>class SomeClass(object): def __init__(self, key_text_pairs = None): ..... for key, text in key_text_pairs: ...... ...... x = SomeClass([(1, "abc",), (2, "fff",)]) </code></pre> <p>The value of key_text_pairs inside the <strong>init</strong> is None even if I pass...
2
2010-04-01T03:00:54Z
2,557,912
<p>First of all, when you say <code>for key, text in key_text_pairs</code>, you are implying that the list has tuples. I tested your code exactly the way it is and that's what happened.</p> <p>Change <code>x = SomeClass([1, 2, 3])</code> to <code>x = SomeClass([(1, 1.0), (2, 2.0), (3, 3.0)])</code> and see if that hel...
2
2010-04-01T03:06:50Z
[ "python", "initialization" ]
How can I parse HTML with html5lib, and query the parsed HTML with XPath?
2,558,056
<p>I am trying to use html5lib to parse an html page in to something I can query with xpath. html5lib has close to zero documentation and I've spent too much time trying to figure this problem out. Ultimate goal is to pull out the second row of a table:</p> <pre><code>&lt;html&gt; &lt;table&gt; &lt;tr&gt;&...
12
2010-04-01T04:04:03Z
2,558,126
<p>try using jquery. and you can retrieve all elements. alternately, you can put an id on your row and pull it out.</p> <p>1) ... ... </p> <p>$("td")[1].innerHTML will be what you want</p> <p>2) ... ... </p> <p>$("#blah").text() will be what you want</p>
-3
2010-04-01T04:30:37Z
[ "python", "parsing", "xpath", "lxml", "html5lib" ]
How can I parse HTML with html5lib, and query the parsed HTML with XPath?
2,558,056
<p>I am trying to use html5lib to parse an html page in to something I can query with xpath. html5lib has close to zero documentation and I've spent too much time trying to figure this problem out. Ultimate goal is to pull out the second row of a table:</p> <pre><code>&lt;html&gt; &lt;table&gt; &lt;tr&gt;&...
12
2010-04-01T04:04:03Z
2,558,137
<p>i believe you can do css search on lxml objects.. like so</p> <pre><code>elements = root.cssselect('div.content') data = elements[0].text </code></pre>
1
2010-04-01T04:33:36Z
[ "python", "parsing", "xpath", "lxml", "html5lib" ]
How can I parse HTML with html5lib, and query the parsed HTML with XPath?
2,558,056
<p>I am trying to use html5lib to parse an html page in to something I can query with xpath. html5lib has close to zero documentation and I've spent too much time trying to figure this problem out. Ultimate goal is to pull out the second row of a table:</p> <pre><code>&lt;html&gt; &lt;table&gt; &lt;tr&gt;&...
12
2010-04-01T04:04:03Z
2,558,147
<p>With <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a>, you can do that with <br /></p> <pre><code>&gt;&gt;&gt; soup = BeautifulSoup.BeautifulSoup('&lt;html&gt;&lt;table&gt;&lt;tr&gt;&lt;td&gt;Header&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;Want This&lt;/td&gt;&lt;/tr&gt;&lt;/...
2
2010-04-01T04:36:17Z
[ "python", "parsing", "xpath", "lxml", "html5lib" ]
How can I parse HTML with html5lib, and query the parsed HTML with XPath?
2,558,056
<p>I am trying to use html5lib to parse an html page in to something I can query with xpath. html5lib has close to zero documentation and I've spent too much time trying to figure this problem out. Ultimate goal is to pull out the second row of a table:</p> <pre><code>&lt;html&gt; &lt;table&gt; &lt;tr&gt;&...
12
2010-04-01T04:04:03Z
2,558,254
<p>Lack of documentation is a good reason to avoid a library IMO, no matter how cool it is. Are you wedded to using html5lib? Have you looked at <a href="http://lxml.de/lxmlhtml.html" rel="nofollow">lxml.html</a>?</p> <p>Here is a way to do this with lxml:</p> <pre><code>from lxml import html tree = html.fromstring(t...
19
2010-04-01T05:13:30Z
[ "python", "parsing", "xpath", "lxml", "html5lib" ]
How can I parse HTML with html5lib, and query the parsed HTML with XPath?
2,558,056
<p>I am trying to use html5lib to parse an html page in to something I can query with xpath. html5lib has close to zero documentation and I've spent too much time trying to figure this problem out. Ultimate goal is to pull out the second row of a table:</p> <pre><code>&lt;html&gt; &lt;table&gt; &lt;tr&gt;&...
12
2010-04-01T04:04:03Z
2,558,275
<p>I always recommend to try out <code>lxml</code> library. It's blazingly fast and has many features.</p> <p>It has also support for html5lib parser if you need that: <a href="http://codespeak.net/lxml/dev/html5parser.html" rel="nofollow">html5parser</a></p> <pre><code>&gt;&gt;&gt; from lxml.html import fromstring, ...
4
2010-04-01T05:17:53Z
[ "python", "parsing", "xpath", "lxml", "html5lib" ]
How can I parse HTML with html5lib, and query the parsed HTML with XPath?
2,558,056
<p>I am trying to use html5lib to parse an html page in to something I can query with xpath. html5lib has close to zero documentation and I've spent too much time trying to figure this problem out. Ultimate goal is to pull out the second row of a table:</p> <pre><code>&lt;html&gt; &lt;table&gt; &lt;tr&gt;&...
12
2010-04-01T04:04:03Z
5,073,316
<p>What you want to use is the <code>namespaceHTMLElements</code> argument, which for some reason defaults to True.</p> <pre><code>doc = html5lib.parse('''&lt;html&gt; &lt;table&gt; &lt;tr&gt;&lt;td&gt;Header&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Want This&lt;/td&gt;&lt;/tr&gt; &lt;/table&g...
15
2011-02-22T02:03:29Z
[ "python", "parsing", "xpath", "lxml", "html5lib" ]
How can I get the expire time for the particular item in memcached
2,558,706
<p>In runtime, I want to retrieve the expire time info about some items in memcached. I didn't find any related interface on memcached. Can I do this? something like: mc.get_expire_time('key')</p> <p>Thank you</p>
6
2010-04-01T07:10:35Z
2,560,268
<p>According to memcache protocol (both <a href="http://code.sixapart.com/svn/memcached/trunk/server/doc/protocol.txt" rel="nofollow">text</a> and <a href="http://code.google.com/p/memcached/wiki/MemcacheBinaryProtocol" rel="nofollow">binary</a>) niether <code>get</code> nor <code>gets</code> return expiration time. An...
3
2010-04-01T12:28:43Z
[ "python", "memcached" ]
How can I get the expire time for the particular item in memcached
2,558,706
<p>In runtime, I want to retrieve the expire time info about some items in memcached. I didn't find any related interface on memcached. Can I do this? something like: mc.get_expire_time('key')</p> <p>Thank you</p>
6
2010-04-01T07:10:35Z
9,970,657
<p>Python memcache API doesn't provide such functionalities. However you can telnet into memcached to dump all keys and expiration time.</p> <pre><code>&gt; telnet localhost 11211 </code></pre> <p><code>stats items</code> show the slabs that contain your data.</p> <pre><code>stats items STAT items:12:number 1108 ......
7
2012-04-02T03:45:43Z
[ "python", "memcached" ]
How can I get the expire time for the particular item in memcached
2,558,706
<p>In runtime, I want to retrieve the expire time info about some items in memcached. I didn't find any related interface on memcached. Can I do this? something like: mc.get_expire_time('key')</p> <p>Thank you</p>
6
2010-04-01T07:10:35Z
21,297,866
<p>Annoyingly, this information only seems to be provided in the slab stats. Start with this:</p> <pre><code>[$]&gt; (sleep 1; echo "stats cachedump 1 0"; sleep 1; echo "quit";) | telnet localhost 11211 | grep 'my_key' </code></pre> <p>and increment the slab (the first number after 'cachedump') until you find the ap...
2
2014-01-23T01:56:32Z
[ "python", "memcached" ]
I/O error(socket error): [Errno 111] Connection refused
2,558,801
<p>I have a program that uses urllib to periodically fetch a url, and I see intermittent errors like : </p> <p>I/O error(socket error): [Errno 111] Connection refused. </p> <p>It works 90% of the time, but the othe r10% it fails. If retry the fetch immediately after it fails, it succeeds. I'm unable to figure out why...
12
2010-04-01T07:28:46Z
2,558,927
<p>I'm not exactly sure what's causing this. You can try looking in your socket.py (mine is a different version, so line numbers from the trace don't match, and I'm afraid some other details might not match as well).</p> <p>Anyway, it seems like a good practice to put your url fetching code in a <code>try: ... except:...
2
2010-04-01T07:54:40Z
[ "python", "sockets", "urllib" ]
I/O error(socket error): [Errno 111] Connection refused
2,558,801
<p>I have a program that uses urllib to periodically fetch a url, and I see intermittent errors like : </p> <p>I/O error(socket error): [Errno 111] Connection refused. </p> <p>It works 90% of the time, but the othe r10% it fails. If retry the fetch immediately after it fails, it succeeds. I'm unable to figure out why...
12
2010-04-01T07:28:46Z
2,560,472
<p>Getting an ECONNREFUSED errno means that <em>your</em> kernel was refused a connection at the other end, so if it's a bug, it's either in your kernel or in the other end. What you can do is to trap the error in a very specific way and try again in a little while, since this seems to work:</p> <pre><code># This is P...
10
2010-04-01T13:00:58Z
[ "python", "sockets", "urllib" ]
I/O error(socket error): [Errno 111] Connection refused
2,558,801
<p>I have a program that uses urllib to periodically fetch a url, and I see intermittent errors like : </p> <p>I/O error(socket error): [Errno 111] Connection refused. </p> <p>It works 90% of the time, but the othe r10% it fails. If retry the fetch immediately after it fails, it succeeds. I'm unable to figure out why...
12
2010-04-01T07:28:46Z
2,560,509
<p>Use a packet sniffer like <a href="http://www.wireshark.org/">Wireshark</a> to look at what happens. You need to see a SYN-flagged packet outgoing, a SYN+ACK-flagged incoming and then a ACK-flagged outgoing. After that, the port is considered open on the local side.</p> <p>If you only see the first packet and the e...
32
2010-04-01T13:05:49Z
[ "python", "sockets", "urllib" ]
I/O error(socket error): [Errno 111] Connection refused
2,558,801
<p>I have a program that uses urllib to periodically fetch a url, and I see intermittent errors like : </p> <p>I/O error(socket error): [Errno 111] Connection refused. </p> <p>It works 90% of the time, but the othe r10% it fails. If retry the fetch immediately after it fails, it succeeds. I'm unable to figure out why...
12
2010-04-01T07:28:46Z
9,013,103
<p>I previously had this problem with my EC2 instance (I was serving couchdb to serve resources -- am considering Amazon's S3 for the future).</p> <p>One thing to check (assuming Ec2) is that the couchdb port is added to your open ports within your security policy.</p> <p>I specifically encountered </p> <blockquote>...
3
2012-01-26T01:56:51Z
[ "python", "sockets", "urllib" ]
Python check if object is in list of objects
2,559,083
<p>I have a list of objects in Python. I then have another list of objects. I want to go through the first list and see if any items appear in the second list.</p> <p>I thought I could simply do</p> <pre><code>for item1 in list1: for item2 in list2: if item1 == item2: print "item %s in both ...
11
2010-04-01T08:35:15Z
2,559,098
<p><a href="http://docs.python.org/library/sets.html#set-objects" rel="nofollow">set intersection</a> will do for that.</p> <pre><code>&gt;&gt;&gt; x=[1,2,3,4] &gt;&gt;&gt; y=[3,4,5,6] &gt;&gt;&gt; for i in set(x) &amp; set(y): ... print "item %d in both lists" %i ... item 3 in both lists item 4 in both lists </co...
4
2010-04-01T08:37:49Z
[ "python" ]
Python check if object is in list of objects
2,559,083
<p>I have a list of objects in Python. I then have another list of objects. I want to go through the first list and see if any items appear in the second list.</p> <p>I thought I could simply do</p> <pre><code>for item1 in list1: for item2 in list2: if item1 == item2: print "item %s in both ...
11
2010-04-01T08:35:15Z
2,559,100
<p>In case the objects are not the same instance, you need to implement the <code>__eq__</code> method for python to be able to tell when 2 objects are actually equal. </p> <p>Of course that most library types, such as strings and lists already have <code>__eq__</code> implemented, which may be the reason comparing t...
7
2010-04-01T08:38:19Z
[ "python" ]
Python check if object is in list of objects
2,559,083
<p>I have a list of objects in Python. I then have another list of objects. I want to go through the first list and see if any items appear in the second list.</p> <p>I thought I could simply do</p> <pre><code>for item1 in list1: for item2 in list2: if item1 == item2: print "item %s in both ...
11
2010-04-01T08:35:15Z
2,559,113
<p>Assuming that your object has only a <code>title</code> attribute which is relevant for equality, you have to implement the <code>__eq__</code> method as follows:</p> <pre><code>class YourObject: [...] def __eq__(self, other): return self.title == other.title </code></pre> <p>Of course if you have ...
20
2010-04-01T08:40:54Z
[ "python" ]
Python check if object is in list of objects
2,559,083
<p>I have a list of objects in Python. I then have another list of objects. I want to go through the first list and see if any items appear in the second list.</p> <p>I thought I could simply do</p> <pre><code>for item1 in list1: for item2 in list2: if item1 == item2: print "item %s in both ...
11
2010-04-01T08:35:15Z
2,559,121
<p>Finding objects who appear in both lists:</p> <pre><code>l1 = [1,2,3,4,5] l2 = [3,4,5] common = set(l1).intersection(set(l2)) </code></pre> <p>Combine this with the <code>__eq__</code> implementation on the object as the others suggested.</p>
4
2010-04-01T08:41:59Z
[ "python" ]
Python check if object is in list of objects
2,559,083
<p>I have a list of objects in Python. I then have another list of objects. I want to go through the first list and see if any items appear in the second list.</p> <p>I thought I could simply do</p> <pre><code>for item1 in list1: for item2 in list2: if item1 == item2: print "item %s in both ...
11
2010-04-01T08:35:15Z
2,559,130
<p>Try the following:</p> <pre><code>list1 = [item1, item2, item3] list2 = [item3, item4, item5] for item in list1: if item in list2: print "item %s in both lists" % item </code></pre>
0
2010-04-01T08:43:28Z
[ "python" ]
Python check if object is in list of objects
2,559,083
<p>I have a list of objects in Python. I then have another list of objects. I want to go through the first list and see if any items appear in the second list.</p> <p>I thought I could simply do</p> <pre><code>for item1 in list1: for item2 in list2: if item1 == item2: print "item %s in both ...
11
2010-04-01T08:35:15Z
2,560,300
<pre><code>matches = [x for x in listA if x in listB] </code></pre>
1
2010-04-01T12:35:58Z
[ "python" ]
Python check if object is in list of objects
2,559,083
<p>I have a list of objects in Python. I then have another list of objects. I want to go through the first list and see if any items appear in the second list.</p> <p>I thought I could simply do</p> <pre><code>for item1 in list1: for item2 in list2: if item1 == item2: print "item %s in both ...
11
2010-04-01T08:35:15Z
2,560,667
<p>You need to write an <code>__eq__</code> function to define how to compare objects for equality. If you want sorting, then yo should have a <code>__cmp__</code> function, and it makes the most sense to implement <code>__eq__</code> in terms of <code>__cmp__</code>.</p> <pre><code>def __eq__(self, other): return...
3
2010-04-01T13:31:09Z
[ "python" ]
Accessing a JET (.mdb) database in Python
2,559,659
<p>Is there a way to access a JET database from Python? I'm on Linux. All I found was a .mdb viewer in the repositories, but it's very faulty. Thanks</p>
12
2010-04-01T10:21:59Z
2,559,686
<p>Probably the most simple solution:</p> <ol> <li><p>Download VirtualBox and install Windows and MS access in it.</p></li> <li><p>Write a small Python server which use ODBC to access the database and which receives commands from a network socket.</p></li> <li><p>On Linux, connect to the server in the virtual machine ...
2
2010-04-01T10:28:14Z
[ "python", "database", "jet" ]
Accessing a JET (.mdb) database in Python
2,559,659
<p>Is there a way to access a JET database from Python? I'm on Linux. All I found was a .mdb viewer in the repositories, but it's very faulty. Thanks</p>
12
2010-04-01T10:21:59Z
2,560,552
<p>Install your distribution's packaged version of <a href="http://mdbtools.sourceforge.net/install/" rel="nofollow">mdbtools</a>, use <code>mdb-export</code> to export the Jet data to text files, import the data into a SQLite database, and have a combination of code and data that works in almost any computing environm...
4
2010-04-01T13:12:46Z
[ "python", "database", "jet" ]
Accessing a JET (.mdb) database in Python
2,559,659
<p>Is there a way to access a JET database from Python? I'm on Linux. All I found was a .mdb viewer in the repositories, but it's very faulty. Thanks</p>
12
2010-04-01T10:21:59Z
2,783,311
<p><a href="http://sourceforge.net/projects/mdbtools/">MDB Tools</a> is a set of open source libraries and utilities to facilitate exporting data from MS Access databases (mdb files) without using the Microsoft DLLs. Thus non Windows OSs can read the data. Or, to put it another way, they are reverse engineering the lay...
11
2010-05-06T18:00:17Z
[ "python", "database", "jet" ]
Accessing a JET (.mdb) database in Python
2,559,659
<p>Is there a way to access a JET database from Python? I'm on Linux. All I found was a .mdb viewer in the repositories, but it's very faulty. Thanks</p>
12
2010-04-01T10:21:59Z
9,070,795
<p>If you build the CVS version of mdb-tools, it works rather well. It fixed a lot of issues I had trying to use the one in the repositories related to memo field size. mdb-tools is basically a dead project, but people have still been occasionally contributing code to the CVS. The build in Ubuntu is from 2004 I thin...
0
2012-01-30T21:08:58Z
[ "python", "database", "jet" ]
Why is it that I cannot insert this into Django correctly?
2,559,702
<pre><code>new_thing = MyTable(last_updated=datetime.datetime.now()) new_thing.save() &gt;&gt;&gt;&gt;select * from MyTable\G; last_updated: 2010-04-01 05:26:21 </code></pre> <p>However, in my Python console...this is what it says...</p> <pre><code>&gt;&gt;&gt; print datetime.datetime.now() 2010-04-01 10:26:21.64304...
0
2010-04-01T10:30:55Z
2,559,721
<p>Difference is between your timezone and whatever is set in Django <code>settings.py</code> <code>TIME_ZONE</code>. By default it's 'America/Chicago'.</p>
2
2010-04-01T10:35:00Z
[ "python", "mysql", "database", "django", "time" ]
Why is it that I cannot insert this into Django correctly?
2,559,702
<pre><code>new_thing = MyTable(last_updated=datetime.datetime.now()) new_thing.save() &gt;&gt;&gt;&gt;select * from MyTable\G; last_updated: 2010-04-01 05:26:21 </code></pre> <p>However, in my Python console...this is what it says...</p> <pre><code>&gt;&gt;&gt; print datetime.datetime.now() 2010-04-01 10:26:21.64304...
0
2010-04-01T10:30:55Z
2,559,734
<p>I suspect that Django save the time in DB according to GMT and the ORM give it back to you according to your locale.</p> <p>Tell use what does this code say :</p> <pre><code>print MyTable.objects.all().order_by("-last_updated")[0].get() </code></pre>
1
2010-04-01T10:37:57Z
[ "python", "mysql", "database", "django", "time" ]
Python: win32console import problem
2,559,731
<p>I want to run wexpect (the windows port of pexpect) on my Windows 7 64-bit machine. I am getting the following error: C:\Program Files (x86)\wexpect\build\lib>wexpect.py Traceback (most recent call last): File "C:\Program Files (x86)\wexpect\build\lib\wexpect.py", line 97, in raise ImportError(str(e) + "This ...
0
2010-04-01T10:37:28Z
2,559,741
<p>Install this: <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">http://sourceforge.net/projects/pywin32/</a></p> <p>Edit to add slightly longer explanation: There's a very useful set of Windows-specific Python modules, called <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">PyWin32<...
2
2010-04-01T10:39:21Z
[ "python", "expect", "pexpect" ]
Python - Number of Significant Digits in results of division
2,559,835
<p>Newbie here. I have the following code:</p> <pre><code>myADC = 128 maxVoltage = 5.0 maxADC = 255.0 VoltsPerADC = maxVoltage/maxADC myVolts = myADC * VoltsPerADC print "myADC = {0: &gt;3}".format(myADC) print "VoltsPerADC = {0: &gt;7}".format(VoltsPerADC) print VoltsPerADC print "myVolts = {0: &gt;7}".format(myVol...
3
2010-04-01T10:56:55Z
2,559,851
<p>The precision is determined by the hardware. Python uses hardware floats (actually doubles) for its floats. The implications are discussed in the tutorial: <a href="http://docs.python.org/tutorial/floatingpoint.html">http://docs.python.org/tutorial/floatingpoint.html</a></p> <p>If you want more control over precisi...
6
2010-04-01T10:59:14Z
[ "python", "floating-point", "format", "division", "digits" ]
Python - Number of Significant Digits in results of division
2,559,835
<p>Newbie here. I have the following code:</p> <pre><code>myADC = 128 maxVoltage = 5.0 maxADC = 255.0 VoltsPerADC = maxVoltage/maxADC myVolts = myADC * VoltsPerADC print "myADC = {0: &gt;3}".format(myADC) print "VoltsPerADC = {0: &gt;7}".format(VoltsPerADC) print VoltsPerADC print "myVolts = {0: &gt;7}".format(myVol...
3
2010-04-01T10:56:55Z
2,559,901
<p>In general, if the documentation isn't at python.org, it is not authoritative. If you look at <a href="http://docs.python.org/reference/simple_stmts.html#grammar-token-print_stmt" rel="nofollow">print</a> it will tell you that floating point numbers are first converted to strings and <a href="http://docs.python.org/...
0
2010-04-01T11:07:25Z
[ "python", "floating-point", "format", "division", "digits" ]