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 |
|---|---|---|---|---|---|---|---|---|---|
Shuffling a list of objects in python | 976,882 | <p>I have a list of objects in Python and I want to shuffle them. I thought I could use the <code>random.shuffle</code> method, but this seems to fail when the list is of objects. Is there a method for shuffling object or another way around this?</p>
<pre><code>import random
class a:
foo = "bar"
a1 = a()
a2 = a()
b = [a1,a2]
print random.shuffle(b)
</code></pre>
<p>This will fail.</p>
| 290 | 2009-06-10T16:56:59Z | 21,708,126 | <p>Make sure you are not naming your source file random.py, and that there is not a file in your working directory called random.pyc.. either could cause your program to try and import your local random.py file instead of pythons random module. </p>
| 0 | 2014-02-11T16:59:01Z | [
"python",
"list",
"random",
"shuffle"
] |
Shuffling a list of objects in python | 976,882 | <p>I have a list of objects in Python and I want to shuffle them. I thought I could use the <code>random.shuffle</code> method, but this seems to fail when the list is of objects. Is there a method for shuffling object or another way around this?</p>
<pre><code>import random
class a:
foo = "bar"
a1 = a()
a2 = a()
b = [a1,a2]
print random.shuffle(b)
</code></pre>
<p>This will fail.</p>
| 290 | 2009-06-10T16:56:59Z | 23,711,022 | <p>You can go for this:</p>
<pre><code>>>> A = ['r','a','n','d','o','m']
>>> B = [1,2,3,4,5,6]
>>> import random
>>> random.sample(A+B, len(A+B))
[3, 'r', 4, 'n', 6, 5, 'm', 2, 1, 'a', 'o', 'd']
</code></pre>
<p>if you want to go back to two lists, you then split this long list into two.</p>
| 0 | 2014-05-17T11:53:48Z | [
"python",
"list",
"random",
"shuffle"
] |
Shuffling a list of objects in python | 976,882 | <p>I have a list of objects in Python and I want to shuffle them. I thought I could use the <code>random.shuffle</code> method, but this seems to fail when the list is of objects. Is there a method for shuffling object or another way around this?</p>
<pre><code>import random
class a:
foo = "bar"
a1 = a()
a2 = a()
b = [a1,a2]
print random.shuffle(b)
</code></pre>
<p>This will fail.</p>
| 290 | 2009-06-10T16:56:59Z | 24,464,173 | <p>It works fine. I am trying it here with functions as list objects:</p>
<pre><code> from random import shuffle
def foo1():
print "foo1",
def foo2():
print "foo2",
def foo3():
print "foo3",
A=[foo1,foo2,foo3]
for x in A:
x()
print "\r"
shuffle(A)
for y in A:
y()
</code></pre>
<p>It prints out:
foo1 foo2 foo3
foo2 foo3 foo1
(the foos in the last row have a random order)</p>
| -3 | 2014-06-28T06:11:44Z | [
"python",
"list",
"random",
"shuffle"
] |
Shuffling a list of objects in python | 976,882 | <p>I have a list of objects in Python and I want to shuffle them. I thought I could use the <code>random.shuffle</code> method, but this seems to fail when the list is of objects. Is there a method for shuffling object or another way around this?</p>
<pre><code>import random
class a:
foo = "bar"
a1 = a()
a2 = a()
b = [a1,a2]
print random.shuffle(b)
</code></pre>
<p>This will fail.</p>
| 290 | 2009-06-10T16:56:59Z | 27,064,019 | <p>it took me some time to get that too, but the documentation for shuffle is very clear:</p>
<blockquote>
<p>shuffle list x <strong>in place</strong>; return None.</p>
</blockquote>
<p>so you shouldn't <code>print random.shuffle(b)</code> but <code>random.shuffle(b)</code> and than <code>print b</code>.</p>
| 11 | 2014-11-21T14:49:30Z | [
"python",
"list",
"random",
"shuffle"
] |
Shuffling a list of objects in python | 976,882 | <p>I have a list of objects in Python and I want to shuffle them. I thought I could use the <code>random.shuffle</code> method, but this seems to fail when the list is of objects. Is there a method for shuffling object or another way around this?</p>
<pre><code>import random
class a:
foo = "bar"
a1 = a()
a2 = a()
b = [a1,a2]
print random.shuffle(b)
</code></pre>
<p>This will fail.</p>
| 290 | 2009-06-10T16:56:59Z | 28,777,473 | <p>If you happen to be using numpy already (very popular for scientific and financial applications) you can save yourself an import.</p>
<pre><code>import numpy as np
np.random.shuffle(b)
print(b)
</code></pre>
<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.shuffle.html">http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.shuffle.html</a></p>
| 6 | 2015-02-28T02:35:34Z | [
"python",
"list",
"random",
"shuffle"
] |
Shuffling a list of objects in python | 976,882 | <p>I have a list of objects in Python and I want to shuffle them. I thought I could use the <code>random.shuffle</code> method, but this seems to fail when the list is of objects. Is there a method for shuffling object or another way around this?</p>
<pre><code>import random
class a:
foo = "bar"
a1 = a()
a2 = a()
b = [a1,a2]
print random.shuffle(b)
</code></pre>
<p>This will fail.</p>
| 290 | 2009-06-10T16:56:59Z | 36,850,264 | <p><strong>The shuffling process is "with replacement"</strong>, so the occurrence of each item may change! At least when when items in your list is also list. </p>
<p>E.g.,</p>
<pre><code>ml = [[0], [1]] * 10
</code></pre>
<p>After, </p>
<pre><code>random.shuffle(ml)
</code></pre>
<p>The number of [0] may be 9 or 8, but not exactly 10.</p>
| 0 | 2016-04-25T20:18:27Z | [
"python",
"list",
"random",
"shuffle"
] |
Shuffling a list of objects in python | 976,882 | <p>I have a list of objects in Python and I want to shuffle them. I thought I could use the <code>random.shuffle</code> method, but this seems to fail when the list is of objects. Is there a method for shuffling object or another way around this?</p>
<pre><code>import random
class a:
foo = "bar"
a1 = a()
a2 = a()
b = [a1,a2]
print random.shuffle(b)
</code></pre>
<p>This will fail.</p>
| 290 | 2009-06-10T16:56:59Z | 37,062,184 | <pre><code>from random import random
my_list = range(10)
shuffled_list = sorted(my_list, key=lambda x: random())
</code></pre>
<p>This alternative may be useful for some applications where you want to swap the ordering function.</p>
| 0 | 2016-05-06T00:04:46Z | [
"python",
"list",
"random",
"shuffle"
] |
Shuffling a list of objects in python | 976,882 | <p>I have a list of objects in Python and I want to shuffle them. I thought I could use the <code>random.shuffle</code> method, but this seems to fail when the list is of objects. Is there a method for shuffling object or another way around this?</p>
<pre><code>import random
class a:
foo = "bar"
a1 = a()
a2 = a()
b = [a1,a2]
print random.shuffle(b)
</code></pre>
<p>This will fail.</p>
| 290 | 2009-06-10T16:56:59Z | 37,062,527 | <p>One can define a function called <code>shuffled</code> (in the same sense of <code>sort</code> vs <code>sorted</code>)</p>
<pre><code>def shuffled(x):
import random
y = x[:]
random.shuffle(y)
return y
x = shuffled([1, 2, 3, 4])
print x
</code></pre>
| 1 | 2016-05-06T00:48:25Z | [
"python",
"list",
"random",
"shuffle"
] |
static stylesheets gets reloaded with each post request | 976,898 | <p>Every time there is a post from page the entire bunch of css gets reloaded. Is it possible to tell them not to come in again and again. There is a series of GET that get fired. Can we optimize in some way or is it normal behavior?</p>
<p>The environment is google apps in python.</p>
| 2 | 2009-06-10T17:01:08Z | 976,986 | <p>Check out Using <a href="http://code.google.com/appengine/docs/python/gettingstarted/staticfiles.html" rel="nofollow">Static Files</a> and <a href="http://code.google.com/appengine/docs/python/config/appconfig.html#Static%5FFile%5FHandlers" rel="nofollow">Handlers for Static Files</a>. Since the latter link refer to cache duration of static files, I believe the the caching functionality is possible.</p>
<blockquote>
<p>Unlike a traditional web hosting
environment, Google App Engine does
not serve files directly out of your
application's source directory unless
configured to do so. We named our
template file index.html, but this
does not automatically make the file
available at the URL /index.html.</p>
<p>But there are many cases where you
want to serve static files directly to
the web browser. Images, CSS
stylesheets, JavaScript code, movies
and Flash animations are all typically
stored with a web application and
served directly to the browser. You
can tell App Engine to serve specific
files directly without your having to
code your own handler.</p>
</blockquote>
| 2 | 2009-06-10T17:18:09Z | [
"python",
"css",
"google-app-engine",
"post",
"get"
] |
static stylesheets gets reloaded with each post request | 976,898 | <p>Every time there is a post from page the entire bunch of css gets reloaded. Is it possible to tell them not to come in again and again. There is a series of GET that get fired. Can we optimize in some way or is it normal behavior?</p>
<p>The environment is google apps in python.</p>
| 2 | 2009-06-10T17:01:08Z | 977,488 | <p>You just have to put all your css in a "static directory" and specify an expiration into the app.yaml file.</p>
<p>Here is the app.yaml of one of my project:</p>
<pre><code>application: <my_app_id>
version: 1
runtime: python
api_version: 1
skip_files: |
^(.*/)?(
(app\.yaml)|
(index\.yaml)|
(\..*)|
(.*\.pyc)|
(.*\.bat)|
(.*\.svn/.*)|
(.*\.lnk)|
(datastore/.*)|
(img/src_img/.*)|
)$
handlers:
- url: /favicon\.ico
static_files: img/favicon.ico
upload: img/favicon.ico
expiration: 180d
- url: /img
static_dir: img
expiration: 180d
- url: /static-js
static_dir: static-js
expiration: 180d
- url: .*
script: main.py
</code></pre>
| 0 | 2009-06-10T18:50:39Z | [
"python",
"css",
"google-app-engine",
"post",
"get"
] |
static stylesheets gets reloaded with each post request | 976,898 | <p>Every time there is a post from page the entire bunch of css gets reloaded. Is it possible to tell them not to come in again and again. There is a series of GET that get fired. Can we optimize in some way or is it normal behavior?</p>
<p>The environment is google apps in python.</p>
| 2 | 2009-06-10T17:01:08Z | 978,724 | <p>If your CSS comes from a static file, then as Steve mentioned you want to put it in a static directory and specify it in your app.yaml file. For example, if your CSS files are in a directory called stylesheets:</p>
<pre><code>handlers:
- url: /stylesheets
static_dir: stylesheets
expiration: "180d"
</code></pre>
<p>The critical thing to remember with this is that when you upload a new version of your CSS file, you must change the filename because otherwise, visitors to your site will still be using the old cached version instead of your shiny new one. Simply incrementing a number on the end works well.</p>
<p>If your CSS is dynamically generated, then when the request comes in you want to set the caching in the response object's headers. For example, in your request handler you might have something like this:</p>
<pre><code>class GetCSS(webapp.RequestHandler):
def get(self):
# generate the CSS file here, minify it or whatever
# make the CSS cached for 86400s = 1 day
self.response.headers['Cache-Control'] = 'max-age=86400'
self.response.out.write(your_css)
</code></pre>
| 1 | 2009-06-11T00:07:55Z | [
"python",
"css",
"google-app-engine",
"post",
"get"
] |
During a subprocess call, catch critical windows errors in Python instead of letting the OS handle it by showing nasty error pop-ups | 977,275 | <p>"The application failed to initialize properly ... Click on OK,to terminate the application." is the message from the error pop-up. What is the way to catch these errors in Python code?</p>
| -1 | 2009-06-10T18:08:49Z | 985,166 | <p>Sounds familiar? This will block your <code>subprocess.Popen</code> forever.. until you click the 'OK' button. Add the following code to your module initialization to workaround this issue:</p>
<pre><code>import win32api, win32con
win32api.SetErrorMode(win32con.SEM_FAILCRITICALERRORS |
win32con.SEM_NOOPENFILEERRORBOX)
</code></pre>
| 3 | 2009-06-12T05:35:13Z | [
"python",
"windows",
"subprocess"
] |
How would I go about parsing the following log? | 977,458 | <p>I need to parse a log in the following format:</p>
<pre><code>===== Item 5483/14800 =====
This is the item title
Info: some note
===== Item 5483/14800 (Update 1/3) =====
This is the item title
Info: some other note
===== Item 5483/14800 (Update 2/3) =====
This is the item title
Info: some more notes
===== Item 5483/14800 (Update 3/3) =====
This is the item title
Info: some other note
Test finished. Result Foo. Time 12 secunds.
Stats: CPU 0.5 MEM 5.3
===== Item 5484/14800 =====
This is this items title
Info: some note
Test finished. Result Bar. Time 4 secunds.
Stats: CPU 0.9 MEM 4.7
===== Item 5485/14800 =====
This is the title of this item
Info: some note
Test finished. Result FooBar. Time 7 secunds.
Stats: CPU 2.5 MEM 2.8
</code></pre>
<p>I only need to extract each item's title (next line after ===== Item 5484/14800 =====) and the result.<br />
So i need to keep only the line with the item title and the result for that title and discard everything else.<br />
The issue is that sometimes a item has notes (maxim 3) and sometimes the result is displayed without additional notes so this makes it tricky.<br />
Any help would be appreciated. I'm doing the parser in python but don't need the actual code but some pointing in how could i achive this?</p>
<p>LE: The result I'm looking for is to discard everything else and get something like:</p>
<pre><code>('This is the item title','Foo')
then
('This is this items title','Bar')
</code></pre>
| 2 | 2009-06-10T18:44:15Z | 977,476 | <pre><code>1) Loop through every line in the log
a)If line matches appropriate Regex:
Display/Store Next Line as the item title.
Look for the next line containing "Result
XXXX." and parse out that result for
including in the result set.
</code></pre>
<p>EDIT: added a bit more now that I see the result you're looking for.</p>
| 5 | 2009-06-10T18:48:39Z | [
"python",
"parsing"
] |
How would I go about parsing the following log? | 977,458 | <p>I need to parse a log in the following format:</p>
<pre><code>===== Item 5483/14800 =====
This is the item title
Info: some note
===== Item 5483/14800 (Update 1/3) =====
This is the item title
Info: some other note
===== Item 5483/14800 (Update 2/3) =====
This is the item title
Info: some more notes
===== Item 5483/14800 (Update 3/3) =====
This is the item title
Info: some other note
Test finished. Result Foo. Time 12 secunds.
Stats: CPU 0.5 MEM 5.3
===== Item 5484/14800 =====
This is this items title
Info: some note
Test finished. Result Bar. Time 4 secunds.
Stats: CPU 0.9 MEM 4.7
===== Item 5485/14800 =====
This is the title of this item
Info: some note
Test finished. Result FooBar. Time 7 secunds.
Stats: CPU 2.5 MEM 2.8
</code></pre>
<p>I only need to extract each item's title (next line after ===== Item 5484/14800 =====) and the result.<br />
So i need to keep only the line with the item title and the result for that title and discard everything else.<br />
The issue is that sometimes a item has notes (maxim 3) and sometimes the result is displayed without additional notes so this makes it tricky.<br />
Any help would be appreciated. I'm doing the parser in python but don't need the actual code but some pointing in how could i achive this?</p>
<p>LE: The result I'm looking for is to discard everything else and get something like:</p>
<pre><code>('This is the item title','Foo')
then
('This is this items title','Bar')
</code></pre>
| 2 | 2009-06-10T18:44:15Z | 977,530 | <p>Parsing is not done using regex. If you have a reasonably well structured text (which it looks as you do), you can use faster testing (e.g. line.startswith() or such).
A list of dictionaries seems to be a suitable data type for such key-value pairs. Not sure what else to tell you. This seems pretty trivial.</p>
<p><hr /></p>
<p>OK, so the regexp way proved to be more suitable in this case:</p>
<pre><code>import re
re.findall("=\n(.*)\n", s)
</code></pre>
<p>is faster than list comprehensions</p>
<pre><code>[item.split('\n', 1)[0] for item in s.split('=\n')]
</code></pre>
<p>Here's what I got:</p>
<pre><code>>>> len(s)
337000000
>>> test(get1, s) #list comprehensions
0:00:04.923529
>>> test(get2, s) #re.findall()
0:00:02.737103
</code></pre>
<p>Lesson learned.</p>
| 0 | 2009-06-10T18:58:22Z | [
"python",
"parsing"
] |
How would I go about parsing the following log? | 977,458 | <p>I need to parse a log in the following format:</p>
<pre><code>===== Item 5483/14800 =====
This is the item title
Info: some note
===== Item 5483/14800 (Update 1/3) =====
This is the item title
Info: some other note
===== Item 5483/14800 (Update 2/3) =====
This is the item title
Info: some more notes
===== Item 5483/14800 (Update 3/3) =====
This is the item title
Info: some other note
Test finished. Result Foo. Time 12 secunds.
Stats: CPU 0.5 MEM 5.3
===== Item 5484/14800 =====
This is this items title
Info: some note
Test finished. Result Bar. Time 4 secunds.
Stats: CPU 0.9 MEM 4.7
===== Item 5485/14800 =====
This is the title of this item
Info: some note
Test finished. Result FooBar. Time 7 secunds.
Stats: CPU 2.5 MEM 2.8
</code></pre>
<p>I only need to extract each item's title (next line after ===== Item 5484/14800 =====) and the result.<br />
So i need to keep only the line with the item title and the result for that title and discard everything else.<br />
The issue is that sometimes a item has notes (maxim 3) and sometimes the result is displayed without additional notes so this makes it tricky.<br />
Any help would be appreciated. I'm doing the parser in python but don't need the actual code but some pointing in how could i achive this?</p>
<p>LE: The result I'm looking for is to discard everything else and get something like:</p>
<pre><code>('This is the item title','Foo')
then
('This is this items title','Bar')
</code></pre>
| 2 | 2009-06-10T18:44:15Z | 977,531 | <p>Maybe something like (<code>log.log</code> is your file):</p>
<pre><code>def doOutput(s): # process or store data
print s
s=''
for line in open('log.log').readlines():
if line.startswith('====='):
if len(s):
doOutput(s)
s=''
else:
s+=line
if len(s):
doOutput(s)
</code></pre>
| 1 | 2009-06-10T18:58:38Z | [
"python",
"parsing"
] |
How would I go about parsing the following log? | 977,458 | <p>I need to parse a log in the following format:</p>
<pre><code>===== Item 5483/14800 =====
This is the item title
Info: some note
===== Item 5483/14800 (Update 1/3) =====
This is the item title
Info: some other note
===== Item 5483/14800 (Update 2/3) =====
This is the item title
Info: some more notes
===== Item 5483/14800 (Update 3/3) =====
This is the item title
Info: some other note
Test finished. Result Foo. Time 12 secunds.
Stats: CPU 0.5 MEM 5.3
===== Item 5484/14800 =====
This is this items title
Info: some note
Test finished. Result Bar. Time 4 secunds.
Stats: CPU 0.9 MEM 4.7
===== Item 5485/14800 =====
This is the title of this item
Info: some note
Test finished. Result FooBar. Time 7 secunds.
Stats: CPU 2.5 MEM 2.8
</code></pre>
<p>I only need to extract each item's title (next line after ===== Item 5484/14800 =====) and the result.<br />
So i need to keep only the line with the item title and the result for that title and discard everything else.<br />
The issue is that sometimes a item has notes (maxim 3) and sometimes the result is displayed without additional notes so this makes it tricky.<br />
Any help would be appreciated. I'm doing the parser in python but don't need the actual code but some pointing in how could i achive this?</p>
<p>LE: The result I'm looking for is to discard everything else and get something like:</p>
<pre><code>('This is the item title','Foo')
then
('This is this items title','Bar')
</code></pre>
| 2 | 2009-06-10T18:44:15Z | 977,541 | <p>I would recommend starting a loop that looks for the "===" in the line. Let that key you off to the Title which is the next line. Set a flag that looks for the results, and if you don't find the results before you hit the next "===", say no results. Else, log the results with the title. Reset your flag and repeat. You could store the results with the Title in a dictionary as well, just store "No Results" when you don't find the results between the Title and the next "===" line.</p>
<p>This looks pretty simple to do based on the output.</p>
| 1 | 2009-06-10T19:01:31Z | [
"python",
"parsing"
] |
How would I go about parsing the following log? | 977,458 | <p>I need to parse a log in the following format:</p>
<pre><code>===== Item 5483/14800 =====
This is the item title
Info: some note
===== Item 5483/14800 (Update 1/3) =====
This is the item title
Info: some other note
===== Item 5483/14800 (Update 2/3) =====
This is the item title
Info: some more notes
===== Item 5483/14800 (Update 3/3) =====
This is the item title
Info: some other note
Test finished. Result Foo. Time 12 secunds.
Stats: CPU 0.5 MEM 5.3
===== Item 5484/14800 =====
This is this items title
Info: some note
Test finished. Result Bar. Time 4 secunds.
Stats: CPU 0.9 MEM 4.7
===== Item 5485/14800 =====
This is the title of this item
Info: some note
Test finished. Result FooBar. Time 7 secunds.
Stats: CPU 2.5 MEM 2.8
</code></pre>
<p>I only need to extract each item's title (next line after ===== Item 5484/14800 =====) and the result.<br />
So i need to keep only the line with the item title and the result for that title and discard everything else.<br />
The issue is that sometimes a item has notes (maxim 3) and sometimes the result is displayed without additional notes so this makes it tricky.<br />
Any help would be appreciated. I'm doing the parser in python but don't need the actual code but some pointing in how could i achive this?</p>
<p>LE: The result I'm looking for is to discard everything else and get something like:</p>
<pre><code>('This is the item title','Foo')
then
('This is this items title','Bar')
</code></pre>
| 2 | 2009-06-10T18:44:15Z | 977,550 | <p>You could try something like this (in c-like pseudocode, since i don't know python):</p>
<pre><code>string line=getline();
regex boundary="^==== [^=]+ ====$";
regex info="^Info: (.*)$";
regex test_data="Test ([^.]*)\. Result ([^.]*)\. Time ([^.]*)\.$";
regex stats="Stats: (.*)$";
while(!eof())
{
// sanity check
test line against boundary, if they don't match, throw excetion
string title=getline();
while(1)
{
// end the loop if we finished the data
if(eof()) break;
line=getline();
test line against boundary, if they match, break
test line against info, if they match, load the first matched group into "info"
test line against test_data, if they match, load the first matched group into "test_result", load the 2nd matched group into "result", load the 3rd matched group into "time"
test line against stats, if they match, load the first matched group into "statistics"
}
// at this point you can use the variables set above to do whatever with a line
// for example, you want to use title and, if set, test_result/result/time.
}
</code></pre>
| 0 | 2009-06-10T19:03:26Z | [
"python",
"parsing"
] |
How would I go about parsing the following log? | 977,458 | <p>I need to parse a log in the following format:</p>
<pre><code>===== Item 5483/14800 =====
This is the item title
Info: some note
===== Item 5483/14800 (Update 1/3) =====
This is the item title
Info: some other note
===== Item 5483/14800 (Update 2/3) =====
This is the item title
Info: some more notes
===== Item 5483/14800 (Update 3/3) =====
This is the item title
Info: some other note
Test finished. Result Foo. Time 12 secunds.
Stats: CPU 0.5 MEM 5.3
===== Item 5484/14800 =====
This is this items title
Info: some note
Test finished. Result Bar. Time 4 secunds.
Stats: CPU 0.9 MEM 4.7
===== Item 5485/14800 =====
This is the title of this item
Info: some note
Test finished. Result FooBar. Time 7 secunds.
Stats: CPU 2.5 MEM 2.8
</code></pre>
<p>I only need to extract each item's title (next line after ===== Item 5484/14800 =====) and the result.<br />
So i need to keep only the line with the item title and the result for that title and discard everything else.<br />
The issue is that sometimes a item has notes (maxim 3) and sometimes the result is displayed without additional notes so this makes it tricky.<br />
Any help would be appreciated. I'm doing the parser in python but don't need the actual code but some pointing in how could i achive this?</p>
<p>LE: The result I'm looking for is to discard everything else and get something like:</p>
<pre><code>('This is the item title','Foo')
then
('This is this items title','Bar')
</code></pre>
| 2 | 2009-06-10T18:44:15Z | 977,790 | <p>Here's some not so good looking perl code that does the job. Perhaps you can find it useful in some way. Quick hack, there are other ways of doing it (I feel that this code needs defending).</p>
<pre><code>#!/usr/bin/perl -w
#
# $Id$
#
use strict;
use warnings;
my @ITEMS;
my $item;
my $state = 0;
open(FD, "< data.txt") or die "Failed to open file.";
while (my $line = <FD>) {
$line =~ s/(\r|\n)//g;
if ($line =~ /^===== Item (\d+)\/\d+/) {
my $item_number = $1;
if ($item) {
# Just to make sure we don't have two lines that seems to be a headline in a row.
# If we have an item but haven't set the title it means that there are two in a row that matches.
die "Something seems to be wrong, better safe than sorry. Line $. : $line\n" if (not $item->{title});
# If we have a new item number add previuos item and create a new.
if ($item_number != $item->{item_number}) {
push(@ITEMS, $item);
$item = {};
$item->{item_number} = $item_number;
}
} else {
# First entry, don't have an item.
$item = {}; # Create new item.
$item->{item_number} = $item_number;
}
$state = 1;
} elsif ($state == 1) {
die "Data must start with a headline." if (not $item);
# If we already have a title make sure it matches.
if ($item->{title}) {
if ($item->{title} ne $line) {
die "Title doesn't match for item " . $item->{item_number} . ", line $. : $line\n";
}
} else {
$item->{title} = $line;
}
$state++;
} elsif (($state == 2) && ($line =~ /^Info:/)) {
# Just make sure that for state 2 we have a line that match Info.
$state++;
} elsif (($state == 3) && ($line =~ /^Test finished\. Result ([^.]+)\. Time \d+ secunds{0,1}\.$/)) {
$item->{status} = $1;
$state++;
} elsif (($state == 4) && ($line =~ /^Stats:/)) {
$state++; # After Stats we must have a new item or we should fail.
} else {
die "Invalid data, line $.: $line\n";
}
}
# Need to take care of the last item too.
push(@ITEMS, $item) if ($item);
close FD;
# Loop our items and print the info we stored.
for $item (@ITEMS) {
print $item->{item_number} . " (" . $item->{status} . ") " . $item->{title} . "\n";
}
</code></pre>
| -1 | 2009-06-10T19:50:11Z | [
"python",
"parsing"
] |
How would I go about parsing the following log? | 977,458 | <p>I need to parse a log in the following format:</p>
<pre><code>===== Item 5483/14800 =====
This is the item title
Info: some note
===== Item 5483/14800 (Update 1/3) =====
This is the item title
Info: some other note
===== Item 5483/14800 (Update 2/3) =====
This is the item title
Info: some more notes
===== Item 5483/14800 (Update 3/3) =====
This is the item title
Info: some other note
Test finished. Result Foo. Time 12 secunds.
Stats: CPU 0.5 MEM 5.3
===== Item 5484/14800 =====
This is this items title
Info: some note
Test finished. Result Bar. Time 4 secunds.
Stats: CPU 0.9 MEM 4.7
===== Item 5485/14800 =====
This is the title of this item
Info: some note
Test finished. Result FooBar. Time 7 secunds.
Stats: CPU 2.5 MEM 2.8
</code></pre>
<p>I only need to extract each item's title (next line after ===== Item 5484/14800 =====) and the result.<br />
So i need to keep only the line with the item title and the result for that title and discard everything else.<br />
The issue is that sometimes a item has notes (maxim 3) and sometimes the result is displayed without additional notes so this makes it tricky.<br />
Any help would be appreciated. I'm doing the parser in python but don't need the actual code but some pointing in how could i achive this?</p>
<p>LE: The result I'm looking for is to discard everything else and get something like:</p>
<pre><code>('This is the item title','Foo')
then
('This is this items title','Bar')
</code></pre>
| 2 | 2009-06-10T18:44:15Z | 977,892 | <p>I know you didn't ask for real code but this is too great an opportunity for a generator-based text muncher to pass up:</p>
<pre><code># data is a multiline string containing your log, but this
# function could be easily rewritten to accept a file handle.
def get_stats(data):
title = ""
grab_title = False
for line in data.split('\n'):
if line.startswith("====="):
grab_title = True
elif grab_title:
grab_title = False
title = line
elif line.startswith("Test finished."):
start = line.index("Result") + 7
end = line.index("Time") - 2
yield (title, line[start:end])
for d in get_stats(data):
print d
# Returns:
# ('This is the item title', 'Foo')
# ('This is this items title', 'Bar')
# ('This is the title of this item', 'FooBar')
</code></pre>
<p>Hopefully this is straightforward enough. Do ask if you have questions on how exactly the above works.</p>
| 5 | 2009-06-10T20:14:31Z | [
"python",
"parsing"
] |
How would I go about parsing the following log? | 977,458 | <p>I need to parse a log in the following format:</p>
<pre><code>===== Item 5483/14800 =====
This is the item title
Info: some note
===== Item 5483/14800 (Update 1/3) =====
This is the item title
Info: some other note
===== Item 5483/14800 (Update 2/3) =====
This is the item title
Info: some more notes
===== Item 5483/14800 (Update 3/3) =====
This is the item title
Info: some other note
Test finished. Result Foo. Time 12 secunds.
Stats: CPU 0.5 MEM 5.3
===== Item 5484/14800 =====
This is this items title
Info: some note
Test finished. Result Bar. Time 4 secunds.
Stats: CPU 0.9 MEM 4.7
===== Item 5485/14800 =====
This is the title of this item
Info: some note
Test finished. Result FooBar. Time 7 secunds.
Stats: CPU 2.5 MEM 2.8
</code></pre>
<p>I only need to extract each item's title (next line after ===== Item 5484/14800 =====) and the result.<br />
So i need to keep only the line with the item title and the result for that title and discard everything else.<br />
The issue is that sometimes a item has notes (maxim 3) and sometimes the result is displayed without additional notes so this makes it tricky.<br />
Any help would be appreciated. I'm doing the parser in python but don't need the actual code but some pointing in how could i achive this?</p>
<p>LE: The result I'm looking for is to discard everything else and get something like:</p>
<pre><code>('This is the item title','Foo')
then
('This is this items title','Bar')
</code></pre>
| 2 | 2009-06-10T18:44:15Z | 978,416 | <p>Regular expression with group matching seems to do the job in python:</p>
<pre><code>import re
data = """===== Item 5483/14800 =====
This is the item title
Info: some note
===== Item 5483/14800 (Update 1/3) =====
This is the item title
Info: some other note
===== Item 5483/14800 (Update 2/3) =====
This is the item title
Info: some more notes
===== Item 5483/14800 (Update 3/3) =====
This is the item title
Info: some other note
Test finished. Result Foo. Time 12 secunds.
Stats: CPU 0.5 MEM 5.3
===== Item 5484/14800 =====
This is this items title
Info: some note
Test finished. Result Bar. Time 4 secunds.
Stats: CPU 0.9 MEM 4.7
===== Item 5485/14800 =====
This is the title of this item
Info: some note
Test finished. Result FooBar. Time 7 secunds.
Stats: CPU 2.5 MEM 2.8"""
p = re.compile("^=====[^=]*=====\n(.*)$\nInfo: .*\n.*Result ([^\.]*)\.",
re.MULTILINE)
for m in re.finditer(p, data):
print "title:", m.group(1), "result:", m.group(2)er code here
</code></pre>
<p>If You need more info about regular expressions check: <a href="http://docs.python.org/library/re.html" rel="nofollow">python docs</a>.</p>
| 1 | 2009-06-10T22:13:10Z | [
"python",
"parsing"
] |
How would I go about parsing the following log? | 977,458 | <p>I need to parse a log in the following format:</p>
<pre><code>===== Item 5483/14800 =====
This is the item title
Info: some note
===== Item 5483/14800 (Update 1/3) =====
This is the item title
Info: some other note
===== Item 5483/14800 (Update 2/3) =====
This is the item title
Info: some more notes
===== Item 5483/14800 (Update 3/3) =====
This is the item title
Info: some other note
Test finished. Result Foo. Time 12 secunds.
Stats: CPU 0.5 MEM 5.3
===== Item 5484/14800 =====
This is this items title
Info: some note
Test finished. Result Bar. Time 4 secunds.
Stats: CPU 0.9 MEM 4.7
===== Item 5485/14800 =====
This is the title of this item
Info: some note
Test finished. Result FooBar. Time 7 secunds.
Stats: CPU 2.5 MEM 2.8
</code></pre>
<p>I only need to extract each item's title (next line after ===== Item 5484/14800 =====) and the result.<br />
So i need to keep only the line with the item title and the result for that title and discard everything else.<br />
The issue is that sometimes a item has notes (maxim 3) and sometimes the result is displayed without additional notes so this makes it tricky.<br />
Any help would be appreciated. I'm doing the parser in python but don't need the actual code but some pointing in how could i achive this?</p>
<p>LE: The result I'm looking for is to discard everything else and get something like:</p>
<pre><code>('This is the item title','Foo')
then
('This is this items title','Bar')
</code></pre>
| 2 | 2009-06-10T18:44:15Z | 984,569 | <p>This is sort of a continuation of maciejka's solution (see the comments there). If the data is in the file daniels.log, then we could go through it item by item with itertools.groupby, and apply a multi-line regexp to each item. This should scale fine.</p>
<pre><code>import itertools, re
p = re.compile("Result ([^.]*)\.", re.MULTILINE)
for sep, item in itertools.groupby(file('daniels.log'),
lambda x: x.startswith('===== Item ')):
if not sep:
title = item.next().strip()
m = p.search(''.join(item))
if m:
print (title, m.group(1))
</code></pre>
| 1 | 2009-06-12T01:04:02Z | [
"python",
"parsing"
] |
Comparing 2 .txt files using difflib in Python | 977,491 | <p>I am trying to compare 2 text files and output the first string in the comparison file that does not match but am having difficulty since I am very new to python. Can anybody please give me a sample way to use this module. </p>
<p>When I try something like:</p>
<pre><code>result = difflib.SequenceMatcher(None, testFile, comparisonFile)
</code></pre>
<p>I get an error saying object of type 'file' has no len.</p>
| 15 | 2009-06-10T18:51:20Z | 977,552 | <p>Are you sure both files exist ?</p>
<p>Just tested it and i get a perfect result.</p>
<p>To get the results i use something like:</p>
<pre><code>import difflib
diff=difflib.ndiff(open(testFile).readlines(), open(comparisonFile).readlines())
try:
while 1:
print diff.next(),
except:
pass
</code></pre>
<p>the first character of each line indicates if they are different:
eg.: '+' means the following line has been added, etc.</p>
| 5 | 2009-06-10T19:03:47Z | [
"python",
"difflib"
] |
Comparing 2 .txt files using difflib in Python | 977,491 | <p>I am trying to compare 2 text files and output the first string in the comparison file that does not match but am having difficulty since I am very new to python. Can anybody please give me a sample way to use this module. </p>
<p>When I try something like:</p>
<pre><code>result = difflib.SequenceMatcher(None, testFile, comparisonFile)
</code></pre>
<p>I get an error saying object of type 'file' has no len.</p>
| 15 | 2009-06-10T18:51:20Z | 977,563 | <p>For starters, you need to pass strings to difflib.SequenceMatcher, not files:</p>
<pre><code># Like so
difflib.SequenceMatcher(None, str1, str2)
# Or just read the files in
difflib.SequenceMatcher(None, file1.read(), file2.read())
</code></pre>
<p>That'll fix your error anyway. To get the first non-matching string, I'll direct you to the wonderful world of <a href="http://docs.python.org/library/difflib.html">difflib documentation.</a></p>
| 23 | 2009-06-10T19:06:00Z | [
"python",
"difflib"
] |
Comparing 2 .txt files using difflib in Python | 977,491 | <p>I am trying to compare 2 text files and output the first string in the comparison file that does not match but am having difficulty since I am very new to python. Can anybody please give me a sample way to use this module. </p>
<p>When I try something like:</p>
<pre><code>result = difflib.SequenceMatcher(None, testFile, comparisonFile)
</code></pre>
<p>I get an error saying object of type 'file' has no len.</p>
| 15 | 2009-06-10T18:51:20Z | 977,737 | <p>It sounds like you may not need difflib at all. If you're comparing line by line, try something like this:</p>
<pre><code>test_lines = open("test.txt").readlines()
correct_lines = open("correct.txt").readlines()
for test, correct in zip(test_lines, correct_lines):
if test != correct:
print "Oh no! Expected %r; got %r." % (correct, test)
break
else:
len_diff = len(test_lines) - len(correct_lines)
if len_diff > 0:
print "Test file had too much data."
elif len_diff < 0:
print "Test file had too little data."
else:
print "Everything was correct!"
</code></pre>
| 3 | 2009-06-10T19:39:59Z | [
"python",
"difflib"
] |
Comparing 2 .txt files using difflib in Python | 977,491 | <p>I am trying to compare 2 text files and output the first string in the comparison file that does not match but am having difficulty since I am very new to python. Can anybody please give me a sample way to use this module. </p>
<p>When I try something like:</p>
<pre><code>result = difflib.SequenceMatcher(None, testFile, comparisonFile)
</code></pre>
<p>I get an error saying object of type 'file' has no len.</p>
| 15 | 2009-06-10T18:51:20Z | 21,790,513 | <p>Here is a quick example of comparing the contents of two files using Python difflib...</p>
<pre><code>import difflib
file1 = "myFile1.txt"
file2 = "myFile2.txt"
diff = difflib.ndiff(open(file1).readlines(),open(file2).readlines())
print ''.join(diff),
</code></pre>
| 5 | 2014-02-14T22:18:55Z | [
"python",
"difflib"
] |
Redirecting FORTRAN (called via F2PY) output in Python | 977,840 | <p>I'm trying to figure out how to redirect output from some FORTRAN code for which I've generated a Python interface by using F2PY. I've tried:</p>
<pre><code>from fortran_code import fortran_function
stdout_holder = sys.stdout
stderr_holder = sys.stderr
sys.stdout = file("/dev/null","w")
fortran_function()
sys.stdout.close()
sys.stderr.close()
sys.stdout = stdout_holder
sys.stderr = stderr_holder
</code></pre>
<p>This is the de facto method of redirecting output in Python, but it doesn't seem to work in this case (i.e., the output is displayed anyway).</p>
<p>I did find <a href="http://cens.ioc.ee/pipermail/f2py-users/2002-November/000352.html">a mailing list post from 2002</a> saying that "It is possible to read messages from pts devices, e.g. ttysnoop does this". Information on ttysnoop seems to be pretty difficult to find online (I don't think it's been updated in quite a few years; for example, <a href="http://www.linuxhelp.net/guides/ttysnoop/">the first result on Google for "ttysnoop"</a> has only dead links to tarballs, RPMs, and .deb's), and <a href="http://macosx.forked.net/bbarchive/forum5/000008.html">this request for a port to OS X</a> received the response "No luck, it requires some linux specific utmp functions which I can't create."</p>
<p>I'm open to any suggestions on how to redirect the output (it doesn't have to use ttysnoop).</p>
<p>Thanks!</p>
| 9 | 2009-06-10T19:59:15Z | 978,264 | <p>The stdin and stdout fds are being inherited by the C shared library.</p>
<pre><code>from fortran_code import fortran_function
import os
print "will run fortran function!"
# open 2 fds
null_fds = [os.open(os.devnull, os.O_RDWR) for x in xrange(2)]
# save the current file descriptors to a tuple
save = os.dup(1), os.dup(2)
# put /dev/null fds on 1 and 2
os.dup2(null_fds[0], 1)
os.dup2(null_fds[1], 2)
# *** run the function ***
fortran_function()
# restore file descriptors so I can print the results
os.dup2(save[0], 1)
os.dup2(save[1], 2)
# close the temporary fds
os.close(null_fds[0])
os.close(null_fds[1])
print "done!"
</code></pre>
| 14 | 2009-06-10T21:33:26Z | [
"python",
"unix",
"fortran",
"stdout"
] |
Redirecting FORTRAN (called via F2PY) output in Python | 977,840 | <p>I'm trying to figure out how to redirect output from some FORTRAN code for which I've generated a Python interface by using F2PY. I've tried:</p>
<pre><code>from fortran_code import fortran_function
stdout_holder = sys.stdout
stderr_holder = sys.stderr
sys.stdout = file("/dev/null","w")
fortran_function()
sys.stdout.close()
sys.stderr.close()
sys.stdout = stdout_holder
sys.stderr = stderr_holder
</code></pre>
<p>This is the de facto method of redirecting output in Python, but it doesn't seem to work in this case (i.e., the output is displayed anyway).</p>
<p>I did find <a href="http://cens.ioc.ee/pipermail/f2py-users/2002-November/000352.html">a mailing list post from 2002</a> saying that "It is possible to read messages from pts devices, e.g. ttysnoop does this". Information on ttysnoop seems to be pretty difficult to find online (I don't think it's been updated in quite a few years; for example, <a href="http://www.linuxhelp.net/guides/ttysnoop/">the first result on Google for "ttysnoop"</a> has only dead links to tarballs, RPMs, and .deb's), and <a href="http://macosx.forked.net/bbarchive/forum5/000008.html">this request for a port to OS X</a> received the response "No luck, it requires some linux specific utmp functions which I can't create."</p>
<p>I'm open to any suggestions on how to redirect the output (it doesn't have to use ttysnoop).</p>
<p>Thanks!</p>
| 9 | 2009-06-10T19:59:15Z | 17,753,573 | <p>Here's a <a href="http://docs.python.org/2/library/contextlib.html" rel="nofollow">context manager</a> that I recently wrote and found useful, because I was having a similar problem with <a href="http://docs.python.org/2/distutils/apiref.html#distutils.ccompiler.CCompiler.has_function" rel="nofollow"><code>distutils.ccompiler.CCompiler.has_function</code></a> while working on <a href="https://code.google.com/p/pymssql/" rel="nofollow">pymssql</a>. I also used the file descriptor approach but I used a <a href="http://docs.python.org/2/library/contextlib.html" rel="nofollow">context manager</a>. Here's what I came up with:</p>
<pre class="lang-python prettyprint-override"><code>import contextlib
@contextlib.contextmanager
def stdchannel_redirected(stdchannel, dest_filename):
"""
A context manager to temporarily redirect stdout or stderr
e.g.:
with stdchannel_redirected(sys.stderr, os.devnull):
if compiler.has_function('clock_gettime', libraries=['rt']):
libraries.append('rt')
"""
try:
oldstdchannel = os.dup(stdchannel.fileno())
dest_file = open(dest_filename, 'w')
os.dup2(dest_file.fileno(), stdchannel.fileno())
yield
finally:
if oldstdchannel is not None:
os.dup2(oldstdchannel, stdchannel.fileno())
if dest_file is not None:
dest_file.close()
</code></pre>
<p>The context for why I created this is at <a href="http://marc-abramowitz.com/archives/2013/07/19/python-context-manager-for-redirected-stdout-and-stderr/" rel="nofollow">this blog post</a>. Similar to yours I think.</p>
<p>I use it like this in a <code>setup.py</code>:</p>
<pre class="lang-python prettyprint-override"><code>with stdchannel_redirected(sys.stderr, os.devnull):
if compiler.has_function('clock_gettime', libraries=['rt']):
libraries.append('rt')
</code></pre>
| 2 | 2013-07-19T18:59:26Z | [
"python",
"unix",
"fortran",
"stdout"
] |
Is there any way to add two bytes with overflow in python? | 978,149 | <p>I am using pySerial to read in data from an attached device. I want to calculate the checksum of each received packet. The packet is read in as a char array, with the actual checksum being the very last byte, at the end of the packet. To calculate the checksum, I would normally sum over the packet payload, and then compare it to the actual checksum. </p>
<p>Normally in a language like C, we would expect overflow, because the checksum itself is only one byte. I'm not sure about the internals of python, but from my experience with the language it looks like it will default to a larger size variable (maybe some internal bigInt class or something). Is there anyway to mimic the expected behavior of adding two chars, without writing my own implementation? Thanks.</p>
| 3 | 2009-06-10T21:03:09Z | 978,154 | <p>Sure, just take the modulus of your result to fit it back in the size you want. You can do the modulus at the end or at every step. For example:</p>
<pre><code>>>> payload = [100, 101, 102, 103, 104] # arbitrary sequence of bytes
>>> sum(payload) % 256 # modulo 256 to make the answer fit in a single byte
254 # this would be your checksum
</code></pre>
| 6 | 2009-06-10T21:04:45Z | [
"python",
"overflow",
"checksum"
] |
Is there any way to add two bytes with overflow in python? | 978,149 | <p>I am using pySerial to read in data from an attached device. I want to calculate the checksum of each received packet. The packet is read in as a char array, with the actual checksum being the very last byte, at the end of the packet. To calculate the checksum, I would normally sum over the packet payload, and then compare it to the actual checksum. </p>
<p>Normally in a language like C, we would expect overflow, because the checksum itself is only one byte. I'm not sure about the internals of python, but from my experience with the language it looks like it will default to a larger size variable (maybe some internal bigInt class or something). Is there anyway to mimic the expected behavior of adding two chars, without writing my own implementation? Thanks.</p>
| 3 | 2009-06-10T21:03:09Z | 978,261 | <p>to improve upon the earlier example, just bitwise-and it with 0xFF. not sure if python does the optimization by default or not.</p>
<pre><code>sum(bytes) & 0xFF
</code></pre>
| 2 | 2009-06-10T21:32:32Z | [
"python",
"overflow",
"checksum"
] |
Is there any way to add two bytes with overflow in python? | 978,149 | <p>I am using pySerial to read in data from an attached device. I want to calculate the checksum of each received packet. The packet is read in as a char array, with the actual checksum being the very last byte, at the end of the packet. To calculate the checksum, I would normally sum over the packet payload, and then compare it to the actual checksum. </p>
<p>Normally in a language like C, we would expect overflow, because the checksum itself is only one byte. I'm not sure about the internals of python, but from my experience with the language it looks like it will default to a larger size variable (maybe some internal bigInt class or something). Is there anyway to mimic the expected behavior of adding two chars, without writing my own implementation? Thanks.</p>
| 3 | 2009-06-10T21:03:09Z | 32,319,852 | <p>Summing the bytes and then taking the modulus, as in <code>sum(bytes) % 256</code> (or <code>sum(bytes) & 0xFF</code>), is (in many programming languages) vulnerable to integer overflow, since there is a finite maximum value that integer types can represent.</p>
<p>But, since we are talking about Python, this is not technically an issue: Python integers are arbitrary-precision, so an integer overflow can't occur.</p>
<p>If you want to perform the modulus operation on an element-by-element basis, you can use <code>functools.reduce()</code>:</p>
<pre><code>>>> payload = [100, 101, 102, 103, 104] # arbitrary sequence of bytes
# (Python 3 uses functools.reduce() instead of builtin reduce() function)
>>> import functools
>>> functools.reduce(lambda x,y: (x+y)%256, payload)
254
</code></pre>
| 0 | 2015-08-31T20:56:57Z | [
"python",
"overflow",
"checksum"
] |
Is it more efficient to parse external XML or to hit the database? | 978,581 | <p>I was wondering when dealing with a web service API that returns XML, whether it's better (faster) to just call the external service each time and parse the XML (using ElementTree) for display on your site or to save the records into the database (after parsing it once or however many times you need to each day) and make database calls instead for that same information.</p>
| 1 | 2009-06-10T23:09:40Z | 978,590 | <p>Consuming the webservices is more efficient because there are a lot more things you can do to scale your webservices and webserver (via caching, etc.). By consuming the middle layer, you also have the options to change the returned data format (e.g. you can decide to use JSON rather than XML). Scaling database is much harder (involving replication, etc.) so in general, reduce hits on DB if you can.</p>
| 3 | 2009-06-10T23:13:52Z | [
"python",
"mysql",
"xml",
"django",
"parsing"
] |
Is it more efficient to parse external XML or to hit the database? | 978,581 | <p>I was wondering when dealing with a web service API that returns XML, whether it's better (faster) to just call the external service each time and parse the XML (using ElementTree) for display on your site or to save the records into the database (after parsing it once or however many times you need to each day) and make database calls instead for that same information.</p>
| 1 | 2009-06-10T23:09:40Z | 978,593 | <p>First off -- measure. Don't just assume that one is better or worse than the other.</p>
<p>Second, if you really don't want to measure, I'd guess the database is a bit faster (assuming the database is relatively local compared to the web service). Network latency usually is more than parse time unless we're talking a really complex database or really complex XML.</p>
| 6 | 2009-06-10T23:14:27Z | [
"python",
"mysql",
"xml",
"django",
"parsing"
] |
Is it more efficient to parse external XML or to hit the database? | 978,581 | <p>I was wondering when dealing with a web service API that returns XML, whether it's better (faster) to just call the external service each time and parse the XML (using ElementTree) for display on your site or to save the records into the database (after parsing it once or however many times you need to each day) and make database calls instead for that same information.</p>
| 1 | 2009-06-10T23:09:40Z | 978,603 | <p>There is not enough information to be able to say for sure in the general case. Why don't you do some tests and find out? Since it sounds like you are using python you will probably want to use the timeit module.</p>
<p>Some things that could effect the result:</p>
<ul>
<li>Performance of the web service you are using</li>
<li>Reliability of the web service you are using</li>
<li>Distance between servers</li>
<li>Amount of data being returned</li>
</ul>
<p>I would guess that if it is cacheable, that a cached version of the data will be faster, but that does not necessarily mean using a local RDBMS, it might mean something like memcached or an in memory cache in your application.</p>
| 1 | 2009-06-10T23:18:38Z | [
"python",
"mysql",
"xml",
"django",
"parsing"
] |
Is it more efficient to parse external XML or to hit the database? | 978,581 | <p>I was wondering when dealing with a web service API that returns XML, whether it's better (faster) to just call the external service each time and parse the XML (using ElementTree) for display on your site or to save the records into the database (after parsing it once or however many times you need to each day) and make database calls instead for that same information.</p>
| 1 | 2009-06-10T23:09:40Z | 978,607 | <p>It depends - who is calling the web service? Is the web service called every time the user hits the page? If that's the case I'd recommend introducing a caching layer of some sort - many web service API's throttle the amount of hits you can make per hour.</p>
<p>Whether you choose to parse the cached XML on the fly or call the data from a database probably won't matter (unless we are talking enterprise scaling here). Personally, I'd much rather make a simple SQL call than write a DOM Parser (which is much more prone to exceptional scenarios). </p>
| 1 | 2009-06-10T23:19:51Z | [
"python",
"mysql",
"xml",
"django",
"parsing"
] |
Is it more efficient to parse external XML or to hit the database? | 978,581 | <p>I was wondering when dealing with a web service API that returns XML, whether it's better (faster) to just call the external service each time and parse the XML (using ElementTree) for display on your site or to save the records into the database (after parsing it once or however many times you need to each day) and make database calls instead for that same information.</p>
| 1 | 2009-06-10T23:09:40Z | 978,717 | <p>It depends from case to case, you'll have to measure (or at least make an educated guess).</p>
<p>You'll have to consider several things.</p>
<p>Web service</p>
<ul>
<li>it might hit database itself</li>
<li>it can be cached</li>
<li>it will introduce network latency and might be unreliable</li>
<li>or it could be in local network and faster than accessing even local disk</li>
</ul>
<p>DB</p>
<ul>
<li>might be slow since it needs to access disk (although databases have internal caches, but those are usually not targeted)</li>
<li>should be reliable</li>
</ul>
<p>Technology itself doesn't mean much in terms of speed - in one case database parses SQL, in other XML parser parses XML, and database is usually acessed via socket as well, so you have both parsing and network in either case.</p>
<p>Caching data in your application if applicable is probably a good idea.</p>
| 0 | 2009-06-11T00:06:35Z | [
"python",
"mysql",
"xml",
"django",
"parsing"
] |
Is it more efficient to parse external XML or to hit the database? | 978,581 | <p>I was wondering when dealing with a web service API that returns XML, whether it's better (faster) to just call the external service each time and parse the XML (using ElementTree) for display on your site or to save the records into the database (after parsing it once or however many times you need to each day) and make database calls instead for that same information.</p>
| 1 | 2009-06-10T23:09:40Z | 978,773 | <p>As a few people have said, it depends, and you should test it.</p>
<p>Often external services are slow, and caching them locally (in a database in memory, e.g., with memcached) is faster. But perhaps not.</p>
<p>Fortunately, it's cheap and easy to test.</p>
| 0 | 2009-06-11T00:29:58Z | [
"python",
"mysql",
"xml",
"django",
"parsing"
] |
Is it more efficient to parse external XML or to hit the database? | 978,581 | <p>I was wondering when dealing with a web service API that returns XML, whether it's better (faster) to just call the external service each time and parse the XML (using ElementTree) for display on your site or to save the records into the database (after parsing it once or however many times you need to each day) and make database calls instead for that same information.</p>
| 1 | 2009-06-10T23:09:40Z | 978,857 | <p>Everyone is being very polite in answering this question: "it depends"... "you should test"... and so forth.</p>
<p>True, the question does not go into great detail about the application and network topographies involved, but if the question is even being asked, then it's likely a) the DB is "local" to the application (on the same subnet, or the same machine, or in memory), and b) the webservice is not. After all, the OP uses the phrases "external service" and "display on your own site." The phrase "parsing it once or however many times you need to each day" also suggests a set of data that doesn't exactly change every second.</p>
<p>The classic SOA myth is that the network is always available; going a step further, I'd say it's a myth that the network is always available with low latency. Unless your own internal systems are crap, sending an HTTP query across the Internet will always be slower than a query to a local DB or DB cluster. There are any number of reasons for this: number of hops to the remote server, outage or degradation issues that you can't control on the remote end, and the internal processing time for the remote web service application to analyze your request, hit its own persistence backend (aka DB), and return a result.</p>
<p>Fire up your app. Do some latency and response times to your DB. Now do the same to a remote web service. Unless your DB is also across the Internet, you'll notice a huge difference.</p>
<p>It's not at all hard for a competent technologist to scale a DB, or for you to completely remove the DB from caching using memcached and other paradigms; the latency between servers sitting near each other in the datacentre is monumentally less than between machines over the Internet (and more secure, to boot). Even if achieving this scale requires some thought, it's under your control, unlike a remote web service whose scaling and latency are totally opaque to you. I, for one, would not be too happy with the idea that the availability and responsiveness of my site are based on someone else entirely.</p>
<p>Finally, what happens if the remote web service is unavailable? Imagine a world where every request to your site involves a request over the Internet to some other site. What happens if that other site is unavailable? Do your users watch a spinning cursor of death for several hours? Do they enjoy an Error 500 while your site borks on this unexpected external dependency? </p>
<p>If you find yourself adopting an architecture whose fundamental features depend on a remote Internet call for every request, think very carefully about your application before deciding if you can live with the consequences.</p>
| 4 | 2009-06-11T01:08:21Z | [
"python",
"mysql",
"xml",
"django",
"parsing"
] |
Is it more efficient to parse external XML or to hit the database? | 978,581 | <p>I was wondering when dealing with a web service API that returns XML, whether it's better (faster) to just call the external service each time and parse the XML (using ElementTree) for display on your site or to save the records into the database (after parsing it once or however many times you need to each day) and make database calls instead for that same information.</p>
| 1 | 2009-06-10T23:09:40Z | 978,864 | <p>Test definitely. As a rule of thumb, XML is good for communicating between apps, but once you have the data inside of your app, everything should go into a database table. This may not apply in all cases, but 95% of the time it has for me. Anytime I ever tried to store data any other way (ex. XML in a content management system) I ended up wishing I would have just used good old sprocs and sql server.</p>
| 0 | 2009-06-11T01:12:47Z | [
"python",
"mysql",
"xml",
"django",
"parsing"
] |
Is it more efficient to parse external XML or to hit the database? | 978,581 | <p>I was wondering when dealing with a web service API that returns XML, whether it's better (faster) to just call the external service each time and parse the XML (using ElementTree) for display on your site or to save the records into the database (after parsing it once or however many times you need to each day) and make database calls instead for that same information.</p>
| 1 | 2009-06-10T23:09:40Z | 979,028 | <p>It sounds like you essentially want to <em>cache</em> results, and are wondering if it's worth it. But if so, I would NOT use a database (I assume you are thinking of a relational DB): RDBMSs are not good for caching; even though many use them. You don't need persistence nor ACID.
If choice was between Oracle/MySQL and external web service, I would start with just using service.</p>
<p>Instead, consider real caching systems; local or not (memcache, simple in-memory caches etc).
Or if you must use a DB, use key/value store, BDB works well. Store response message in its serialized form (XML), try to fetch from cache, if not, from service, parse. Or if there's a convenient and more compact serialization, store and fetch that.</p>
| 0 | 2009-06-11T02:26:38Z | [
"python",
"mysql",
"xml",
"django",
"parsing"
] |
Vim, Python, and Django autocompletion (pysmell?) | 978,643 | <p>Does anyone know how to set up auto completion to work nicely with python, django, and vim?</p>
<p>I've been trying to use pysmell, but I can't seem to get it set up correctly (or maybe I don't know how it works). Right now, I run pysmell in the django directory (I'm using the trunk) and move the resulting tags to my project directory, then I also run pysmell in the project directory. Vim doesn't pick up the django tags, though, and they don't get auto completed.</p>
<p>Does anyone know how to set up auto completion in vim so that it will complete the long django functions (like get_object_or_404) as well as classes/functions in my own code? I have poked around on google but haven't found any good resources.</p>
<p>Thanks.</p>
| 46 | 2009-06-10T23:35:16Z | 978,766 | <p>I've had good luck with exuberant-ctags for this.</p>
<p>I use this macro in my vimrc:</p>
<pre>
execute 'map :!/usr/bin/exuberant-ctags -f '.&tags.' --recurse '.$_P4ROOT.' '
</pre>
<p>You'll want to modify that slightly, so that it includes your python /site-packages/django/ directory as well as your own code.</p>
<p>Then, hit F2 inside vim to update the tags, and use the regular vim tag bindings to navigate.</p>
| 3 | 2009-06-11T00:26:40Z | [
"python",
"django",
"vim"
] |
Vim, Python, and Django autocompletion (pysmell?) | 978,643 | <p>Does anyone know how to set up auto completion to work nicely with python, django, and vim?</p>
<p>I've been trying to use pysmell, but I can't seem to get it set up correctly (or maybe I don't know how it works). Right now, I run pysmell in the django directory (I'm using the trunk) and move the resulting tags to my project directory, then I also run pysmell in the project directory. Vim doesn't pick up the django tags, though, and they don't get auto completed.</p>
<p>Does anyone know how to set up auto completion in vim so that it will complete the long django functions (like get_object_or_404) as well as classes/functions in my own code? I have poked around on google but haven't found any good resources.</p>
<p>Thanks.</p>
| 46 | 2009-06-10T23:35:16Z | 978,778 | <p>First off, thank you for asking this question, as it forced me to figure this out myself and it's great!</p>
<p>Here is the page I used as a reference: <a href="http://github.com/orestis/pysmell/tree/v0.6">PySmell v0.6 released : orestis.gr</a></p>
<ol>
<li>Install PySmell using the <code>setup.py install</code> command.</li>
<li>Generate the <code>PYSMELLTAGS</code> file for django by going to your <code>site-packages/django</code> directory and running: <code>pysmell . -o ~/PYSMELLTAGS.django</code></li>
<li>Copy that file to your project directory, and then ran <code>pysmell .</code> to generate the project PYSMELLTAGS file</li>
<li>Make sure pysmell is in your <code>PYTHONPATH</code> (<code>export PYTHONPATH=${PYTHONPATH}:/path/to/pysmell/</code>)</li>
<li>Run vim (<code>vim .</code>)</li>
<li>Source <code>pysmell.vim</code> (<code>:source /path/to/pysmell/pysmell.vim</code>)</li>
<li>Set the autocomplete command (<code>:set omnifunc=pysmell#Complete</code>)</li>
<li>Type ^x^o to autocomplete and it should work</li>
</ol>
<p>I realize this is not a sustainable solution, but you should be able to use this as a start to getting it setup to always work (e.g., add the export to your .bashrc, add the :source to your .vimrc, setup <code>autocmd FileType python set omnifunc=pysmell#Complete</code>, etc.)</p>
<p>Let me know if this is enough to get you started. It worked for me!</p>
<p><strong>Edit</strong>
I simply added this to my .vimrc and as long as the <code>PYSMELLTAGS</code> & <code>PYSMELLTAGS.django</code> files are in my project root, it works fine without any other work:</p>
<pre><code>python << EOF
import os
import sys
import vim
sys.path.append("/usr/local/python/lib/python2.5/site-packages")
EOF
exe ":source ~/src/pysmell/pysmell.vim"
autocmd FileType python set omnifunc=pysmell#Complete
</code></pre>
| 30 | 2009-06-11T00:32:43Z | [
"python",
"django",
"vim"
] |
Vim, Python, and Django autocompletion (pysmell?) | 978,643 | <p>Does anyone know how to set up auto completion to work nicely with python, django, and vim?</p>
<p>I've been trying to use pysmell, but I can't seem to get it set up correctly (or maybe I don't know how it works). Right now, I run pysmell in the django directory (I'm using the trunk) and move the resulting tags to my project directory, then I also run pysmell in the project directory. Vim doesn't pick up the django tags, though, and they don't get auto completed.</p>
<p>Does anyone know how to set up auto completion in vim so that it will complete the long django functions (like get_object_or_404) as well as classes/functions in my own code? I have poked around on google but haven't found any good resources.</p>
<p>Thanks.</p>
| 46 | 2009-06-10T23:35:16Z | 979,347 | <p><img src="http://blog.dispatched.ch/wp-content/uploads/2009/05/vim-as-python-ide.png" alt="alt text" /></p>
<p>You can set up VIM with buffers, buffer display, auto complete, even Py Doc display.</p>
<p><a href="http://blog.dispatched.ch/2009/05/24/vim-as-python-ide/">Here you go</a></p>
| 12 | 2009-06-11T04:43:30Z | [
"python",
"django",
"vim"
] |
Vim, Python, and Django autocompletion (pysmell?) | 978,643 | <p>Does anyone know how to set up auto completion to work nicely with python, django, and vim?</p>
<p>I've been trying to use pysmell, but I can't seem to get it set up correctly (or maybe I don't know how it works). Right now, I run pysmell in the django directory (I'm using the trunk) and move the resulting tags to my project directory, then I also run pysmell in the project directory. Vim doesn't pick up the django tags, though, and they don't get auto completed.</p>
<p>Does anyone know how to set up auto completion in vim so that it will complete the long django functions (like get_object_or_404) as well as classes/functions in my own code? I have poked around on google but haven't found any good resources.</p>
<p>Thanks.</p>
| 46 | 2009-06-10T23:35:16Z | 10,666,285 | <p>Today, you not need special extentions for django autocomplete in vim. Make sure that you have vim with python support.
To check it, type in xterm:</p>
<p>vim --version|grep python</p>
<h1>output:</h1>
<p><strong>+python</strong> -python3 +quickfix +reltime +rightleft -ruby +scrollbind +signs ... ...</p>
<p>To make work autocomplete, add this lines in your .vimrc:</p>
<blockquote>
<p>autocmd FileType python set omnifunc=pythoncomplete#Complete</p>
<p>if has("python")</p>
<p>python import sys,os</p>
<p>python sys.path.append('/home/sergey/workspace/django')</p>
<p>python os.environ['DJANGO_SETTINGS_MODULE'] = 'djangoProject.settings'</p>
<p>endif</p>
</blockquote>
<p>where:</p>
<ul>
<li>sys.path.append is path to your django workspace directory</li>
<li>djangoProject is name of your django project, which is going just after '/home/sergey/workspace/django'</li>
</ul>
<p>Finally, save it and restart vim. Now, after '.', you press default ctrl-x ctrl-o to get your autocomplete.</p>
| 2 | 2012-05-19T15:01:29Z | [
"python",
"django",
"vim"
] |
Vim, Python, and Django autocompletion (pysmell?) | 978,643 | <p>Does anyone know how to set up auto completion to work nicely with python, django, and vim?</p>
<p>I've been trying to use pysmell, but I can't seem to get it set up correctly (or maybe I don't know how it works). Right now, I run pysmell in the django directory (I'm using the trunk) and move the resulting tags to my project directory, then I also run pysmell in the project directory. Vim doesn't pick up the django tags, though, and they don't get auto completed.</p>
<p>Does anyone know how to set up auto completion in vim so that it will complete the long django functions (like get_object_or_404) as well as classes/functions in my own code? I have poked around on google but haven't found any good resources.</p>
<p>Thanks.</p>
| 46 | 2009-06-10T23:35:16Z | 12,885,498 | <p>As I wrote in other places, I developed Jedi. I really think it is far better than all the existing solutions (even PyCharm).</p>
<p><a href="https://github.com/davidhalter/jedi-vim">https://github.com/davidhalter/jedi-vim</a></p>
<p>It is built upon pythoncomplete and much much more powerful!</p>
<p>It works for complex code:<img src="http://i.stack.imgur.com/uTCI5.png" alt="completion"></p>
<p>And has additional features:
<img src="http://i.stack.imgur.com/5Irvi.png" alt="enter image description here"></p>
<p>There is a list of all possible features:</p>
<ul>
<li>builtin functions/classes support</li>
<li>complex module / function / class structures</li>
<li>ignores syntax and indentation errors</li>
<li>multiple returns / yields</li>
<li>tuple assignments / array indexing / dictionary indexing</li>
<li>exceptions / with-statement</li>
<li>*args / **kwargs</li>
<li>decorators</li>
<li>descriptors -> property / staticmethod / classmethod</li>
<li>closures</li>
<li>generators (yield statement) / iterators</li>
<li>support for some magic methods: <code>__call__</code>, <code>__iter__</code>, <code>__next__</code>,
<code>__get__</code>, <code>__getitem__</code>, <code>__init__</code></li>
<li>support for list.append, set.add, list.extend, etc.</li>
<li>(nested) list comprehensions / ternary expressions</li>
<li>relative imports</li>
<li><code>getattr()</code> / <code>__getattr__</code> / <code>__getattribute__</code></li>
<li>function annotations (py3k feature, are ignored right now, but being parsed.
I don't know what to do with them.)</li>
<li>class decorators (py3k feature, are being ignored too, until I find a use
case, that doesn't work with Jedi)</li>
<li>simple/usual <code>sys.path</code> modifications</li>
<li><code>isinstance</code> checks for if/while/assert</li>
</ul>
| 12 | 2012-10-14T19:00:53Z | [
"python",
"django",
"vim"
] |
How to expose client_address to all methods, using xmlrpclib? | 978,784 | <p>I create little SimpleXMLRPCServer for check ip of client.</p>
<p>I try this:</p>
<h1>Server</h1>
<p>import xmlrpclib</p>
<p>from SimpleXMLRPCServer import SimpleXMLRPCServer</p>
<p>server = SimpleXMLRPCServer(("localhost", 8000))</p>
<p>def MyIp():
return "Your ip is: %s" % server.socket.getpeername()</p>
<p>server.register_function(MyIp)</p>
<p>server.serve_forever()</p>
<h1>Client</h1>
<p>import xmlrpclib</p>
<p>se = xmlrpclib.Server("http://localhost:8000")</p>
<p>print se.MyIp()</p>
<h1>Error</h1>
<p>xmlrpclib.Fault: :(107, 'Transport endpoint is not connected')"></p>
<p>How make client_address visible to all functions?</p>
| 2 | 2009-06-11T00:34:23Z | 978,868 | <p>If you want for example to pass <code>client_address</code> as the first argument to every function, you could subclass SimpleXMLRPCRequestHandler (pass your subclass as the handler when you instantiate SimpleXMLRPCServer) and override <code>_dispatch</code> (to prepend <code>self.client_address</code> to the params tuple and then delegate the rest to <code>SimpleXMLRPCRequestHandler._dispatch</code>). If this approach is OK and you want to see code, just ask!</p>
<p>I'm not sure how you'd safely use anything but the function arguments to "make <code>client_address</code> visible" -- there's no <code>client_address</code> as a bare name, global or otherwise, there's just the <code>self.client_address</code> of each instance of the request handler class (and hacks such as copying it to a global variables feel <em>really</em> yucky indeed -- and unsafe under threading, etc etc).</p>
| 3 | 2009-06-11T01:15:31Z | [
"python",
"xmlrpclib"
] |
Error message "MemoryError" in Python | 978,841 | <p>Here's my problem: I'm trying to parse a big text file (about 15,000 KB) and write it to a MySQL database. I'm using Python 2.6, and the script parses about half the file and adds it to the database before freezing up. Sometimes it displays the text:</p>
<blockquote>
<p>MemoryError.</p>
</blockquote>
<p>Other times it simply freezes. I figured I could avoid this problem by using generator's wherever possible, but I was apparently wrong.</p>
<p>What am I doing wrong?</p>
<p>When I press <a href="http://en.wikipedia.org/wiki/Control_key" rel="nofollow">Ctrl</a> + <kbd>C</kbd> to keyboard interrupt, it shows this error message:</p>
<pre><code>...
sucessfully added vote # 2281
sucessfully added vote # 2282
sucessfully added vote # 2283
sucessfully added vote # 2284
floorvotes_db.py:35: Warning: Data truncated for column 'vote_value' at row 1
r['bill ID'] , r['last name'], r['vote'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "floorvotes_db.py", line 67, in addAllFiles
addFile(file)
File "floorvotes_db.py", line 61, in addFile
add(record)
File "floorvotes_db.py", line 35, in add
r['bill ID'] , r['last name'], r['vote'])
File "build/bdist.linux-i686/egg/MySQLdb/cursors.py", line 166, in execute
File "build/bdist.linux-i686/egg/MySQLdb/connections.py", line 35, in defaulte rrorhandler
KeyboardInterrupt
import os, re, datetime, string
# Data
DIR = '/mydir'
tfn = r'C:\Documents and Settings\Owner\Desktop\data.txt'
rgxs = {
'bill number': {
'rgx': r'(A|S)[0-9]+-?[A-Za-z]* {50}'}
}
# Compile rgxs for speediness
for rgx in rgxs: rgxs[rgx]['rgx'] = re.compile(rgxs[rgx]['rgx'])
splitter = rgxs['bill number']['rgx']
# Guts
class floor_vote_file:
def __init__(self, fn):
self.iterdata = (str for str in
splitter.split(open(fn).read())
if str and str <> 'A' and str <> 'S')
def iterVotes(self):
for record in self.data:
if record: yield billvote(record)
class billvote(object):
def __init__(self, section):
self.data = [line.strip() for line
in section.splitlines()]
self.summary = self.data[1].split()
self.vtlines = self.data[2:]
self.date = self.date()
self.year = self.year()
self.votes = self.parse_votes()
self.record = self.record()
# Parse summary date
def date(self):
d = [int(str) for str in self.summary[0].split('/')]
return datetime.date(d[2],d[0],d[1]).toordinal()
def year(self):
return datetime.date.fromordinal(self.date).year
def session(self):
"""
arg: 2-digit year int
returns: 4-digit session
"""
def odd():
return divmod(self.year, 2)[1] == 1
if odd():
return str(string.zfill(self.year, 2)) + \
str(string.zfill(self.year + 1, 2))
else:
return str(string.zfill(self.year - 1, 2))+ \
str(string.zfill(self.year, 2))
def house(self):
if self.summary[2] == 'Assembly': return 1
if self.summary[2] == 'Senate' : return 2
def splt_v_line(self, line):
return [string for string in line.split(' ')
if string <> '']
def splt_v(self, line):
return line.split()
def prse_v(self, item):
"""takes split_vote item"""
return {
'vote' : unicode(item[0]),
'last name': unicode(' '.join(item[1:]))
}
# Parse votes - main
def parse_votes(self):
nested = [[self.prse_v(self.splt_v(vote))
for vote in self.splt_v_line(line)]
for line in self.vtlines]
flattened = []
for lst in nested:
for dct in lst:
flattened.append(dct)
return flattened
# Useful data objects
def record(self):
return {
'date' : unicode(self.date),
'year' : unicode(self.year),
'session' : unicode(self.session()),
'house' : unicode(self.house()),
'bill ID' : unicode(self.summary[1]),
'ayes' : unicode(self.summary[5]),
'nays' : unicode(self.summary[7]),
}
def iterRecords(self):
for vote in self.votes:
r = self.record.copy()
r['vote'] = vote['vote']
r['last name'] = vote['last name']
yield r
test = floor_vote_file(tfn)
import MySQLdb as dbapi2
import floorvotes_parse as v
import os
# Initial database crap
db = dbapi2.connect(db=r"db",
user="user",
passwd="XXXXX")
cur = db.cursor()
if db and cur: print "\nConnected to db.\n"
def commit(): db.commit()
def ext():
cur.close()
db.close()
print "\nConnection closed.\n"
# DATA
DIR = '/mydir'
files = [DIR+fn for fn in os.listdir(DIR)
if fn.startswith('fvote')]
# Add stuff
def add(r):
"""add a record"""
cur.execute(
u'''INSERT INTO ny_votes (vote_house, vote_date, vote_year, bill_id,
member_lastname, vote_value) VALUES
(%s , %s , %s ,
%s , %s , %s )''',
(r['house'] , r['date'] , r['year'],
r['bill ID'] , r['last name'], r['vote'])
)
#print "added", r['year'], r['bill ID']
def crt():
"""create table"""
SQL = """
CREATE TABLE ny_votes (openleg_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
vote_house int(1), vote_date int(5), vote_year int(2), bill_id varchar(8),
member_lastname varchar(50), vote_value varchar(10));
"""
cur.execute(SQL)
print "\nCreate ny_votes.\n"
def rst():
SQL = """DROP TABLE ny_votes"""
cur.execute(SQL)
print "\nDropped ny_votes.\n"
crt()
def addFile(fn):
"""parse and add all records in a file"""
n = 0
for votes in v.floor_vote_file(fn).iterVotes():
for record in votes.iterRecords():
add(record)
n += 1
print 'sucessfully added vote # ' + str(n)
def addAllFiles():
for file in files:
addFile(file)
if __name__=='__main__':
rst()
addAllFiles()
</code></pre>
| 1 | 2009-06-11T00:59:50Z | 978,917 | <p>Generators are a good idea, but you seem to miss the biggest problem:</p>
<p>(str for str in splitter.split(<strong>open(fn).read()</strong>) if str and str <> 'A' and str <> 'S')</p>
<p>You're reading the whole file in at once even if you only need to work with bits at a time. You're code is too complicated for me to fix, but you should be able to use file's iterator for your task:</p>
<p>(line for line in open(fn))</p>
| 7 | 2009-06-11T01:39:01Z | [
"python",
"memory-management"
] |
Error message "MemoryError" in Python | 978,841 | <p>Here's my problem: I'm trying to parse a big text file (about 15,000 KB) and write it to a MySQL database. I'm using Python 2.6, and the script parses about half the file and adds it to the database before freezing up. Sometimes it displays the text:</p>
<blockquote>
<p>MemoryError.</p>
</blockquote>
<p>Other times it simply freezes. I figured I could avoid this problem by using generator's wherever possible, but I was apparently wrong.</p>
<p>What am I doing wrong?</p>
<p>When I press <a href="http://en.wikipedia.org/wiki/Control_key" rel="nofollow">Ctrl</a> + <kbd>C</kbd> to keyboard interrupt, it shows this error message:</p>
<pre><code>...
sucessfully added vote # 2281
sucessfully added vote # 2282
sucessfully added vote # 2283
sucessfully added vote # 2284
floorvotes_db.py:35: Warning: Data truncated for column 'vote_value' at row 1
r['bill ID'] , r['last name'], r['vote'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "floorvotes_db.py", line 67, in addAllFiles
addFile(file)
File "floorvotes_db.py", line 61, in addFile
add(record)
File "floorvotes_db.py", line 35, in add
r['bill ID'] , r['last name'], r['vote'])
File "build/bdist.linux-i686/egg/MySQLdb/cursors.py", line 166, in execute
File "build/bdist.linux-i686/egg/MySQLdb/connections.py", line 35, in defaulte rrorhandler
KeyboardInterrupt
import os, re, datetime, string
# Data
DIR = '/mydir'
tfn = r'C:\Documents and Settings\Owner\Desktop\data.txt'
rgxs = {
'bill number': {
'rgx': r'(A|S)[0-9]+-?[A-Za-z]* {50}'}
}
# Compile rgxs for speediness
for rgx in rgxs: rgxs[rgx]['rgx'] = re.compile(rgxs[rgx]['rgx'])
splitter = rgxs['bill number']['rgx']
# Guts
class floor_vote_file:
def __init__(self, fn):
self.iterdata = (str for str in
splitter.split(open(fn).read())
if str and str <> 'A' and str <> 'S')
def iterVotes(self):
for record in self.data:
if record: yield billvote(record)
class billvote(object):
def __init__(self, section):
self.data = [line.strip() for line
in section.splitlines()]
self.summary = self.data[1].split()
self.vtlines = self.data[2:]
self.date = self.date()
self.year = self.year()
self.votes = self.parse_votes()
self.record = self.record()
# Parse summary date
def date(self):
d = [int(str) for str in self.summary[0].split('/')]
return datetime.date(d[2],d[0],d[1]).toordinal()
def year(self):
return datetime.date.fromordinal(self.date).year
def session(self):
"""
arg: 2-digit year int
returns: 4-digit session
"""
def odd():
return divmod(self.year, 2)[1] == 1
if odd():
return str(string.zfill(self.year, 2)) + \
str(string.zfill(self.year + 1, 2))
else:
return str(string.zfill(self.year - 1, 2))+ \
str(string.zfill(self.year, 2))
def house(self):
if self.summary[2] == 'Assembly': return 1
if self.summary[2] == 'Senate' : return 2
def splt_v_line(self, line):
return [string for string in line.split(' ')
if string <> '']
def splt_v(self, line):
return line.split()
def prse_v(self, item):
"""takes split_vote item"""
return {
'vote' : unicode(item[0]),
'last name': unicode(' '.join(item[1:]))
}
# Parse votes - main
def parse_votes(self):
nested = [[self.prse_v(self.splt_v(vote))
for vote in self.splt_v_line(line)]
for line in self.vtlines]
flattened = []
for lst in nested:
for dct in lst:
flattened.append(dct)
return flattened
# Useful data objects
def record(self):
return {
'date' : unicode(self.date),
'year' : unicode(self.year),
'session' : unicode(self.session()),
'house' : unicode(self.house()),
'bill ID' : unicode(self.summary[1]),
'ayes' : unicode(self.summary[5]),
'nays' : unicode(self.summary[7]),
}
def iterRecords(self):
for vote in self.votes:
r = self.record.copy()
r['vote'] = vote['vote']
r['last name'] = vote['last name']
yield r
test = floor_vote_file(tfn)
import MySQLdb as dbapi2
import floorvotes_parse as v
import os
# Initial database crap
db = dbapi2.connect(db=r"db",
user="user",
passwd="XXXXX")
cur = db.cursor()
if db and cur: print "\nConnected to db.\n"
def commit(): db.commit()
def ext():
cur.close()
db.close()
print "\nConnection closed.\n"
# DATA
DIR = '/mydir'
files = [DIR+fn for fn in os.listdir(DIR)
if fn.startswith('fvote')]
# Add stuff
def add(r):
"""add a record"""
cur.execute(
u'''INSERT INTO ny_votes (vote_house, vote_date, vote_year, bill_id,
member_lastname, vote_value) VALUES
(%s , %s , %s ,
%s , %s , %s )''',
(r['house'] , r['date'] , r['year'],
r['bill ID'] , r['last name'], r['vote'])
)
#print "added", r['year'], r['bill ID']
def crt():
"""create table"""
SQL = """
CREATE TABLE ny_votes (openleg_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
vote_house int(1), vote_date int(5), vote_year int(2), bill_id varchar(8),
member_lastname varchar(50), vote_value varchar(10));
"""
cur.execute(SQL)
print "\nCreate ny_votes.\n"
def rst():
SQL = """DROP TABLE ny_votes"""
cur.execute(SQL)
print "\nDropped ny_votes.\n"
crt()
def addFile(fn):
"""parse and add all records in a file"""
n = 0
for votes in v.floor_vote_file(fn).iterVotes():
for record in votes.iterRecords():
add(record)
n += 1
print 'sucessfully added vote # ' + str(n)
def addAllFiles():
for file in files:
addFile(file)
if __name__=='__main__':
rst()
addAllFiles()
</code></pre>
| 1 | 2009-06-11T00:59:50Z | 978,961 | <p>Try to comment out <code>add(record)</code> to see if the problem is in your code or on the database side. All the records are added in one transaction (if supported) and maybe this leads to a problem if it get too many records. If commenting out <code>add(record)</code> helps, you could try to call <code>commit()</code> from time to time.</p>
| 1 | 2009-06-11T02:00:43Z | [
"python",
"memory-management"
] |
Error message "MemoryError" in Python | 978,841 | <p>Here's my problem: I'm trying to parse a big text file (about 15,000 KB) and write it to a MySQL database. I'm using Python 2.6, and the script parses about half the file and adds it to the database before freezing up. Sometimes it displays the text:</p>
<blockquote>
<p>MemoryError.</p>
</blockquote>
<p>Other times it simply freezes. I figured I could avoid this problem by using generator's wherever possible, but I was apparently wrong.</p>
<p>What am I doing wrong?</p>
<p>When I press <a href="http://en.wikipedia.org/wiki/Control_key" rel="nofollow">Ctrl</a> + <kbd>C</kbd> to keyboard interrupt, it shows this error message:</p>
<pre><code>...
sucessfully added vote # 2281
sucessfully added vote # 2282
sucessfully added vote # 2283
sucessfully added vote # 2284
floorvotes_db.py:35: Warning: Data truncated for column 'vote_value' at row 1
r['bill ID'] , r['last name'], r['vote'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "floorvotes_db.py", line 67, in addAllFiles
addFile(file)
File "floorvotes_db.py", line 61, in addFile
add(record)
File "floorvotes_db.py", line 35, in add
r['bill ID'] , r['last name'], r['vote'])
File "build/bdist.linux-i686/egg/MySQLdb/cursors.py", line 166, in execute
File "build/bdist.linux-i686/egg/MySQLdb/connections.py", line 35, in defaulte rrorhandler
KeyboardInterrupt
import os, re, datetime, string
# Data
DIR = '/mydir'
tfn = r'C:\Documents and Settings\Owner\Desktop\data.txt'
rgxs = {
'bill number': {
'rgx': r'(A|S)[0-9]+-?[A-Za-z]* {50}'}
}
# Compile rgxs for speediness
for rgx in rgxs: rgxs[rgx]['rgx'] = re.compile(rgxs[rgx]['rgx'])
splitter = rgxs['bill number']['rgx']
# Guts
class floor_vote_file:
def __init__(self, fn):
self.iterdata = (str for str in
splitter.split(open(fn).read())
if str and str <> 'A' and str <> 'S')
def iterVotes(self):
for record in self.data:
if record: yield billvote(record)
class billvote(object):
def __init__(self, section):
self.data = [line.strip() for line
in section.splitlines()]
self.summary = self.data[1].split()
self.vtlines = self.data[2:]
self.date = self.date()
self.year = self.year()
self.votes = self.parse_votes()
self.record = self.record()
# Parse summary date
def date(self):
d = [int(str) for str in self.summary[0].split('/')]
return datetime.date(d[2],d[0],d[1]).toordinal()
def year(self):
return datetime.date.fromordinal(self.date).year
def session(self):
"""
arg: 2-digit year int
returns: 4-digit session
"""
def odd():
return divmod(self.year, 2)[1] == 1
if odd():
return str(string.zfill(self.year, 2)) + \
str(string.zfill(self.year + 1, 2))
else:
return str(string.zfill(self.year - 1, 2))+ \
str(string.zfill(self.year, 2))
def house(self):
if self.summary[2] == 'Assembly': return 1
if self.summary[2] == 'Senate' : return 2
def splt_v_line(self, line):
return [string for string in line.split(' ')
if string <> '']
def splt_v(self, line):
return line.split()
def prse_v(self, item):
"""takes split_vote item"""
return {
'vote' : unicode(item[0]),
'last name': unicode(' '.join(item[1:]))
}
# Parse votes - main
def parse_votes(self):
nested = [[self.prse_v(self.splt_v(vote))
for vote in self.splt_v_line(line)]
for line in self.vtlines]
flattened = []
for lst in nested:
for dct in lst:
flattened.append(dct)
return flattened
# Useful data objects
def record(self):
return {
'date' : unicode(self.date),
'year' : unicode(self.year),
'session' : unicode(self.session()),
'house' : unicode(self.house()),
'bill ID' : unicode(self.summary[1]),
'ayes' : unicode(self.summary[5]),
'nays' : unicode(self.summary[7]),
}
def iterRecords(self):
for vote in self.votes:
r = self.record.copy()
r['vote'] = vote['vote']
r['last name'] = vote['last name']
yield r
test = floor_vote_file(tfn)
import MySQLdb as dbapi2
import floorvotes_parse as v
import os
# Initial database crap
db = dbapi2.connect(db=r"db",
user="user",
passwd="XXXXX")
cur = db.cursor()
if db and cur: print "\nConnected to db.\n"
def commit(): db.commit()
def ext():
cur.close()
db.close()
print "\nConnection closed.\n"
# DATA
DIR = '/mydir'
files = [DIR+fn for fn in os.listdir(DIR)
if fn.startswith('fvote')]
# Add stuff
def add(r):
"""add a record"""
cur.execute(
u'''INSERT INTO ny_votes (vote_house, vote_date, vote_year, bill_id,
member_lastname, vote_value) VALUES
(%s , %s , %s ,
%s , %s , %s )''',
(r['house'] , r['date'] , r['year'],
r['bill ID'] , r['last name'], r['vote'])
)
#print "added", r['year'], r['bill ID']
def crt():
"""create table"""
SQL = """
CREATE TABLE ny_votes (openleg_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
vote_house int(1), vote_date int(5), vote_year int(2), bill_id varchar(8),
member_lastname varchar(50), vote_value varchar(10));
"""
cur.execute(SQL)
print "\nCreate ny_votes.\n"
def rst():
SQL = """DROP TABLE ny_votes"""
cur.execute(SQL)
print "\nDropped ny_votes.\n"
crt()
def addFile(fn):
"""parse and add all records in a file"""
n = 0
for votes in v.floor_vote_file(fn).iterVotes():
for record in votes.iterRecords():
add(record)
n += 1
print 'sucessfully added vote # ' + str(n)
def addAllFiles():
for file in files:
addFile(file)
if __name__=='__main__':
rst()
addAllFiles()
</code></pre>
| 1 | 2009-06-11T00:59:50Z | 978,981 | <p>This isn't a Python memory issue, but perhaps it's worth thinking about. The previous answers make me think you'll sort that issue out quickly.</p>
<p>I wonder about the rollback logs in MySQL. If a single transaction is too large, perhaps you can checkpoint chunks. Commit each chunk separately instead of trying to rollback a 15MB file's worth.</p>
| 1 | 2009-06-11T02:08:53Z | [
"python",
"memory-management"
] |
Error message "MemoryError" in Python | 978,841 | <p>Here's my problem: I'm trying to parse a big text file (about 15,000 KB) and write it to a MySQL database. I'm using Python 2.6, and the script parses about half the file and adds it to the database before freezing up. Sometimes it displays the text:</p>
<blockquote>
<p>MemoryError.</p>
</blockquote>
<p>Other times it simply freezes. I figured I could avoid this problem by using generator's wherever possible, but I was apparently wrong.</p>
<p>What am I doing wrong?</p>
<p>When I press <a href="http://en.wikipedia.org/wiki/Control_key" rel="nofollow">Ctrl</a> + <kbd>C</kbd> to keyboard interrupt, it shows this error message:</p>
<pre><code>...
sucessfully added vote # 2281
sucessfully added vote # 2282
sucessfully added vote # 2283
sucessfully added vote # 2284
floorvotes_db.py:35: Warning: Data truncated for column 'vote_value' at row 1
r['bill ID'] , r['last name'], r['vote'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "floorvotes_db.py", line 67, in addAllFiles
addFile(file)
File "floorvotes_db.py", line 61, in addFile
add(record)
File "floorvotes_db.py", line 35, in add
r['bill ID'] , r['last name'], r['vote'])
File "build/bdist.linux-i686/egg/MySQLdb/cursors.py", line 166, in execute
File "build/bdist.linux-i686/egg/MySQLdb/connections.py", line 35, in defaulte rrorhandler
KeyboardInterrupt
import os, re, datetime, string
# Data
DIR = '/mydir'
tfn = r'C:\Documents and Settings\Owner\Desktop\data.txt'
rgxs = {
'bill number': {
'rgx': r'(A|S)[0-9]+-?[A-Za-z]* {50}'}
}
# Compile rgxs for speediness
for rgx in rgxs: rgxs[rgx]['rgx'] = re.compile(rgxs[rgx]['rgx'])
splitter = rgxs['bill number']['rgx']
# Guts
class floor_vote_file:
def __init__(self, fn):
self.iterdata = (str for str in
splitter.split(open(fn).read())
if str and str <> 'A' and str <> 'S')
def iterVotes(self):
for record in self.data:
if record: yield billvote(record)
class billvote(object):
def __init__(self, section):
self.data = [line.strip() for line
in section.splitlines()]
self.summary = self.data[1].split()
self.vtlines = self.data[2:]
self.date = self.date()
self.year = self.year()
self.votes = self.parse_votes()
self.record = self.record()
# Parse summary date
def date(self):
d = [int(str) for str in self.summary[0].split('/')]
return datetime.date(d[2],d[0],d[1]).toordinal()
def year(self):
return datetime.date.fromordinal(self.date).year
def session(self):
"""
arg: 2-digit year int
returns: 4-digit session
"""
def odd():
return divmod(self.year, 2)[1] == 1
if odd():
return str(string.zfill(self.year, 2)) + \
str(string.zfill(self.year + 1, 2))
else:
return str(string.zfill(self.year - 1, 2))+ \
str(string.zfill(self.year, 2))
def house(self):
if self.summary[2] == 'Assembly': return 1
if self.summary[2] == 'Senate' : return 2
def splt_v_line(self, line):
return [string for string in line.split(' ')
if string <> '']
def splt_v(self, line):
return line.split()
def prse_v(self, item):
"""takes split_vote item"""
return {
'vote' : unicode(item[0]),
'last name': unicode(' '.join(item[1:]))
}
# Parse votes - main
def parse_votes(self):
nested = [[self.prse_v(self.splt_v(vote))
for vote in self.splt_v_line(line)]
for line in self.vtlines]
flattened = []
for lst in nested:
for dct in lst:
flattened.append(dct)
return flattened
# Useful data objects
def record(self):
return {
'date' : unicode(self.date),
'year' : unicode(self.year),
'session' : unicode(self.session()),
'house' : unicode(self.house()),
'bill ID' : unicode(self.summary[1]),
'ayes' : unicode(self.summary[5]),
'nays' : unicode(self.summary[7]),
}
def iterRecords(self):
for vote in self.votes:
r = self.record.copy()
r['vote'] = vote['vote']
r['last name'] = vote['last name']
yield r
test = floor_vote_file(tfn)
import MySQLdb as dbapi2
import floorvotes_parse as v
import os
# Initial database crap
db = dbapi2.connect(db=r"db",
user="user",
passwd="XXXXX")
cur = db.cursor()
if db and cur: print "\nConnected to db.\n"
def commit(): db.commit()
def ext():
cur.close()
db.close()
print "\nConnection closed.\n"
# DATA
DIR = '/mydir'
files = [DIR+fn for fn in os.listdir(DIR)
if fn.startswith('fvote')]
# Add stuff
def add(r):
"""add a record"""
cur.execute(
u'''INSERT INTO ny_votes (vote_house, vote_date, vote_year, bill_id,
member_lastname, vote_value) VALUES
(%s , %s , %s ,
%s , %s , %s )''',
(r['house'] , r['date'] , r['year'],
r['bill ID'] , r['last name'], r['vote'])
)
#print "added", r['year'], r['bill ID']
def crt():
"""create table"""
SQL = """
CREATE TABLE ny_votes (openleg_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
vote_house int(1), vote_date int(5), vote_year int(2), bill_id varchar(8),
member_lastname varchar(50), vote_value varchar(10));
"""
cur.execute(SQL)
print "\nCreate ny_votes.\n"
def rst():
SQL = """DROP TABLE ny_votes"""
cur.execute(SQL)
print "\nDropped ny_votes.\n"
crt()
def addFile(fn):
"""parse and add all records in a file"""
n = 0
for votes in v.floor_vote_file(fn).iterVotes():
for record in votes.iterRecords():
add(record)
n += 1
print 'sucessfully added vote # ' + str(n)
def addAllFiles():
for file in files:
addFile(file)
if __name__=='__main__':
rst()
addAllFiles()
</code></pre>
| 1 | 2009-06-11T00:59:50Z | 5,736,532 | <p>I noticed that you use a lot of slit() calls. This is memory consuming, according to <a href="http://mail.python.org/pipermail/python-bugs-list/2006-January/031571.html" rel="nofollow">http://mail.python.org/pipermail/python-bugs-list/2006-January/031571.html</a> . You can start investigating this.</p>
| 2 | 2011-04-20T20:55:24Z | [
"python",
"memory-management"
] |
django import search path | 979,371 | <p>I'm configuring autocompletion for python and django in vim. One of the problems is that I need to set an environment variable DJANGO_SETTINGS_MODULE=myapp.settings. The django tutorial states that </p>
<blockquote>
<p>The value of DJANGO_SETTINGS_MODULE
should be in Python path syntax, e.g.
mysite.settings. Note that the
settings module should be on the
Python import search path.</p>
</blockquote>
<p><a href="http://docs.djangoproject.com/en/dev/topics/settings/" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/settings/</a></p>
<p>But if your app isn't in the import search path, how do you make it so that it is?</p>
| 2 | 2009-06-11T04:51:37Z | 979,393 | <p>Try appending the path to sys.path at runtime.</p>
<pre><code>import sys
sys.path.append('/path/to/myapp')
</code></pre>
| 3 | 2009-06-11T05:01:47Z | [
"python",
"django"
] |
django import search path | 979,371 | <p>I'm configuring autocompletion for python and django in vim. One of the problems is that I need to set an environment variable DJANGO_SETTINGS_MODULE=myapp.settings. The django tutorial states that </p>
<blockquote>
<p>The value of DJANGO_SETTINGS_MODULE
should be in Python path syntax, e.g.
mysite.settings. Note that the
settings module should be on the
Python import search path.</p>
</blockquote>
<p><a href="http://docs.djangoproject.com/en/dev/topics/settings/" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/settings/</a></p>
<p>But if your app isn't in the import search path, how do you make it so that it is?</p>
| 2 | 2009-06-11T04:51:37Z | 979,403 | <p>Add this in your <code>.bashrc</code> or <code>.bash_profile</code></p>
<p><code>export PATH=$PATH:/path/to/django/bin</code></p>
<p><code>export PYTHONPATH=$PYTHONPATH:/path/to/myapp</code></p>
| 3 | 2009-06-11T05:06:16Z | [
"python",
"django"
] |
django import search path | 979,371 | <p>I'm configuring autocompletion for python and django in vim. One of the problems is that I need to set an environment variable DJANGO_SETTINGS_MODULE=myapp.settings. The django tutorial states that </p>
<blockquote>
<p>The value of DJANGO_SETTINGS_MODULE
should be in Python path syntax, e.g.
mysite.settings. Note that the
settings module should be on the
Python import search path.</p>
</blockquote>
<p><a href="http://docs.djangoproject.com/en/dev/topics/settings/" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/settings/</a></p>
<p>But if your app isn't in the import search path, how do you make it so that it is?</p>
| 2 | 2009-06-11T04:51:37Z | 980,446 | <p>Three choices.</p>
<ol>
<li><p>Set <code>PYTHONPATH</code> environment variable to include your application's directory. Be sure it has an <code>__init__.py</code> file.</p></li>
<li><p>Create a <code>.pth</code> file in site-packages to point to your application's directory. </p></li>
<li><p>Install your application in site-packages.</p></li>
</ol>
<p>These are the three ways of "installing" a Python module. Read about the <a href="http://docs.python.org/library/site.html" rel="nofollow">site</a> module for more information.</p>
| 3 | 2009-06-11T10:46:06Z | [
"python",
"django"
] |
django import search path | 979,371 | <p>I'm configuring autocompletion for python and django in vim. One of the problems is that I need to set an environment variable DJANGO_SETTINGS_MODULE=myapp.settings. The django tutorial states that </p>
<blockquote>
<p>The value of DJANGO_SETTINGS_MODULE
should be in Python path syntax, e.g.
mysite.settings. Note that the
settings module should be on the
Python import search path.</p>
</blockquote>
<p><a href="http://docs.djangoproject.com/en/dev/topics/settings/" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/settings/</a></p>
<p>But if your app isn't in the import search path, how do you make it so that it is?</p>
| 2 | 2009-06-11T04:51:37Z | 27,721,624 | <p>import from path containing dir with module (with <code>__init__.py</code> file)</p>
<p>example:</p>
<pre><code>dm@batman:~/.local/15/lib/python2.7/site-packages $ pwd
/home/d/dm/.local/15/lib/python2.7/site-packages
dm@batman:~/.local/15/lib/python2.7/site-packages $ ls
django Django-1.5.11-py2.7.egg-info
dm@batman:~/.local/15/lib/python2.7/site-packages $ python
Python 2.7.3 (default, Feb 27 2014, 19:58:35)
[GCC 4.6.3] on linux2
>>> import sys
>>> sys.path.append("/home/d/dgaloc/.local/15/lib/python2.7/site-packages")
>>> import django
>>> django.VERSION
(1, 5, 11, 'final', 0)
</code></pre>
| 0 | 2014-12-31T13:10:03Z | [
"python",
"django"
] |
Getting all items less than a month old | 979,533 | <p>Is there a way to get all objects with a date less than a month ago in django.</p>
<p>Something like:</p>
<pre><code>items = Item.objects.filter(less than a month old).order_by(...)
</code></pre>
| 14 | 2009-06-11T05:46:51Z | 979,538 | <p>What is your definition of a "month"? 30 days? 31 days? Past that, this should do it:</p>
<pre><code>from datetime import datetime, timedelta
last_month = datetime.today() - timedelta(days=30)
items = Item.objects.filter(my_date__gte=last_month).order_by(...)
</code></pre>
<p>Takes advantange of the <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#gte">gte</a> field lookup.</p>
| 25 | 2009-06-11T05:50:09Z | [
"python",
"django",
"django-views"
] |
Getting all items less than a month old | 979,533 | <p>Is there a way to get all objects with a date less than a month ago in django.</p>
<p>Something like:</p>
<pre><code>items = Item.objects.filter(less than a month old).order_by(...)
</code></pre>
| 14 | 2009-06-11T05:46:51Z | 979,543 | <pre><code>items = Item.objects.filter(created_date__gte=aMonthAgo)
</code></pre>
<p>Where aMonthAgo would be calculated by datetime and timedelta.</p>
| 4 | 2009-06-11T05:51:41Z | [
"python",
"django",
"django-views"
] |
Adding SSL support to Python 2.6 | 979,551 | <p>I tried using the <code>ssl</code> module in Python 2.6 but I was told that it wasn't available. After installing OpenSSL, I recompiled 2.6 but the problem persists.</p>
<p>Any suggestions?</p>
| 2 | 2009-06-11T05:56:20Z | 979,598 | <p>Did you install the OpenSSL development libraries? I had to install <code>openssl-devel</code> on CentOS, for example. On Ubuntu, <code>sudo apt-get build-dep python2.5</code> did the trick (even for Python 2.6).</p>
| 4 | 2009-06-11T06:16:06Z | [
"python",
"ssl",
"openssl"
] |
Adding SSL support to Python 2.6 | 979,551 | <p>I tried using the <code>ssl</code> module in Python 2.6 but I was told that it wasn't available. After installing OpenSSL, I recompiled 2.6 but the problem persists.</p>
<p>Any suggestions?</p>
| 2 | 2009-06-11T05:56:20Z | 979,604 | <p>Use <a href="http://pexpect.sourceforge.net/pexpect.html" rel="nofollow">pexpect</a> with the openssl binary.</p>
| -4 | 2009-06-11T06:17:45Z | [
"python",
"ssl",
"openssl"
] |
Adding SSL support to Python 2.6 | 979,551 | <p>I tried using the <code>ssl</code> module in Python 2.6 but I was told that it wasn't available. After installing OpenSSL, I recompiled 2.6 but the problem persists.</p>
<p>Any suggestions?</p>
| 2 | 2009-06-11T05:56:20Z | 996,622 | <p>Use the binaries provided by python.org or by your OS distributor. It's a lot easier than building it yourself, and all the features are usually compiled in.</p>
<p>If you really need to build it yourself, you'll need to provide more information here about what build options you provided, what your environment is like, and perhaps provide some logs.</p>
| -1 | 2009-06-15T15:03:43Z | [
"python",
"ssl",
"openssl"
] |
Extracting IP from request in Python | 979,599 | <p>I have a Pythonic HTTP server that is supposed to determine client's IP. How do I do that in Python? Is there any way to get the request headers and extract it from there?</p>
<p>PS: I'm using WebPy.</p>
| 3 | 2009-06-11T06:16:20Z | 979,637 | <p>web.env.get('REMOTE_ADDR')</p>
| 3 | 2009-06-11T06:30:25Z | [
"python",
"http",
"header",
"request",
"ip"
] |
Extracting IP from request in Python | 979,599 | <p>I have a Pythonic HTTP server that is supposed to determine client's IP. How do I do that in Python? Is there any way to get the request headers and extract it from there?</p>
<p>PS: I'm using WebPy.</p>
| 3 | 2009-06-11T06:16:20Z | 980,339 | <p>Use web.ctx:</p>
<pre><code>class example:
def GET(self):
print web.ctx.ip
</code></pre>
<p>More info <a href="http://webpy.org/cookbook/ctx" rel="nofollow">here</a></p>
| 4 | 2009-06-11T10:15:13Z | [
"python",
"http",
"header",
"request",
"ip"
] |
Format an array of tuples in a nice "table" | 980,000 | <p>Say I have an array of tuples which look like that:</p>
<pre><code>[('url#id1', 'url#predicate1', 'value1'),
('url#id1', 'url#predicate2', 'value2'),
('url#id1', 'url#predicate3', 'value3'),
('url#id2', 'url#predicate1', 'value4'),
('url#id2', 'url#predicate2', 'value5')]
</code></pre>
<p>I would like be able to return a nice 2D array to be able to display it "as it" in my page through django.</p>
<p>The table would look like that:</p>
<pre><code>[['', 'predicate1', 'predicate2', 'predicate3'],
['id1', 'value1', 'value2', 'value3'],
['id2', 'value4', 'value5', '']]
</code></pre>
<p>You will notice that the 2nd item of each tuple became the table "column's title" and that we now have rows with ids and columns values.</p>
<p>How would you do that? Of course if you have a better idea than using the table example I gave I would be happy to have your thoughts :)</p>
<p>Right now I am generating a dict of dict and display that in django. But as my pairs of keys, values are not always in the same order in my dicts, then it cannot display correctly my data.</p>
<p>Thanks!</p>
| 0 | 2009-06-11T08:39:08Z | 980,016 | <p>Your dict of dict is probably on the right track. While you create that dict of dict, you could also maintain a list of ids and a list of predicates. That way, you can remember the ordering and build the table by looping through those lists.</p>
<p>using the <code>zip</code> function on your initial array wil give you three lists: the list of ids, the list of predicates and the list of values.</p>
<p>to get rid of duplicates, try the <code>reduce</code> function:</p>
<pre><code>list_without_duplicates = reduce(
lambda l, x: (l[-1] != x and l.append(x)) or l, list_with_duplicates, [])
</code></pre>
| 0 | 2009-06-11T08:45:50Z | [
"python",
"django",
"algorithm"
] |
Format an array of tuples in a nice "table" | 980,000 | <p>Say I have an array of tuples which look like that:</p>
<pre><code>[('url#id1', 'url#predicate1', 'value1'),
('url#id1', 'url#predicate2', 'value2'),
('url#id1', 'url#predicate3', 'value3'),
('url#id2', 'url#predicate1', 'value4'),
('url#id2', 'url#predicate2', 'value5')]
</code></pre>
<p>I would like be able to return a nice 2D array to be able to display it "as it" in my page through django.</p>
<p>The table would look like that:</p>
<pre><code>[['', 'predicate1', 'predicate2', 'predicate3'],
['id1', 'value1', 'value2', 'value3'],
['id2', 'value4', 'value5', '']]
</code></pre>
<p>You will notice that the 2nd item of each tuple became the table "column's title" and that we now have rows with ids and columns values.</p>
<p>How would you do that? Of course if you have a better idea than using the table example I gave I would be happy to have your thoughts :)</p>
<p>Right now I am generating a dict of dict and display that in django. But as my pairs of keys, values are not always in the same order in my dicts, then it cannot display correctly my data.</p>
<p>Thanks!</p>
| 0 | 2009-06-11T08:39:08Z | 985,296 | <p>Ok,</p>
<p>At last I came up with that code:</p>
<pre><code>columns = dict()
columnsTitles = []
rows = dict()
colIdxCounter = 1 # Start with 1 because the first col are ids
rowIdxCounter = 1 # Start with 1 because the columns titles
for i in dataset:
if not rows.has_key(i[0]):
rows[i[0]] = rowIdxCounter
rowIdxCounter += 1
if not columns.has_key(i[1]):
columns[i[1]] = colIdxCounter
colIdxCounter += 1
columnsTitles.append(i[1])
toRet = [columnsTitles]
for i in range(len(rows)):
toAppend = []
for j in range(colIdxCounter):
toAppend.append("")
toRet.append(toAppend)
for i in dataset:
toRet[rows[i[0]]][columns[i[1]]] = i[2]
for i in toRet:
print i
</code></pre>
<p>Please don't hesitate to comment/improve it :)</p>
| 0 | 2009-06-12T06:42:18Z | [
"python",
"django",
"algorithm"
] |
Finding rendered HTML element positions using WebKit (or Gecko) | 980,058 | <p>I would like to get the dimensions (coordinates) for all the HTML elements of a webpage as they are rendered by a browser, that is the positions they are rendered at. For example, <code>(top-left,top-right,bottom-left,bottom-right)</code></p>
<p>Could not find this in lxml. So, is there any library in Python that does this? I had also looked at Mechanize::Mozilla in Perl but, that seems difficult to configure/set-up.</p>
<p>I think the best way to do this for my requirement is to use a rendering engine - like WebKit or Gecko.</p>
<p>Are there any perl/python bindings available for the above two rendering engines? Google searches for tutorials on how to "plug-in" to the WebKit rendering engine is not very helpful. </p>
| 2 | 2009-06-11T08:57:28Z | 980,098 | <p>lxml isn't going to help you at all. It isn't concerned about front-end rendering at all.</p>
<p>To accurately work out how something renders, you need to render it. For that you need to hook into a browser, spawn the page and run some JS on the page to find the DOM element and get its attributes.</p>
<p>It's totally possible but I think you should start by looking at how website screenshot factories work (as they'll share 90% of the code you need to get a browser launching and showing the right page). </p>
<p>You may want to still use lxml to inject your javascript into the page.</p>
| 3 | 2009-06-11T09:08:12Z | [
"python",
"html",
"perl",
"rendering",
"rendering-engine"
] |
Finding rendered HTML element positions using WebKit (or Gecko) | 980,058 | <p>I would like to get the dimensions (coordinates) for all the HTML elements of a webpage as they are rendered by a browser, that is the positions they are rendered at. For example, <code>(top-left,top-right,bottom-left,bottom-right)</code></p>
<p>Could not find this in lxml. So, is there any library in Python that does this? I had also looked at Mechanize::Mozilla in Perl but, that seems difficult to configure/set-up.</p>
<p>I think the best way to do this for my requirement is to use a rendering engine - like WebKit or Gecko.</p>
<p>Are there any perl/python bindings available for the above two rendering engines? Google searches for tutorials on how to "plug-in" to the WebKit rendering engine is not very helpful. </p>
| 2 | 2009-06-11T08:57:28Z | 980,157 | <p>The problem is that current browsers don't render things quite the same. If you're looking for the standards compliant way of doing things, you could probably write something in Python to render the page, but that's going to be a hell of a lot of work.</p>
<p>You could use the <a href="http://docs.wxwidgets.org/2.6/wx_wxhtml.html" rel="nofollow">wxHTML control from wxWidgets</a> to render each part of a page individually to get an idea of it's size.</p>
<p>If you have a Mac you could try <a href="http://www.paulhammond.org/webkit2png/" rel="nofollow">WebKit</a>. That same article has some suggestions for solutions on other platforms too.</p>
| 0 | 2009-06-11T09:25:48Z | [
"python",
"html",
"perl",
"rendering",
"rendering-engine"
] |
Finding rendered HTML element positions using WebKit (or Gecko) | 980,058 | <p>I would like to get the dimensions (coordinates) for all the HTML elements of a webpage as they are rendered by a browser, that is the positions they are rendered at. For example, <code>(top-left,top-right,bottom-left,bottom-right)</code></p>
<p>Could not find this in lxml. So, is there any library in Python that does this? I had also looked at Mechanize::Mozilla in Perl but, that seems difficult to configure/set-up.</p>
<p>I think the best way to do this for my requirement is to use a rendering engine - like WebKit or Gecko.</p>
<p>Are there any perl/python bindings available for the above two rendering engines? Google searches for tutorials on how to "plug-in" to the WebKit rendering engine is not very helpful. </p>
| 2 | 2009-06-11T08:57:28Z | 980,619 | <p>I agree with <a href="http://stackoverflow.com/users/12870/oli">Oli</a>, rendering the page in question and inspecting DOM via JavaScript is the most practical way IMHO.</p>
<p>You might find <a href="http://jquery.com" rel="nofollow">jQuery</a> very useful here:</p>
<pre><code>$(document).ready(function() {
var elem = $("div#some_container_id h1")
var elem_offset = elem.offset();
/* elem_offset is an object literal:
elem_offset = { x: 25, y: 140 }
*/
var elem_height = elem.height();
var elem_width = elem.width();
/* bottom_right is then
{ x: elem_offset.x + elem_width,
y: elem_offset.y + elem_height }
});
</code></pre>
<p>Related documentation is <a href="http://docs.jquery.com/CSS" rel="nofollow">here</a>.</p>
| 1 | 2009-06-11T11:37:58Z | [
"python",
"html",
"perl",
"rendering",
"rendering-engine"
] |
Finding rendered HTML element positions using WebKit (or Gecko) | 980,058 | <p>I would like to get the dimensions (coordinates) for all the HTML elements of a webpage as they are rendered by a browser, that is the positions they are rendered at. For example, <code>(top-left,top-right,bottom-left,bottom-right)</code></p>
<p>Could not find this in lxml. So, is there any library in Python that does this? I had also looked at Mechanize::Mozilla in Perl but, that seems difficult to configure/set-up.</p>
<p>I think the best way to do this for my requirement is to use a rendering engine - like WebKit or Gecko.</p>
<p>Are there any perl/python bindings available for the above two rendering engines? Google searches for tutorials on how to "plug-in" to the WebKit rendering engine is not very helpful. </p>
| 2 | 2009-06-11T08:57:28Z | 980,671 | <p>Yes, Javascript is the way to go:</p>
<p>var allElements=document.getElementsByTagName("*"); will select all the elements in the page.</p>
<p>Then you can loop through this a extract the information you need from each element. Good documentation about getting the dimensions and positions of an element <a href="http://www.quirksmode.org/dom/tests/elementdimensions.html" rel="nofollow">is here.</a></p>
<p>getElementsByTagName returns a nodelist not an array (so if your JS changes your HTML those changes will be reflected in the nodelist), so I'd be tempted to build the data into an AJAX post and send it to a server when it's done.</p>
| 1 | 2009-06-11T11:51:05Z | [
"python",
"html",
"perl",
"rendering",
"rendering-engine"
] |
Finding rendered HTML element positions using WebKit (or Gecko) | 980,058 | <p>I would like to get the dimensions (coordinates) for all the HTML elements of a webpage as they are rendered by a browser, that is the positions they are rendered at. For example, <code>(top-left,top-right,bottom-left,bottom-right)</code></p>
<p>Could not find this in lxml. So, is there any library in Python that does this? I had also looked at Mechanize::Mozilla in Perl but, that seems difficult to configure/set-up.</p>
<p>I think the best way to do this for my requirement is to use a rendering engine - like WebKit or Gecko.</p>
<p>Are there any perl/python bindings available for the above two rendering engines? Google searches for tutorials on how to "plug-in" to the WebKit rendering engine is not very helpful. </p>
| 2 | 2009-06-11T08:57:28Z | 1,029,109 | <p>You might consider looking at <a href="http://search.cpan.org/dist/Test-WWW-Selenium/lib/WWW/Selenium.pm" rel="nofollow">WWW::Selenium</a>. With it (and <a href="http://seleniumhq.org/projects/remote-control/" rel="nofollow">selenium rc</a>) you can puppet string IE, Firefox, or Safari from inside of Perl.</p>
| 0 | 2009-06-22T19:56:38Z | [
"python",
"html",
"perl",
"rendering",
"rendering-engine"
] |
Finding rendered HTML element positions using WebKit (or Gecko) | 980,058 | <p>I would like to get the dimensions (coordinates) for all the HTML elements of a webpage as they are rendered by a browser, that is the positions they are rendered at. For example, <code>(top-left,top-right,bottom-left,bottom-right)</code></p>
<p>Could not find this in lxml. So, is there any library in Python that does this? I had also looked at Mechanize::Mozilla in Perl but, that seems difficult to configure/set-up.</p>
<p>I think the best way to do this for my requirement is to use a rendering engine - like WebKit or Gecko.</p>
<p>Are there any perl/python bindings available for the above two rendering engines? Google searches for tutorials on how to "plug-in" to the WebKit rendering engine is not very helpful. </p>
| 2 | 2009-06-11T08:57:28Z | 1,038,408 | <p>I was not able to find any easy solution (ie. Java/Perl/Python :) to hook onto Webkit/Gecko to solve the above rendering problem. The best I could find was the <a href="http://lobobrowser.org/" rel="nofollow">Lobo rendering engine</a> written in Java which has a very clear API that does exactly what I want - access to both DOM and the rendering attributes of HTML elements.</p>
<p><a href="http://jrex.mozdev.org/docs.html" rel="nofollow">JRex</a> is a Java wrapper to Gecko rendering engine.</p>
| 1 | 2009-06-24T13:38:28Z | [
"python",
"html",
"perl",
"rendering",
"rendering-engine"
] |
Finding rendered HTML element positions using WebKit (or Gecko) | 980,058 | <p>I would like to get the dimensions (coordinates) for all the HTML elements of a webpage as they are rendered by a browser, that is the positions they are rendered at. For example, <code>(top-left,top-right,bottom-left,bottom-right)</code></p>
<p>Could not find this in lxml. So, is there any library in Python that does this? I had also looked at Mechanize::Mozilla in Perl but, that seems difficult to configure/set-up.</p>
<p>I think the best way to do this for my requirement is to use a rendering engine - like WebKit or Gecko.</p>
<p>Are there any perl/python bindings available for the above two rendering engines? Google searches for tutorials on how to "plug-in" to the WebKit rendering engine is not very helpful. </p>
| 2 | 2009-06-11T08:57:28Z | 3,897,453 | <p>you have three main options:</p>
<p>1) <a href="http://www.gnu.org/software/pythonwebkit" rel="nofollow">http://www.gnu.org/software/pythonwebkit</a> is webkit-based;</p>
<p>2) python-comtypes for accessing MSHTML (windows only)</p>
<p>3) hulahop (python-xpcom) which is xulrunner-based</p>
<p>you should get the pyjamas-desktop source code and look in the pyjd/ directory for "startup" code which will allow you to create a web browser application and begin, once the "page loaded" callback has been called by the engine, to manipulate the DOM.</p>
<p>you can perform node-walking, and can access the properties of the DOM elements that you require. you can look at the pyjamas/library/pyjamas/DOM.py module to see many of the things that you will need to be using in order to do what you want.</p>
<p>but if the three options above are not enough then you should read the page <a href="http://wiki.python.org/moin/WebBrowserProgramming" rel="nofollow">http://wiki.python.org/moin/WebBrowserProgramming</a> for further options, many of which have been mentioned here by other people.</p>
<p>l.</p>
| 1 | 2010-10-09T19:02:50Z | [
"python",
"html",
"perl",
"rendering",
"rendering-engine"
] |
Difference between dir(â¦) and vars(â¦).keys() in Python? | 980,249 | <p>Is there a difference between <code>dir(â¦)</code> and <code>vars(â¦).keys()</code> in Python?</p>
<p>(I hope there is a difference, because otherwise this would break the "one way to do it" principle... :)</p>
| 30 | 2009-06-11T09:46:51Z | 980,276 | <p>The documentation has this to say about <a href="http://docs.python.org/library/functions.html"><code>dir</code></a>:</p>
<blockquote>
<p>Without arguments, return the list of names in the current local scope. <em>With an argument, attempt to return a list of valid attributes for that object.</em></p>
</blockquote>
<p>And this about <a href="http://docs.python.org/library/functions.html#vars"><code>vars</code></a>:</p>
<blockquote>
<p>Without arguments, return a dictionary corresponding to the current local symbol table. <em>With a module, class or class instance object as argument (or anything else that has a <code>__dict__</code> attribute), returns a dictionary corresponding to the objectâs symbol table.</em></p>
</blockquote>
<p>If you don't see the difference, maybe this will show you more:</p>
<pre><code>>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delsli
ce__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getit
em__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__',
'__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__r
educe__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__'
, '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'a
ppend', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'
]
>>> vars(list).keys()
['__getslice__', '__getattribute__', 'pop', 'remove', '__rmul__', '__lt__', '__s
izeof__', '__init__', 'count', 'index', '__delslice__', '__new__', '__contains__
', 'append', '__doc__', '__len__', '__mul__', 'sort', '__ne__', '__getitem__', '
insert', '__setitem__', '__add__', '__gt__', '__eq__', 'reverse', 'extend', '__d
elitem__', '__reversed__', '__imul__', '__setslice__', '__iter__', '__iadd__', '
__le__', '__repr__', '__hash__', '__ge__']
</code></pre>
<p>If you don't feel like reading through that, <code>dir</code> includes these attributes while <code>vars</code> does not:</p>
<pre><code>>>> set(dir(list)).difference(vars(list).keys())
set(['__str__', '__reduce__', '__subclasshook__', '__setattr__', '__reduce_ex__'
, '__format__', '__class__', '__delattr__'])
</code></pre>
| 18 | 2009-06-11T09:53:11Z | [
"python"
] |
Difference between dir(â¦) and vars(â¦).keys() in Python? | 980,249 | <p>Is there a difference between <code>dir(â¦)</code> and <code>vars(â¦).keys()</code> in Python?</p>
<p>(I hope there is a difference, because otherwise this would break the "one way to do it" principle... :)</p>
| 30 | 2009-06-11T09:46:51Z | 981,624 | <p>Python objects store their instance variables in a dictionary that belongs to the object. <code>vars(x)</code> returns this dictionary (as does <code>x.__dict__</code>). <code>dir(x)</code>, on the other hand, returns a dictionary of <code>x</code>'s "attributes, its class's attributes, and recursively the attributes of its class's base classes."</p>
<p>When you access an object's attribute using the dot operator, python does a lot more than just looking up the attribute in that objects dictionary. A common case is when <code>x</code> is an object of class <code>C</code> and you call a method <code>m</code> on it.</p>
<pre><code>class C(object):
def m(self):
print "m"
x = C()
x.m()
</code></pre>
<p>The method <code>m</code> is not stored in <code>x.__dict__</code>. It is an attribute of the class <code>C</code>.
When you call <code>x.m()</code>, python will begin by looking for m in <code>x.__dict__</code>, but it won't find it. However, it knows that <code>x</code> is an instance of <code>C</code>, so it will next look in <code>C.__dict__</code>, find it there, and call <code>m</code> with <code>x</code> as the first argument.</p>
<p>So the difference between <code>vars(x)</code> and <code>dir(x)</code> is that <code>dir(x)</code> does the extra work of looking in <code>x</code>'s class (and its bases) for attributes that are accessible from it, not just those attributes that are stored in <code>x</code>'s own symbol table. In the above example, <code>vars(x)</code> returns an empty dictionary, because <code>x</code> has no instance variables. However, <code>dir(x)</code> returns</p>
<pre><code>['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__',
'__hash__', '__init__', '__module__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'm']
</code></pre>
| 45 | 2009-06-11T14:57:52Z | [
"python"
] |
Difference between dir(â¦) and vars(â¦).keys() in Python? | 980,249 | <p>Is there a difference between <code>dir(â¦)</code> and <code>vars(â¦).keys()</code> in Python?</p>
<p>(I hope there is a difference, because otherwise this would break the "one way to do it" principle... :)</p>
| 30 | 2009-06-11T09:46:51Z | 39,463,891 | <p>Apart from Answers given, I would like to add that, using vars() with instances built-in types will give error, as instances builtin types do not have <code>__dict__</code> attribute.</p>
<p>eg. </p>
<pre><code>In [96]: vars([])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-96-a6cdd8d17b23> in <module>()
----> 1 vars([])
TypeError: vars() argument must have __dict__ attribute
</code></pre>
| 0 | 2016-09-13T06:54:42Z | [
"python"
] |
Python QuickBase API Help | 980,932 | <p>Hey, I'm having some trouble using the QuickBase API from Python. From the QuickBase guide, there are two methods of hitting the API: POST and GET. I can handle the GET calls, but some API methods require XML to be sent over POST. The link to the documentation is here: <a href="http://member.developer.intuit.com/MyIDN/technical_resources/quickbase/framework/httpapiref/HTML_API_Programmers_Guide.htm" rel="nofollow">http://member.developer.intuit.com/MyIDN/technical_resources/quickbase/framework/httpapiref/HTML_API_Programmers_Guide.htm</a></p>
<p>I guess I don't quite understand how to pack the XML payload into the POST request from python. Using the urllib.urlencode method, as well as any other way I've created POST requests requires a key-value type data structure, where all I have here is a string. Any help would be appreciated.</p>
| 1 | 2009-06-11T13:02:07Z | 981,468 | <p>Got it. For some reason The data I was sending in my POST needed to have a .strip() placed after it.</p>
| 0 | 2009-06-11T14:33:47Z | [
"python",
"xml",
"api",
"post",
"quickbase"
] |
Trying to create a Python Server | 981,033 | <p>I am looking at trying to create a python server, which allows me to run root commands on a Centos Server remotely, I would also like the server to be able to respond with the result's of the command.</p>
<p>I have found another question on here which has a basic python server, however it throws a error, the code is:</p>
<pre><code>#!/usr/bin/python
import os
import socket
print " Loading Bindings..."
settings = {}
line = 0
for each in open('/root/actions.txt', 'r'):
line = line + 1
each = each.rstrip()
if each <> "":
if each[0] <> '#':
a = each.partition(':')
if a[2]:
settings[a[0]] = a[2]
else:
print " Err @ line",line,":",each
print " Starting Server...",
port = 12345
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("", port))
print "OK."
print " Listening on port:", port
while True:
datagram = s.recv(1024)
if not datagram:
break
print "Rx Cmd:", datagram
if settings.has_key(datagram):
print "Launch:", settings[datagram]
os.system(settings[datagram]+" &")
s.close()
</code></pre>
<p>When i run using <code>python vzctl.py</code>. I get the following error:</p>
<pre><code> File "vzctl.py", line 9
each = each.rstrip()
^
SyntaxError: invalid syntax
</code></pre>
<p>Does anyone have any idea of the error, and if it would be possible to add the function of the server responding with the output of the command.</p>
<p>You can see the source of this script at : <a href="http://stackoverflow.com/questions/722172/how-can-i-have-a-php-script-run-a-shell-script-as-root">http://stackoverflow.com/questions/722172/how-can-i-have-a-php-script-run-a-shell-script-as-root</a></p>
<p>Thanks,
Ashley</p>
| 0 | 2009-06-11T13:21:18Z | 981,043 | <p>you need to keep indentation at the same level for each nested statement throughout your code.</p>
| 2 | 2009-06-11T13:23:37Z | [
"python",
"syntax-error"
] |
Trying to create a Python Server | 981,033 | <p>I am looking at trying to create a python server, which allows me to run root commands on a Centos Server remotely, I would also like the server to be able to respond with the result's of the command.</p>
<p>I have found another question on here which has a basic python server, however it throws a error, the code is:</p>
<pre><code>#!/usr/bin/python
import os
import socket
print " Loading Bindings..."
settings = {}
line = 0
for each in open('/root/actions.txt', 'r'):
line = line + 1
each = each.rstrip()
if each <> "":
if each[0] <> '#':
a = each.partition(':')
if a[2]:
settings[a[0]] = a[2]
else:
print " Err @ line",line,":",each
print " Starting Server...",
port = 12345
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("", port))
print "OK."
print " Listening on port:", port
while True:
datagram = s.recv(1024)
if not datagram:
break
print "Rx Cmd:", datagram
if settings.has_key(datagram):
print "Launch:", settings[datagram]
os.system(settings[datagram]+" &")
s.close()
</code></pre>
<p>When i run using <code>python vzctl.py</code>. I get the following error:</p>
<pre><code> File "vzctl.py", line 9
each = each.rstrip()
^
SyntaxError: invalid syntax
</code></pre>
<p>Does anyone have any idea of the error, and if it would be possible to add the function of the server responding with the output of the command.</p>
<p>You can see the source of this script at : <a href="http://stackoverflow.com/questions/722172/how-can-i-have-a-php-script-run-a-shell-script-as-root">http://stackoverflow.com/questions/722172/how-can-i-have-a-php-script-run-a-shell-script-as-root</a></p>
<p>Thanks,
Ashley</p>
| 0 | 2009-06-11T13:21:18Z | 981,095 | <p>On a different note: why not using <a href="http://www.twistedmatrix.com" rel="nofollow">TwistedMatrix</a>?</p>
| 2 | 2009-06-11T13:32:07Z | [
"python",
"syntax-error"
] |
Executing shell commands as given UID in Python | 981,052 | <p>I need a way to execute the os.system() module as different UID's. It would need to behave similar to the following BASH code (note these are not the exact commands I am executing):</p>
<pre><code>su user1
ls ~
mv file1
su user2
ls ~
mv file1
</code></pre>
<p>The target platform is GNU Linux Generic. </p>
<p>Of course I could just pass these to the os.system module, but how to send the password? Of course I could run the script as root, but that's sloppy and insecure.</p>
<p>Preferably I would like to do with without requiring any passwords to be in plain text.</p>
| 0 | 2009-06-11T13:24:49Z | 981,319 | <p>I think that's not trivial: you can do that with a shell because each command is launched into its own process, which has its own id. But with python, everything will have the uid of the python interpreted process (of course, assuming you don't launch subprocesses using the subprocess module and co). I don't know a way of changing the user of a process - I don't know if that's even possible - even if it were, you would at least need admin privileges.</p>
<p>What are you trying to do exactly ? This does not sound like the right thing to do for admin purpose, for example. Generally, admin scripts run in a priviledge user - because nobody knows the password of user 2 except user 2 (in theory). Being root means su user always work for a 'normal' user, without requesting password.</p>
| 3 | 2009-06-11T14:08:00Z | [
"python",
"linux",
"permissions",
"os.system"
] |
Executing shell commands as given UID in Python | 981,052 | <p>I need a way to execute the os.system() module as different UID's. It would need to behave similar to the following BASH code (note these are not the exact commands I am executing):</p>
<pre><code>su user1
ls ~
mv file1
su user2
ls ~
mv file1
</code></pre>
<p>The target platform is GNU Linux Generic. </p>
<p>Of course I could just pass these to the os.system module, but how to send the password? Of course I could run the script as root, but that's sloppy and insecure.</p>
<p>Preferably I would like to do with without requiring any passwords to be in plain text.</p>
| 0 | 2009-06-11T13:24:49Z | 981,347 | <p>The function you're looking for is called <code>os.seteuid</code>. I'm afraid you probably won't escape executing the script as root, in any case, but I think you can use the <code>capabilities(7)</code> framework to 'fence in' the execution a little, so that it can change users--but not do any of the other things the superuser can.</p>
<p>Alternatively, you <em>might</em> be able to do this with PAM. But generally speaking, there's no 'neat' way to do this, and David Cournapeau is absolutely right that it's traditional for admin scripts to run with privileges.</p>
| 1 | 2009-06-11T14:12:20Z | [
"python",
"linux",
"permissions",
"os.system"
] |
Executing shell commands as given UID in Python | 981,052 | <p>I need a way to execute the os.system() module as different UID's. It would need to behave similar to the following BASH code (note these are not the exact commands I am executing):</p>
<pre><code>su user1
ls ~
mv file1
su user2
ls ~
mv file1
</code></pre>
<p>The target platform is GNU Linux Generic. </p>
<p>Of course I could just pass these to the os.system module, but how to send the password? Of course I could run the script as root, but that's sloppy and insecure.</p>
<p>Preferably I would like to do with without requiring any passwords to be in plain text.</p>
| 0 | 2009-06-11T13:24:49Z | 981,467 | <p>maybe sudo can help you here, otherwise you must be root to execute os.setuid</p>
<p>alternatively if you want to have fun you can use pexpect to do things
something like this, you can improve over this</p>
<pre><code>p = pexpect.spawn("su guest")
p.logfile = sys.stdout
p.expect('Password:')
p.sendline("guest")
</code></pre>
| 2 | 2009-06-11T14:33:39Z | [
"python",
"linux",
"permissions",
"os.system"
] |
Executing shell commands as given UID in Python | 981,052 | <p>I need a way to execute the os.system() module as different UID's. It would need to behave similar to the following BASH code (note these are not the exact commands I am executing):</p>
<pre><code>su user1
ls ~
mv file1
su user2
ls ~
mv file1
</code></pre>
<p>The target platform is GNU Linux Generic. </p>
<p>Of course I could just pass these to the os.system module, but how to send the password? Of course I could run the script as root, but that's sloppy and insecure.</p>
<p>Preferably I would like to do with without requiring any passwords to be in plain text.</p>
| 0 | 2009-06-11T13:24:49Z | 982,185 | <p>Somewhere along the line, some process or other is going to need an effective UID of 0 (root), because only such a process can set the effective UID to an arbitrary other UID.</p>
<p>At the shell, the <code>su</code> command is a SUID root program; it is appropriately privileged (POSIX jargon) and can set the real and effective UID. Similarly, the <code>sudo</code> command can do the same job. With <code>sudo</code>, you can also configure which commands and UID are allowed. The crucial difference is that <code>su</code> requires the target user's password to let you in; <code>sudo</code> requires the password of the user running it.</p>
<p>There is, of course, the issue of whether a user should know the passwords of other users. In general, no user should know any other user's password.</p>
<p>Scripting UID changes is hard. You can do:</p>
<pre><code>su altuser -c "commands to execute as altuser"
sudo -u altuser commands to execute as altuser
</code></pre>
<p>However, <code>su</code> will demand a password from the controlling terminal (and will fail if there is no controlling terminal). If you use <code>sudo</code>, it will cache credentials (or can be configured to do so) so you only get asked once for a password - but it will prompt the first time just like <code>su</code> does.</p>
<p>Working around the prompting is hard. You can use tools parallel to <code>expect</code> which handle pseudo-ttys for you. However, you are then faced with storing passwords in scripts (not a good idea) or somehow stashing them out of sight.</p>
<p><hr></p>
<p>The tool I use for the job is one I wrote, called <code>asroot</code>. It allows me to control precisely the UID and GID attributes that the child process should have. But it is designed to only allow me to use it - that is, at compile time, the authorized username is specified (of course, that can be changed). However, I can do things like:</p>
<pre><code>asroot -u someone -g theirgrp -C -A othergrp -m 022 -- somecmd arg1 ...
</code></pre>
<p>This sets the real and effective UID to 'someone', sets the primary group to 'theirgrp', removes all auxilliary groups, and adds 'othergrp' (so the process belongs to just two groups) and sets the umask to 0222; it then executes 'somecmd' with the arguments given.</p>
<p>For a specific user who needs limited (or not so limited) access to other user accounts, this works well. As a general solution, it is not so hot; <code>sudo</code> is better in most respects, but still requires a password (which <code>asroot</code> does not).</p>
| 1 | 2009-06-11T16:33:53Z | [
"python",
"linux",
"permissions",
"os.system"
] |
Python: printing floats / modifying the output | 981,189 | <p>I have a problem which prints out a float variable. What I should get is for example: 104.0625, 119.0, 72.0. I know how to control the number of decimals but how do I control the number of zeros specifically, i.e. when the float is 104.06250000 the program should print 104.0625 but when the float is 119.00000 or 72.000000 etc., I should have 119.0 and 72.0.</p>
| 6 | 2009-06-11T13:48:26Z | 981,218 | <p>The <code>'%2.2f'</code> operator will only do the same number of decimals regardless of how many significant digits the number has. You will have to identify this in the number and manually frig the format. You might be able to short-cut this by printing to a string with a large number of decimal places and strip all of the trailing zeros.</p>
<p>A trivial function to do this might look something like <code>intel_format()</code> in the sample below:</p>
<pre><code>import re
foo_string = '%.10f' % (1.33333)
bar_string = '%.10f' % (1)
print 'Raw Output'
print foo_string
print bar_string
print 'Strip trailing zeros'
print re.split ('0+$', foo_string)[0]
print re.split ('0+$', bar_string)[0]
print 'Intelligently strip trailing zeros'
def intel_format (nn):
formatted = '%.10f' % (nn)
stripped = re.split('0+$', formatted)
if stripped[0][-1] == '.':
return stripped[0] + '0'
else:
return stripped[0]
print intel_format (1.3333)
print intel_format (1.0)
</code></pre>
<p>When run, you get this output:</p>
<pre><code>Raw Output
1.3333300000
1.0000000000
Strip trailing zeros
1.33333
1.
Intelligently strip trailing zeros
1.3333
1.0
</code></pre>
| 1 | 2009-06-11T13:53:22Z | [
"python",
"floating-point"
] |
Python: printing floats / modifying the output | 981,189 | <p>I have a problem which prints out a float variable. What I should get is for example: 104.0625, 119.0, 72.0. I know how to control the number of decimals but how do I control the number of zeros specifically, i.e. when the float is 104.06250000 the program should print 104.0625 but when the float is 119.00000 or 72.000000 etc., I should have 119.0 and 72.0.</p>
| 6 | 2009-06-11T13:48:26Z | 981,224 | <p>I don't think there is a pre-defined format for this - format in python are inherited from C, and I am pretty sure you don't have the desired format in C.</p>
<p>Now, in python 3, you have the <strong>format</strong> special function, where you can do your own formatting. Removing the last zeros in python is very easy: just use the strip method:</p>
<pre><code>a = 1.23040000
print str(a).rstrip('0')
</code></pre>
<p>If you want to keep a 0 after the decimal point, that's not very difficult either.</p>
| 5 | 2009-06-11T13:54:35Z | [
"python",
"floating-point"
] |
Python: printing floats / modifying the output | 981,189 | <p>I have a problem which prints out a float variable. What I should get is for example: 104.0625, 119.0, 72.0. I know how to control the number of decimals but how do I control the number of zeros specifically, i.e. when the float is 104.06250000 the program should print 104.0625 but when the float is 119.00000 or 72.000000 etc., I should have 119.0 and 72.0.</p>
| 6 | 2009-06-11T13:48:26Z | 981,233 | <p>How about using the decimal module?</p>
<p>From the <a href="http://docs.python.org/library/decimal.html">documentation</a>:</p>
<p>"The decimal module incorporates a notion of significant places so that 1.30 + 1.20 is 2.50. The trailing zero is kept to indicate significance. This is the customary presentation for monetary applications. For multiplication, the âschoolbookâ approach uses all the figures in the multiplicands. <strong>For instance, 1.3 * 1.2 gives 1.56 while 1.30 * 1.20 gives 1.5600.</strong>"</p>
<p>The <a href="http://docs.python.org/library/decimal.html#decimal.Decimal.normalize">normalize()</a> function removes trailing zeros:</p>
<pre><code>>>> from decimal import *
>>> d1 = Decimal("1.30")
>>> d2 = Decimal("1.20")
>>> d3
Decimal("1.5600")
>>> d3.normalize()
Decimal("1.56")
</code></pre>
| 9 | 2009-06-11T13:55:55Z | [
"python",
"floating-point"
] |
Python: printing floats / modifying the output | 981,189 | <p>I have a problem which prints out a float variable. What I should get is for example: 104.0625, 119.0, 72.0. I know how to control the number of decimals but how do I control the number of zeros specifically, i.e. when the float is 104.06250000 the program should print 104.0625 but when the float is 119.00000 or 72.000000 etc., I should have 119.0 and 72.0.</p>
| 6 | 2009-06-11T13:48:26Z | 5,612,090 | <pre><code>def float_remove_zeros(input_val):
"""
Remove the last zeros after the decimal point:
* 34.020 -> 34.02
* 34.000 -> 34
* 0 -> 0
* 0.0 -> 0
"""
stripped = input_val
if input_val != 0:
stripped = str(input_val).rstrip('0').rstrip('.')
else:
stripped = 0
return stripped
</code></pre>
| -2 | 2011-04-10T13:37:35Z | [
"python",
"floating-point"
] |
Python: printing floats / modifying the output | 981,189 | <p>I have a problem which prints out a float variable. What I should get is for example: 104.0625, 119.0, 72.0. I know how to control the number of decimals but how do I control the number of zeros specifically, i.e. when the float is 104.06250000 the program should print 104.0625 but when the float is 119.00000 or 72.000000 etc., I should have 119.0 and 72.0.</p>
| 6 | 2009-06-11T13:48:26Z | 12,497,279 | <p>I think the simplest way would be "round" function. in your case:</p>
<pre><code>>>> round(104.06250000,4)
104.0625
</code></pre>
| 4 | 2012-09-19T14:52:43Z | [
"python",
"floating-point"
] |
Python: printing floats / modifying the output | 981,189 | <p>I have a problem which prints out a float variable. What I should get is for example: 104.0625, 119.0, 72.0. I know how to control the number of decimals but how do I control the number of zeros specifically, i.e. when the float is 104.06250000 the program should print 104.0625 but when the float is 119.00000 or 72.000000 etc., I should have 119.0 and 72.0.</p>
| 6 | 2009-06-11T13:48:26Z | 25,035,464 | <p>You can use the string method format if you're using Python 2.6 and above.</p>
<pre><code>>>> print "{0}".format(1.0)
1.0
>>> print "{0}".format(1.01)
1.01
>>> print "{0}".format(float(1))
1.0
>>> print "{0}".format(1.010000)
1.01
</code></pre>
| 0 | 2014-07-30T11:18:27Z | [
"python",
"floating-point"
] |
Can Windows drivers be written in Python? | 981,200 | <p>Can Windows drivers be written in Python?</p>
| 10 | 2009-06-11T13:50:06Z | 981,216 | <p>Python runs in a virtual machine, so no.</p>
<p>BUT:</p>
<p>You could write a compiler that translates Python code to machine language. Once you've done that, you can do it.</p>
| 1 | 2009-06-11T13:53:12Z | [
"python",
"windows",
"drivers"
] |
Can Windows drivers be written in Python? | 981,200 | <p>Can Windows drivers be written in Python?</p>
| 10 | 2009-06-11T13:50:06Z | 981,227 | <p>Never say never but eh.. no</p>
<p>You might be able to hack something together to run user-mode parts of drivers in python. But kernel-mode stuff can only be done in C or assembly.</p>
| 0 | 2009-06-11T13:54:52Z | [
"python",
"windows",
"drivers"
] |
Can Windows drivers be written in Python? | 981,200 | <p>Can Windows drivers be written in Python?</p>
| 10 | 2009-06-11T13:50:06Z | 981,251 | <p>No they cannot. Windows drivers must be written in a language that can </p>
<ol>
<li>Interface with the C based API</li>
<li>Compile down to machine code </li>
</ol>
<p>Then again, there's nothing stopping you from writing a compiler that translates python to machine code ;)</p>
| 0 | 2009-06-11T13:59:38Z | [
"python",
"windows",
"drivers"
] |
Can Windows drivers be written in Python? | 981,200 | <p>Can Windows drivers be written in Python?</p>
| 10 | 2009-06-11T13:50:06Z | 981,268 | <p>I don't know the restrictions on drivers on windows (memory allocation schemes, dynamic load of libraries and all), but you may be able to embed a python interpreter in your driver, at which point you can do whatever you want. Not that I think it is a good idea :)</p>
| 1 | 2009-06-11T14:01:27Z | [
"python",
"windows",
"drivers"
] |
Can Windows drivers be written in Python? | 981,200 | <p>Can Windows drivers be written in Python?</p>
| 10 | 2009-06-11T13:50:06Z | 981,320 | <p>The definitive answer is not without embedding an interpreter in your otherwise C/assembly driver. Unless someone has a framework available, then the answer is no. Once you have the interpreter and bindings in place then the rest of the logic could be done in Python.</p>
<p>However, writing drivers is one of the things for which C is best suited. I imagine the resulting Python code would look a whole lot like C code and defeat the purpose of the interpreter overhead.</p>
| 3 | 2009-06-11T14:08:06Z | [
"python",
"windows",
"drivers"
] |
Can Windows drivers be written in Python? | 981,200 | <p>Can Windows drivers be written in Python?</p>
| 10 | 2009-06-11T13:50:06Z | 981,423 | <p>A good way to gain insight why this is practically impossible is by reading <a href="http://www.microsoft.com/whdc/driver/kernel/KMcode.mspx" rel="nofollow">Microsoft's advice</a> on the use of C++ in drivers. As a derivative of C, the use of C++ appears to be straightforward. In practice, not so. </p>
<p>For instance, you must decide for every function (and really every assembly instruction) whether it's in pageable or non-pageable memory. This requires extensions to C, careful use of new C++ features, or in this case a special extension to the Python language and VM. In addition, your driver-compatible VM would also have to deal with the different IRQLs - there's a hierarchy of "levels" which restrict what you can and cannot do. </p>
| 3 | 2009-06-11T14:26:22Z | [
"python",
"windows",
"drivers"
] |
Can Windows drivers be written in Python? | 981,200 | <p>Can Windows drivers be written in Python?</p>
| 10 | 2009-06-11T13:50:06Z | 981,462 | <p>Yes. You cannot create the "classic" kernel-mode drivers. However, starting with XP, Windows offers a <a href="http://www.microsoft.com/whdc/driver/wdf/UMDF.mspx">User-Mode Driver Framework</a>. They can't do everything, obviously - any driver used in booting the OS obviously has to be kernel-mode. But with UMDF, you only need to implement COM components. </p>
<p>Besides boot-time drivers, you also can't write UMDF drivers that:</p>
<ul>
<li>Handle interrupts</li>
<li>Directly access hardware, such as direct memory access (DMA)</li>
<li>have strict timing loops</li>
<li>Use nonpaged pool or other resources that are reserved for kernel mode</li>
</ul>
| 16 | 2009-06-11T14:32:37Z | [
"python",
"windows",
"drivers"
] |
Stomp Broadcast with Rabbitmq and Python | 981,291 | <p>Im trying to move a system from using morbid to rabbitmq, but I cannot seem to get the same broadcast behaviour morbid supplied by default. By broadcast I mean that when a message is added to the queue, every consumer recieves it. With rabbit, when a message is added they are distributed round robin style to every listener.</p>
<p>Can anyone tell me how to achieve the same kind of message distribution?</p>
<p>The stomp library used below is <a href="http://code.google.com/p/stomppy/" rel="nofollow">http://code.google.com/p/stomppy/</a></p>
<p>Failing being able to do with with stomp, even a amqplib example would really help.</p>
<p>My code at present looks like this</p>
<p>The Consumer</p>
<pre><code>import stomp
class MyListener(object):
def on_error(self, headers, message):
print 'recieved an error %s' % message
def on_message(self, headers, message):
print 'recieved a message %s' % message
conn = stomp.Connection([('0.0.0.0', 61613), ('127.0.0.1', 61613)], 'user', 'password')
conn.set_listener('', MyListener())
conn.start()
conn.connect(username="user", password="password")
headers = {}
conn.subscribe(destination='/topic/demoqueue', ack='auto')
while True:
pass
conn.disconnect()
</code></pre>
<p>And the sender looks like this</p>
<pre><code>import stomp
class MyListener(object):
def on_error(self, headers, message):
print 'recieved an error %s' % message
def on_message(self, headers, message):
print 'recieved a message %s' % message
conn = stomp.Connection([('0.0.0.0', 61613), ('127.0.0.1', 61613)], 'user', 'password')
conn.set_listener('', MyListener())
conn.start()
conn.connect(username="user", password="password")
headers = {}
conn.subscribe(destination='/topic/demotopic', ack='auto')
while True:
pass
conn.disconnect()
</code></pre>
| 2 | 2009-06-11T14:03:17Z | 981,503 | <p>Apparently you can't do with directly with STOMP; there is a <a href="http://lists.rabbitmq.com/pipermail/rabbitmq-discuss/2008-September/001775.html" rel="nofollow">mailing list thread</a> that shows all the hoops you have to jump through to get broadcast working with stomp (it involves some lower-level AMPQ stuff).</p>
| 3 | 2009-06-11T14:40:35Z | [
"python",
"broadcast",
"rabbitmq",
"stomp"
] |
Stomp Broadcast with Rabbitmq and Python | 981,291 | <p>Im trying to move a system from using morbid to rabbitmq, but I cannot seem to get the same broadcast behaviour morbid supplied by default. By broadcast I mean that when a message is added to the queue, every consumer recieves it. With rabbit, when a message is added they are distributed round robin style to every listener.</p>
<p>Can anyone tell me how to achieve the same kind of message distribution?</p>
<p>The stomp library used below is <a href="http://code.google.com/p/stomppy/" rel="nofollow">http://code.google.com/p/stomppy/</a></p>
<p>Failing being able to do with with stomp, even a amqplib example would really help.</p>
<p>My code at present looks like this</p>
<p>The Consumer</p>
<pre><code>import stomp
class MyListener(object):
def on_error(self, headers, message):
print 'recieved an error %s' % message
def on_message(self, headers, message):
print 'recieved a message %s' % message
conn = stomp.Connection([('0.0.0.0', 61613), ('127.0.0.1', 61613)], 'user', 'password')
conn.set_listener('', MyListener())
conn.start()
conn.connect(username="user", password="password")
headers = {}
conn.subscribe(destination='/topic/demoqueue', ack='auto')
while True:
pass
conn.disconnect()
</code></pre>
<p>And the sender looks like this</p>
<pre><code>import stomp
class MyListener(object):
def on_error(self, headers, message):
print 'recieved an error %s' % message
def on_message(self, headers, message):
print 'recieved a message %s' % message
conn = stomp.Connection([('0.0.0.0', 61613), ('127.0.0.1', 61613)], 'user', 'password')
conn.set_listener('', MyListener())
conn.start()
conn.connect(username="user", password="password")
headers = {}
conn.subscribe(destination='/topic/demotopic', ack='auto')
while True:
pass
conn.disconnect()
</code></pre>
| 2 | 2009-06-11T14:03:17Z | 986,949 | <p>I finally figured out how to do it by creating an exchange for each "recieving group", im not sure how well rabbit will do with thousands of exchanges, so you might want to figure test this heavily before trying it in production</p>
<p>In the sending code:</p>
<pre><code>conn.send(str(i), exchange=exchange, destination='')
</code></pre>
<p>The blank destination is required, all I care about is sending to that exchange</p>
<p>To recieve</p>
<pre><code>import stomp
import sys
from amqplib import client_0_8 as amqp
#read in the exchange name so I can set up multiple recievers for different exchanges to tset
exchange = sys.argv[1]
conn = amqp.Connection(host="localhost:5672", userid="username", password="password",
virtual_host="/", insist=False)
chan = conn.channel()
chan.access_request('/', active=True, write=True, read=True)
#declare my exchange
chan.exchange_declare(exchange, 'topic')
#not passing a queue name means I get a new unique one back
qname,_,_ = chan.queue_declare()
#bind the queue to the exchange
chan.queue_bind(qname, exchange=exchange)
class MyListener(object):
def on_error(self, headers, message):
print 'recieved an error %s' % message
def on_message(self, headers, message):
print 'recieved a message %s' % message
conn = stomp.Connection([('0.0.0.0', 61613), ('127.0.0.1', 61613)], 'browser', 'browser')
conn.set_listener('', MyListener())
conn.start()
conn.connect(username="username", password="password")
headers = {}
#subscribe to the queue
conn.subscribe(destination=qname, ack='auto')
while True:
pass
conn.disconnect()
</code></pre>
| 3 | 2009-06-12T14:32:06Z | [
"python",
"broadcast",
"rabbitmq",
"stomp"
] |
Send output from a python server back to client | 981,348 | <p>I now have a small java script server working correctly, called by:</p>
<pre><code><?php
$handle = fsockopen("udp://78.129.148.16",12345);
fwrite($handle,"vzctlrestart110");
fclose($handle);
?>
</code></pre>
<p>On a remote server the following python server is running and executing the comand's</p>
<pre><code>#!/usr/bin/python
import os
import socket
print " Loading Bindings..."
settings = {}
line = 0
for each in open('/root/actions.txt', 'r'):
line = line + 1
each = each.rstrip()
if each != "":
if each[0] != '#':
a = each.partition(':')
if a[2]:
settings[a[0]] = a[2]
else:
print " Err @ line",line,":",each
print " Starting Server...",
port = 12345
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("", port))
print "OK."
print " Listening on port:", port
while True:
datagram = s.recv(1024)
if not datagram:
break
print "Rx Cmd:", datagram
if settings.has_key(datagram):
print "Launch:", settings[datagram]
os.system(settings[datagram]+" &")
s.close()
</code></pre>
<p>Is it possible to easily send the output of the command back, when the server is started and is running a command the output is shown in the ssh window, however I want this output to be sent back to the browser of the original client, maybe setting the browser to wait for 15 seconds and then check for any data received via the socket.</p>
<p>I know I am asking quite a lot, however I am creating a PHP script which I have a large knowledge about, however my python knowledge lacks greatly.</p>
<p>Thanks,
Ashley</p>
| 0 | 2009-06-11T14:12:24Z | 981,387 | <p>Yes, you can read the output of the command. For this I would recommend the Python <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> module. Then you can just <code>s.write()</code> it back.</p>
<p>Naturally this has some implications, you would probably have to let your PHP script run for a while longer since the process may be running slow.</p>
<pre><code># The pipe behaves like a file object in Python.
process = Popen(cmd, shell=True, stdout=PIPE)
process_output = ""
while process.poll():
process_output += process.stdout.read(256)
s.write(process_output)
# Better yet.
process = Popen(cmd, shell=true, stdout=PIPE)
stdout, stderr = process.communicate() # will read and wait for process to end.
s.write(stdout)
</code></pre>
<p>Integrated into your code:</p>
<pre><code># ... snip ...
import subprocess
con, addr = s.accept()
while True:
datagram = con.recv(1024)
if not datagram:
break
print "Rx Cmd:", datagram
if settings.has_key(datagram):
print "Launch:", settings[datagram]
process = subprocess.Popen(settings[datagram]+" &", shell=True, stdout=subprocess.PIPE)
stdout, stderr = process.communicate()
con.send(stdout)
con.close()
s.close()
</code></pre>
| 1 | 2009-06-11T14:20:42Z | [
"python",
"sockets"
] |
Send output from a python server back to client | 981,348 | <p>I now have a small java script server working correctly, called by:</p>
<pre><code><?php
$handle = fsockopen("udp://78.129.148.16",12345);
fwrite($handle,"vzctlrestart110");
fclose($handle);
?>
</code></pre>
<p>On a remote server the following python server is running and executing the comand's</p>
<pre><code>#!/usr/bin/python
import os
import socket
print " Loading Bindings..."
settings = {}
line = 0
for each in open('/root/actions.txt', 'r'):
line = line + 1
each = each.rstrip()
if each != "":
if each[0] != '#':
a = each.partition(':')
if a[2]:
settings[a[0]] = a[2]
else:
print " Err @ line",line,":",each
print " Starting Server...",
port = 12345
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("", port))
print "OK."
print " Listening on port:", port
while True:
datagram = s.recv(1024)
if not datagram:
break
print "Rx Cmd:", datagram
if settings.has_key(datagram):
print "Launch:", settings[datagram]
os.system(settings[datagram]+" &")
s.close()
</code></pre>
<p>Is it possible to easily send the output of the command back, when the server is started and is running a command the output is shown in the ssh window, however I want this output to be sent back to the browser of the original client, maybe setting the browser to wait for 15 seconds and then check for any data received via the socket.</p>
<p>I know I am asking quite a lot, however I am creating a PHP script which I have a large knowledge about, however my python knowledge lacks greatly.</p>
<p>Thanks,
Ashley</p>
| 0 | 2009-06-11T14:12:24Z | 981,396 | <p>Here's an example of how to get the output of a command:</p>
<pre><code>>>> import commands
>>> s = commands.getoutput("ls *")
>>> s
'client.py'
</code></pre>
| 0 | 2009-06-11T14:22:04Z | [
"python",
"sockets"
] |
Get original path from django filefield | 981,371 | <p>My django app accepts two files (in this case a jad and jar combo). Is there a way I can preserve the folders they came from?</p>
<p>I need this so I can check later that they came from the same path.</p>
<p>(And later on accept a whole load of files and be able to work out which came from the same folder).</p>
| 1 | 2009-06-11T14:17:02Z | 981,666 | <p>I think that is not possible, most browsers at least firefox3.0 do not allow fullpath to be seen, so even from JavaScript side you can not get full path
If you could get full path you can send it to server, but I think you will have to be satisfied with file name</p>
| 1 | 2009-06-11T15:03:11Z | [
"python",
"django",
"file",
"forms",
"field"
] |
Using a Django custom model method property in order_by() | 981,375 | <p>I'm currently learning Django and some of my models have custom methods to get values formatted in a specific way. Is it possible to use the value of one of these custom methods that I've defined as a property in a model with order_by()?</p>
<p>Here is an example that demonstrates how the property is implemented.</p>
<pre><code>class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField(blank=True, verbose_name='e-mail')
def _get_full_name(self):
return u'%s %s' % (self.first_name, self.last_name)
full_name = property(_get_full_name)
def __unicode__(self):
return self.full_name
</code></pre>
<p>With this model I can do:</p>
<pre><code>>>> Author.objects.all()
[<Author: John Doh>, <Author: Jane Doh>, <Author: Andre Miller>]
>>> Author.objects.order_by('first_name')
[<Author: Andre Miller>, <Author: Jane Doh>, <Author: John Doh>]
</code></pre>
<p>But I cannot do:</p>
<pre><code>>>> Author.objects.order_by('full_name')
FieldError: Cannot resolve keyword 'full_name' into field. Choices are: book, email, first_name, id, last_name
</code></pre>
<p>What would be the correct way to use order_by on a custom property like this?</p>
| 34 | 2009-06-11T14:18:10Z | 981,802 | <p>No, you can't do that. <code>order_by</code> is applied at the database level, but the database can't know anything about your custom Python methods.</p>
<p>You can either use the separate fields to order:</p>
<pre><code>Author.objects.order_by('first_name', 'last_name')
</code></pre>
<p>or do the ordering in Python:</p>
<pre><code>sorted(Author.objects.all(), key=lambda a: a.full_name)
</code></pre>
| 54 | 2009-06-11T15:27:12Z | [
"python",
"django",
"django-models"
] |
Run a Python project in Eclipse as root | 981,411 | <p>I use Eclipse as my IDE, and when I run my application I wish the application itself to run as root. My program currently checks if it is root, and if not it restarts itself with <code>gksudo</code>. The output, however, isn't written to the console. I can't use <code>sudo</code>, since it doesn't give me a graphical prompt. (While my program is CLI, Eclipse doesn't permit console interaction afaict)</p>
<p>What's the "right" way to be elevating my application?</p>
| 8 | 2009-06-11T14:24:30Z | 981,839 | <p>Restrictive execution dominates. I believe that Eclipse does permit console interaction, but a quick and dirty, brute force approach would be to use suid if you're not concerned about security. Or throw up your own graphical prompt in Tkinter/other and use a bit of <a href="http://sourceforge.net/projects/pexpect/" rel="nofollow">Expect magic</a> to spawn and respond to the sudo process. Careful with these, however :)</p>
| 2 | 2009-06-11T15:32:24Z | [
"python",
"eclipse",
"root",
"sudo",
"gksudo"
] |
Run a Python project in Eclipse as root | 981,411 | <p>I use Eclipse as my IDE, and when I run my application I wish the application itself to run as root. My program currently checks if it is root, and if not it restarts itself with <code>gksudo</code>. The output, however, isn't written to the console. I can't use <code>sudo</code>, since it doesn't give me a graphical prompt. (While my program is CLI, Eclipse doesn't permit console interaction afaict)</p>
<p>What's the "right" way to be elevating my application?</p>
| 8 | 2009-06-11T14:24:30Z | 982,463 | <p>It may not be an ideal solution, but the rare times that I need this same functionality I end up just running Eclipse as root.</p>
| 3 | 2009-06-11T17:23:51Z | [
"python",
"eclipse",
"root",
"sudo",
"gksudo"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.