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
Can I change BeautifulSoup's behavior regarding converting XML tags to lowercase?
891,690
<p>I'm working on code to parse a configuration file written in XML, where the XML tags are mixed case and the case is significant. Beautiful Soup appears to convert XML tags to lowercase by default, and I would like to change this behavior.</p> <p>I'm not the first to ask a question on this subject [see <a href="http://stackoverflow.com/questions/567999/preventing-beautifulsoup-from-converting-my-xml-tags-to-lowercase">here</a>]. However, I did not understand the answer given to that question and in BeautifulSoup-3.1.0.1 BeautifulSoup.py does not appear to contain any instances of "<code>encodedName</code>" or "<code>Tag.__str__</code>"</p>
6
2009-05-21T07:03:24Z
904,863
<p>According to Leonard Richardson, creator|maintainer of Beautiful Soup, you <a href="http://groups.google.com/group/beautifulsoup/browse%5Fthread/thread/ff6910752566df78" rel="nofollow">can't</a>.</p>
3
2009-05-24T23:30:54Z
[ "python", "xml", "beautifulsoup" ]
Can I change BeautifulSoup's behavior regarding converting XML tags to lowercase?
891,690
<p>I'm working on code to parse a configuration file written in XML, where the XML tags are mixed case and the case is significant. Beautiful Soup appears to convert XML tags to lowercase by default, and I would like to change this behavior.</p> <p>I'm not the first to ask a question on this subject [see <a href="http://stackoverflow.com/questions/567999/preventing-beautifulsoup-from-converting-my-xml-tags-to-lowercase">here</a>]. However, I did not understand the answer given to that question and in BeautifulSoup-3.1.0.1 BeautifulSoup.py does not appear to contain any instances of "<code>encodedName</code>" or "<code>Tag.__str__</code>"</p>
6
2009-05-21T07:03:24Z
1,223,014
<p>It's much better to use <a href="http://codespeak.net/lxml/" rel="nofollow">lxml</a>. It's much, much faster than BeautifulSoup. It has a compatibility API for BeautifulSoup too if you don't want to learn the lxml API.</p> <p><a href="http://blog.ianbicking.org/2008/12/10/lxml-an-underappreciated-web-scraping-library/" rel="nofollow">Ian Blicking agrees</a>.</p> <p>There's no reason to use BeautifulSoup anymore, unless you're on Google App Engine or something where anything not purely Python isn't allowed.</p> <p>It's more suited for XML as well.</p>
1
2009-08-03T15:35:17Z
[ "python", "xml", "beautifulsoup" ]
Strings and file
891,895
<p>Suppose this is my list of languages.</p> <pre><code>aList = ['Python','C','C++','Java'] </code></pre> <p>How can i write to a file like :</p> <pre><code>Python : ... C : ... C++ : ... Java : ... </code></pre> <p>I have used rjust() to achieve this. Without it how can i do ?</p> <p>Here i have done manually. I want to <strong>avoid</strong> that,ie; it shuould be <strong>ordered automatically</strong>.</p>
2
2009-05-21T08:28:20Z
891,897
<p>You can do this with <a href="http://www.python.org/doc/2.5.2/lib/typesseq-strings.html" rel="nofollow">string formatting</a> operators</p> <pre><code>f=open('filename.txt','w') for item in aList: print &gt;&gt;f, "%-20s : ..." % item </code></pre> <p>The 20 is the field width, while the "-" indicates to left justify it.</p>
5
2009-05-21T08:29:38Z
[ "python", "string", "order" ]
Strings and file
891,895
<p>Suppose this is my list of languages.</p> <pre><code>aList = ['Python','C','C++','Java'] </code></pre> <p>How can i write to a file like :</p> <pre><code>Python : ... C : ... C++ : ... Java : ... </code></pre> <p>I have used rjust() to achieve this. Without it how can i do ?</p> <p>Here i have done manually. I want to <strong>avoid</strong> that,ie; it shuould be <strong>ordered automatically</strong>.</p>
2
2009-05-21T08:28:20Z
891,907
<p>Do you mean this?</p> <pre><code>&gt;&gt;&gt; languages = ['Python','C','C++','Java'] &gt;&gt;&gt; f = open('myfile.txt', 'w') &gt;&gt;&gt; print('\n'.join('%-10s: ...' % l for l in languages), file=f) &gt;&gt;&gt; f.close() &gt;&gt;&gt; print(open('myfile.txt').read()) Python : ... C : ... C++ : ... Java : ... </code></pre> <p>This uses the <a href="http://docs.python.org/3.0/library/string.html#format-specification-mini-language" rel="nofollow">format specification mini language</a>. Note the <a href="http://docs.python.org/3.0/library/functions.html#print" rel="nofollow">print</a> statement uses 3.0 syntax. (Yeah I changed this since <a href="http://stackoverflow.com/questions/891895/strings-and-file/891897#891897">Brian's</a> answer links to the 2.5.2 docs. Just for contrast.)</p>
5
2009-05-21T08:33:24Z
[ "python", "string", "order" ]
Strings and file
891,895
<p>Suppose this is my list of languages.</p> <pre><code>aList = ['Python','C','C++','Java'] </code></pre> <p>How can i write to a file like :</p> <pre><code>Python : ... C : ... C++ : ... Java : ... </code></pre> <p>I have used rjust() to achieve this. Without it how can i do ?</p> <p>Here i have done manually. I want to <strong>avoid</strong> that,ie; it shuould be <strong>ordered automatically</strong>.</p>
2
2009-05-21T08:28:20Z
892,218
<p>Automatically determine colon position (using max width) and language order (sorted alphabetically):</p> <pre><code>languages = ['Python','C','C++','Java'] maxlen = max(map(len, languages)) with open('langs.txt', 'w') as f: for L in sorted(languages): f.write('%-*s: ...\n'% (maxlen, L)) print open('langs.txt').read() </code></pre> <p>Output:</p> <pre><code>C : ... C++ : ... Java : ... Python: ... </code></pre>
0
2009-05-21T10:13:19Z
[ "python", "string", "order" ]
Satchmo donations
891,934
<p>Can anyone share some pointers on building a Donations module for Satchmo? I'm comfortable customizing Satchmo's product models etc but unable to find anything related to Donations</p> <p>I realize it's possible to create a Donations virtual product but as far as I can tell this still requires setting the amount beforehand ($5, $10 etc). I want users to be able to donate arbitrary amounts</p>
1
2009-05-21T08:46:17Z
901,050
<p>It looks like the *satchmo_cart_details_query* signal is the way to go about doing this. It allows you to add a price change value (in my case, donation amount) to a cart item</p> <p>I'll post the full solution if anyone is interested</p>
2
2009-05-23T07:08:55Z
[ "python", "django", "e-commerce", "satchmo" ]
filter with string return nothing
891,935
<p>I run into follow problem. Did I miss anything?</p> <pre><code>Association.all().count() 1 Association.all().fetch(1) [Association(**{'server_url': u'server-url', 'handle': u'handle2', 'secret': 'c2VjcmV0\n', 'issued': 1242892477L, 'lifetime': 200L, 'assoc_type': u'HMAC-SHA1'})] Association.all().filter('server_url =', 'server-url').count() 0 # expect 1 Association.all().filter('server_url =', u'server-url').count() 0 # expect 1 Association.all().filter('issued &gt;', 0).count() 1 </code></pre>
0
2009-05-21T08:46:18Z
892,459
<p>What kind of property is "server_url"?</p> <p>If it is a TextProperty, then it cannot be used in filters.</p> <blockquote> <p>Unlike StringProperty, a TextProperty value can be more than 500 bytes long. However, TextProperty values are not indexed, and cannot be used in filters or sort orders.</p> </blockquote> <p><a href="http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#TextProperty" rel="nofollow">http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#TextProperty</a> </p>
5
2009-05-21T11:28:19Z
[ "python", "google-app-engine" ]
How would one build an smtp client in python?
892,196
<p>buildin an smtp client in python . which can send mail , and also show that mail has been received through any mail service for example gmail !!</p>
0
2009-05-21T10:04:53Z
892,230
<p>If you want the Python standard library to do the work for you (recommended!), use <a href="http://docs.python.org/library/smtplib.html" rel="nofollow">smtplib</a>. To see whether sending the mail worked, just open your inbox ;)</p> <p>If you want to implement the protocol yourself (is this homework?), then read up on the <a href="http://www.ietf.org/rfc/rfc0821.txt" rel="nofollow">SMTP protocol</a> and use e.g. the <a href="http://docs.python.org/library/socket.html" rel="nofollow">socket</a> module.</p>
1
2009-05-21T10:17:32Z
[ "python", "smtp" ]
How would one build an smtp client in python?
892,196
<p>buildin an smtp client in python . which can send mail , and also show that mail has been received through any mail service for example gmail !!</p>
0
2009-05-21T10:04:53Z
892,264
<p>Depends what you mean by "received". It's possible to verify "delivery" of a message to a server but there is no 100% reliable guarantee it actually ended up in a mailbox. smtplib will throw an exception on certain conditions (like the remote end reporting user not found) but just as often the remote end will accept the mail and then either filter it or send a bounce notice at a later time.</p>
0
2009-05-21T10:30:51Z
[ "python", "smtp" ]
How would one build an smtp client in python?
892,196
<p>buildin an smtp client in python . which can send mail , and also show that mail has been received through any mail service for example gmail !!</p>
0
2009-05-21T10:04:53Z
892,306
<p>Create mail messages (possibly with multipart attachments) with <a href="http://docs.python.org/library/email.html" rel="nofollow">email</a>.</p> <blockquote> <p>The <code>email</code> package is a library for managing email messages, including MIME and other RFC 2822-based message documents.</p> </blockquote> <p>Send mail using <a href="http://docs.python.org/library/smtplib.html" rel="nofollow">smtplib</a></p> <blockquote> <p>The <code>smtplib</code> module defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon.</p> </blockquote> <p>If you are interested in browsing a remote mailbox (for example, to see if the message you sent have arrived), you need a mail service accessible via a known protocol. An popular example is the <a href="http://docs.python.org/library/imaplib.html" rel="nofollow"><code>imaplib</code></a> module, implementing the <a href="http://en.wikipedia.org/wiki/IMAP4" rel="nofollow"><code>IMAP4</code> protocol</a>. <code>IMAP</code> is <a href="http://mail.google.com/support/bin/topic.py?hl=en&amp;topic=12806" rel="nofollow">supported by <code>gmail</code></a>.</p> <blockquote> <p>This (<code>imaplib</code>) module defines three classes, IMAP4, IMAP4_SSL and IMAP4_stream, which encapsulate a connection to an IMAP4 server and implement a large subset of the IMAP4rev1 client protocol as defined in RFC 2060. It is backward compatible with IMAP4 (RFC 1730) servers, but note that the STATUS command is not supported in IMAP4.</p> </blockquote>
2
2009-05-21T10:43:14Z
[ "python", "smtp" ]
Detect & Record Audio in Python
892,199
<p>I need to capture audio clips as WAV files that I can then pass to another bit of python for processing. The problem is that I need to determine when there is audio present and then record it, stop when it goes silent and then pass that file to the processing module.</p> <p>I'm thinking it should be possible with the wave module to detect when there is pure silence and discard it then as soon as something other than silence is detected start recording, then when the line goes silent again stop the recording.</p> <p>Just can't quite get my head around it, can anyone get me started with a basic example.</p>
49
2009-05-21T10:05:32Z
892,293
<p>I believe the WAVE module does not support recording, just processing existing files. You might want to look at <a href="http://people.csail.mit.edu/hubert/pyaudio/">PyAudio</a> for actually recording. WAV is about the world's simplest file format. In paInt16 you just get a signed integer representing a level, and closer to 0 is quieter. I can't remember if WAV files are high byte first or low byte, but something like this ought to work (sorry, I'm not really a python programmer:</p> <pre><code>from array import array # you'll probably want to experiment on threshold # depends how noisy the signal threshold = 10 max_value = 0 as_ints = array('h', data) max_value = max(as_ints) if max_value &gt; threshold: # not silence </code></pre> <p>PyAudio code for recording kept for reference:</p> <pre><code>import pyaudio import sys chunk = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 44100 RECORD_SECONDS = 5 p = pyaudio.PyAudio() stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, output=True, frames_per_buffer=chunk) print "* recording" for i in range(0, 44100 / chunk * RECORD_SECONDS): data = stream.read(chunk) # check for silence here by comparing the level with 0 (or some threshold) for # the contents of data. # then write data or not to a file print "* done" stream.stop_stream() stream.close() p.terminate() </code></pre>
36
2009-05-21T10:39:35Z
[ "python", "wav", "audio-recording" ]
Detect & Record Audio in Python
892,199
<p>I need to capture audio clips as WAV files that I can then pass to another bit of python for processing. The problem is that I need to determine when there is audio present and then record it, stop when it goes silent and then pass that file to the processing module.</p> <p>I'm thinking it should be possible with the wave module to detect when there is pure silence and discard it then as soon as something other than silence is detected start recording, then when the line goes silent again stop the recording.</p> <p>Just can't quite get my head around it, can anyone get me started with a basic example.</p>
49
2009-05-21T10:05:32Z
892,400
<p>You might want to look at <a href="http://www.csounds.com/" rel="nofollow">csounds</a>, also. It has several API's, including Python. It might be able to interact with an A-D interface and gather sound samples.</p>
0
2009-05-21T11:08:23Z
[ "python", "wav", "audio-recording" ]
Detect & Record Audio in Python
892,199
<p>I need to capture audio clips as WAV files that I can then pass to another bit of python for processing. The problem is that I need to determine when there is audio present and then record it, stop when it goes silent and then pass that file to the processing module.</p> <p>I'm thinking it should be possible with the wave module to detect when there is pure silence and discard it then as soon as something other than silence is detected start recording, then when the line goes silent again stop the recording.</p> <p>Just can't quite get my head around it, can anyone get me started with a basic example.</p>
49
2009-05-21T10:05:32Z
6,743,593
<p>As a follow up to Nick Fortescue's answer, here's a more complete example of how to record from the microphone and process the resulting data:</p> <pre><code>from sys import byteorder from array import array from struct import pack import pyaudio import wave THRESHOLD = 500 CHUNK_SIZE = 1024 FORMAT = pyaudio.paInt16 RATE = 44100 def is_silent(snd_data): "Returns 'True' if below the 'silent' threshold" return max(snd_data) &lt; THRESHOLD def normalize(snd_data): "Average the volume out" MAXIMUM = 16384 times = float(MAXIMUM)/max(abs(i) for i in snd_data) r = array('h') for i in snd_data: r.append(int(i*times)) return r def trim(snd_data): "Trim the blank spots at the start and end" def _trim(snd_data): snd_started = False r = array('h') for i in snd_data: if not snd_started and abs(i)&gt;THRESHOLD: snd_started = True r.append(i) elif snd_started: r.append(i) return r # Trim to the left snd_data = _trim(snd_data) # Trim to the right snd_data.reverse() snd_data = _trim(snd_data) snd_data.reverse() return snd_data def add_silence(snd_data, seconds): "Add silence to the start and end of 'snd_data' of length 'seconds' (float)" r = array('h', [0 for i in xrange(int(seconds*RATE))]) r.extend(snd_data) r.extend([0 for i in xrange(int(seconds*RATE))]) return r def record(): """ Record a word or words from the microphone and return the data as an array of signed shorts. Normalizes the audio, trims silence from the start and end, and pads with 0.5 seconds of blank sound to make sure VLC et al can play it without getting chopped off. """ p = pyaudio.PyAudio() stream = p.open(format=FORMAT, channels=1, rate=RATE, input=True, output=True, frames_per_buffer=CHUNK_SIZE) num_silent = 0 snd_started = False r = array('h') while 1: # little endian, signed short snd_data = array('h', stream.read(CHUNK_SIZE)) if byteorder == 'big': snd_data.byteswap() r.extend(snd_data) silent = is_silent(snd_data) if silent and snd_started: num_silent += 1 elif not silent and not snd_started: snd_started = True if snd_started and num_silent &gt; 30: break sample_width = p.get_sample_size(FORMAT) stream.stop_stream() stream.close() p.terminate() r = normalize(r) r = trim(r) r = add_silence(r, 0.5) return sample_width, r def record_to_file(path): "Records from the microphone and outputs the resulting data to 'path'" sample_width, data = record() data = pack('&lt;' + ('h'*len(data)), *data) wf = wave.open(path, 'wb') wf.setnchannels(1) wf.setsampwidth(sample_width) wf.setframerate(RATE) wf.writeframes(data) wf.close() if __name__ == '__main__': print("please speak a word into the microphone") record_to_file('demo.wav') print("done - result written to demo.wav") </code></pre>
64
2011-07-19T07:24:04Z
[ "python", "wav", "audio-recording" ]
Detect & Record Audio in Python
892,199
<p>I need to capture audio clips as WAV files that I can then pass to another bit of python for processing. The problem is that I need to determine when there is audio present and then record it, stop when it goes silent and then pass that file to the processing module.</p> <p>I'm thinking it should be possible with the wave module to detect when there is pure silence and discard it then as soon as something other than silence is detected start recording, then when the line goes silent again stop the recording.</p> <p>Just can't quite get my head around it, can anyone get me started with a basic example.</p>
49
2009-05-21T10:05:32Z
15,693,662
<p>The pyaudio website has many examples that are pretty short and clear: <a href="http://people.csail.mit.edu/hubert/pyaudio/" rel="nofollow">http://people.csail.mit.edu/hubert/pyaudio/</a></p>
2
2013-03-28T23:01:19Z
[ "python", "wav", "audio-recording" ]
Detect & Record Audio in Python
892,199
<p>I need to capture audio clips as WAV files that I can then pass to another bit of python for processing. The problem is that I need to determine when there is audio present and then record it, stop when it goes silent and then pass that file to the processing module.</p> <p>I'm thinking it should be possible with the wave module to detect when there is pure silence and discard it then as soon as something other than silence is detected start recording, then when the line goes silent again stop the recording.</p> <p>Just can't quite get my head around it, can anyone get me started with a basic example.</p>
49
2009-05-21T10:05:32Z
16,385,946
<p>Thanks to cryo for improved version that I based my tested code below:</p> <pre><code>#Instead of adding silence at start and end of recording (values=0) I add the original audio . This makes audio sound more natural as volume is &gt;0. See trim() #I also fixed issue with the previous code - accumulated silence counter needs to be cleared once recording is resumed. from array import array from struct import pack from sys import byteorder import copy import pyaudio import wave THRESHOLD = 500 # audio levels not normalised. CHUNK_SIZE = 1024 SILENT_CHUNKS = 3 * 44100 / 1024 # about 3sec FORMAT = pyaudio.paInt16 FRAME_MAX_VALUE = 2 ** 15 - 1 NORMALIZE_MINUS_ONE_dB = 10 ** (-1.0 / 20) RATE = 44100 CHANNELS = 1 TRIM_APPEND = RATE / 4 def is_silent(data_chunk): """Returns 'True' if below the 'silent' threshold""" return max(data_chunk) &lt; THRESHOLD def normalize(data_all): """Amplify the volume out to max -1dB""" # MAXIMUM = 16384 normalize_factor = (float(NORMALIZE_MINUS_ONE_dB * FRAME_MAX_VALUE) / max(abs(i) for i in data_all)) r = array('h') for i in data_all: r.append(int(i * normalize_factor)) return r def trim(data_all): _from = 0 _to = len(data_all) - 1 for i, b in enumerate(data_all): if abs(b) &gt; THRESHOLD: _from = max(0, i - TRIM_APPEND) break for i, b in enumerate(reversed(data_all)): if abs(b) &gt; THRESHOLD: _to = min(len(data_all) - 1, len(data_all) - 1 - i + TRIM_APPEND) break return copy.deepcopy(data_all[_from:(_to + 1)]) def record(): """Record a word or words from the microphone and return the data as an array of signed shorts.""" p = pyaudio.PyAudio() stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, output=True, frames_per_buffer=CHUNK_SIZE) silent_chunks = 0 audio_started = False data_all = array('h') while True: # little endian, signed short data_chunk = array('h', stream.read(CHUNK_SIZE)) if byteorder == 'big': data_chunk.byteswap() data_all.extend(data_chunk) silent = is_silent(data_chunk) if audio_started: if silent: silent_chunks += 1 if silent_chunks &gt; SILENT_CHUNKS: break else: silent_chunks = 0 elif not silent: audio_started = True sample_width = p.get_sample_size(FORMAT) stream.stop_stream() stream.close() p.terminate() data_all = trim(data_all) # we trim before normalize as threshhold applies to un-normalized wave (as well as is_silent() function) data_all = normalize(data_all) return sample_width, data_all def record_to_file(path): "Records from the microphone and outputs the resulting data to 'path'" sample_width, data = record() data = pack('&lt;' + ('h' * len(data)), *data) wave_file = wave.open(path, 'wb') wave_file.setnchannels(CHANNELS) wave_file.setsampwidth(sample_width) wave_file.setframerate(RATE) wave_file.writeframes(data) wave_file.close() if __name__ == '__main__': print("Wait in silence to begin recording; wait in silence to terminate") record_to_file('demo.wav') print("done - result written to demo.wav") </code></pre>
11
2013-05-05T15:14:56Z
[ "python", "wav", "audio-recording" ]
to send emails from Google appengine
892,266
<p>I have a web server with Django(Python programming language), hosted with Apache server. I would like to configure Google Appengine for the email server. My web server should be able to use Google Appengine, when it makes any email send using EmailMessage or sendmail infrastructure of Google mail api. I learnt that using remote_api I can access google appengine server from my main web server. However, I could not access the mail apis supported by google appengine. Is the remote_api is strictly for datastore?? So, only the db reads can be done from it but no other api calls??</p>
0
2009-05-21T10:31:09Z
892,427
<p>The example code for the remote APi gives you an interactive console from which you can access <em>any</em> of the modules in your application. I see no requirement that they be only datastore operations.</p>
2
2009-05-21T11:18:57Z
[ "python", "django", "google-app-engine", "mail-server" ]
to send emails from Google appengine
892,266
<p>I have a web server with Django(Python programming language), hosted with Apache server. I would like to configure Google Appengine for the email server. My web server should be able to use Google Appengine, when it makes any email send using EmailMessage or sendmail infrastructure of Google mail api. I learnt that using remote_api I can access google appengine server from my main web server. However, I could not access the mail apis supported by google appengine. Is the remote_api is strictly for datastore?? So, only the db reads can be done from it but no other api calls??</p>
0
2009-05-21T10:31:09Z
894,179
<p>You may want to use a third-party SMTP relaying service. <a href="http://www.birds-eye.net/article%5Farchive/smtp%5Fmail%5Frelay%5Fservices.htm" rel="nofollow">Here's a list</a>.</p> <p>Most of them have a simple API that lets you forward your email to their service. That way, you're not bound by the AppEngine's limits. The more reputable ones also take care of headers necessary so your app isn't tagged as a spam sender (which hopefully, it isn't :-)</p>
0
2009-05-21T17:47:33Z
[ "python", "django", "google-app-engine", "mail-server" ]
Unit testing with nose: tests at compile time?
892,297
<p>Is it possible for the nose unit testing framework to perform tests during the compilation phase of a module?</p> <p>In fact, I'd like to test something with the following structure:</p> <pre><code>x = 123 # [x is used here...] def test_x(): assert (x == 123) del x # Deleted because I don't want to clutter the module with unnecessary attributes </code></pre> <p>nosetests tells me that x is undefined, as it apparently runs test_x() after importing the module. Is there a way of having nose perform test during the compilation phase while having the module free unnecessary resources after using them?</p>
3
2009-05-21T10:40:21Z
892,416
<p>A simple way to handle this would be to have a TESTING flag, and write:</p> <pre><code>if not TESTING: del x </code></pre> <p>However, you won't really be properly testing your modules as the tests will be running under different circumstances to your code.</p> <p>The proper answer is that you shouldn't really be bothering with manually cleaning up variables, unless you have actually had some major performance problems because of them. Read up on <a href="http://c2.com/cgi/wiki?PrematureOptimization" rel="nofollow">Premature Optimization</a>, it's an important concept. Fix the problems you have, not the ones you maybe could have one day.</p>
2
2009-05-21T11:14:36Z
[ "python", "unit-testing", "nose" ]
Unit testing with nose: tests at compile time?
892,297
<p>Is it possible for the nose unit testing framework to perform tests during the compilation phase of a module?</p> <p>In fact, I'd like to test something with the following structure:</p> <pre><code>x = 123 # [x is used here...] def test_x(): assert (x == 123) del x # Deleted because I don't want to clutter the module with unnecessary attributes </code></pre> <p>nosetests tells me that x is undefined, as it apparently runs test_x() after importing the module. Is there a way of having nose perform test during the compilation phase while having the module free unnecessary resources after using them?</p>
3
2009-05-21T10:40:21Z
904,574
<p>According to nose's main developer Jason Pellerin, the nose unit testing framework <a href="http://groups.google.com/group/nose-users/browse%5Fthread/thread/5fd8e112fe8f5c88?hl=en" rel="nofollow">cannot run tests during compilation</a>. This is a potential annoyance if both the module "construction" and the test routines need to access a certain variable (which would be deleted in the absence of tests).</p> <p>One option is to discourage the user from using any of these unnecessarily saved variables by prepending "__" to their name (this works also for variables used in class construction: they can be one of these "private" globals).</p> <p>Another, perhaps cleaner option is to dedicate a module to the task: this module would contain variables that are shared by the module "itself" (i.e. without tests) and its tests (and that would not have to be shared were it not for the tests).</p> <p>The problem with these option is that variables that could be deleted if there were no tests are instead kept in memory, just because it is better for the test code to use them. At least, with the above two options, the user should not be tempted to use these variables, nor should he feel the need to wonder what they are!</p>
2
2009-05-24T20:23:12Z
[ "python", "unit-testing", "nose" ]
Overriding a static method in python
893,015
<p>Referring to the <a href="http://stackoverflow.com/questions/114214/class-method-differences-in-python-bound-unbound-and-static/114267#114267">first answer</a> about python's bound and unbound methods here, I have a question:</p> <pre><code>class Test: def method_one(self): print "Called method_one" @staticmethod def method_two(): print "Called method_two" @staticmethod def method_three(): Test.method_two() class T2(Test): @staticmethod def method_two(): print "T2" a_test = Test() a_test.method_one() a_test.method_two() a_test.method_three() b_test = T2() b_test.method_three() </code></pre> <p>produces output:</p> <pre><code>Called method_one Called method_two Called method_two Called method_two </code></pre> <p>Is there a way to override a static method in python?</p> <p>I expected <code>b_test.method_three()</code> to print "T2", but it doesn't (prints "Called method_two" instead).</p>
27
2009-05-21T13:47:09Z
893,060
<p>In the form that you are using there, you are explicitly specifying what class's static <code>method_two</code> to call. If <code>method_three</code> was a classmethod, and you called <code>cls.method_two</code>, you would get the results that you wanted:</p> <pre><code>class Test: def method_one(self): print "Called method_one" @staticmethod def method_two(): print "Called method_two" @classmethod def method_three(cls): cls.method_two() class T2(Test): @staticmethod def method_two(): print "T2" a_test = Test() a_test.method_one() a_test.method_two() a_test.method_three() b_test = T2() b_test.method_three() Test.method_two() T2.method_three() </code></pre>
37
2009-05-21T13:56:59Z
[ "python", "static", "override" ]
Overriding a static method in python
893,015
<p>Referring to the <a href="http://stackoverflow.com/questions/114214/class-method-differences-in-python-bound-unbound-and-static/114267#114267">first answer</a> about python's bound and unbound methods here, I have a question:</p> <pre><code>class Test: def method_one(self): print "Called method_one" @staticmethod def method_two(): print "Called method_two" @staticmethod def method_three(): Test.method_two() class T2(Test): @staticmethod def method_two(): print "T2" a_test = Test() a_test.method_one() a_test.method_two() a_test.method_three() b_test = T2() b_test.method_three() </code></pre> <p>produces output:</p> <pre><code>Called method_one Called method_two Called method_two Called method_two </code></pre> <p>Is there a way to override a static method in python?</p> <p>I expected <code>b_test.method_three()</code> to print "T2", but it doesn't (prints "Called method_two" instead).</p>
27
2009-05-21T13:47:09Z
893,074
<p>The behavior you see is the expected behavior. Static methods are... static. When you call <code>method_three()</code> defined in <code>Test</code> it will certainly call <code>method_two()</code> defined by <code>Test</code>.</p> <p>As for how to "get around" this proper behavior...</p> <p>The very best way is to make methods virtual when you want virtual behavior. If you're stuck with some library code with a static method that you wish were virtual then you might look deeper to see if there's a reason or if it's just an oversight.</p> <p>Otherwise, you can define a new <code>method_three()</code> in <code>T2</code> that calls <code>T2.method_two()</code>.</p>
4
2009-05-21T14:00:27Z
[ "python", "static", "override" ]
Overriding a static method in python
893,015
<p>Referring to the <a href="http://stackoverflow.com/questions/114214/class-method-differences-in-python-bound-unbound-and-static/114267#114267">first answer</a> about python's bound and unbound methods here, I have a question:</p> <pre><code>class Test: def method_one(self): print "Called method_one" @staticmethod def method_two(): print "Called method_two" @staticmethod def method_three(): Test.method_two() class T2(Test): @staticmethod def method_two(): print "T2" a_test = Test() a_test.method_one() a_test.method_two() a_test.method_three() b_test = T2() b_test.method_three() </code></pre> <p>produces output:</p> <pre><code>Called method_one Called method_two Called method_two Called method_two </code></pre> <p>Is there a way to override a static method in python?</p> <p>I expected <code>b_test.method_three()</code> to print "T2", but it doesn't (prints "Called method_two" instead).</p>
27
2009-05-21T13:47:09Z
38,119,459
<p>Additionally, if you want to call the "virtual static" function without an instance, you could proceed like so:</p> <ol> <li><p>Declare the function in the base class non-static like so:</p> <pre><code>class Base: def my_fun(self): print('my_fun base') class Derived(Base): def my_fun(self): print('my_fun derived') </code></pre></li> <li><p>Call it by passing the class type, which is not an instance, like so:</p> <pre><code>Derived.my_fun(Derived) </code></pre></li> </ol> <p>Note, this is useful if you have a variable "class_type", which is only known during run time.</p>
0
2016-06-30T09:45:09Z
[ "python", "static", "override" ]
Seeing escape characters when pressing the arrow keys in python shell
893,053
<p>In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.</p> <p>But after I ssh into another machine and start <code>python</code> there, I get sessions like:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; ^[[A </code></pre> <p>where the last character comes from arrow-up. Or, using arrow-left:</p> <pre><code>&gt;&gt;&gt; impor^[[D </code></pre> <p>How can I fix this?</p> <p>In the regular bash, arrow keys work fine. The weird behavior is just in the interactive python (or perl etc.) shell.</p>
47
2009-05-21T13:55:32Z
893,067
<p>Have you tried using a different SSH client? Some SSH clients have special, built-in keymappings for different remote processes. I ran into this one a lot with emacs.</p> <p>What client are you using? I'd recommend trying Putty and SecureCRT to compare their behavior.</p>
1
2009-05-21T13:57:57Z
[ "python", "shell", "ssh", "arrow-keys" ]
Seeing escape characters when pressing the arrow keys in python shell
893,053
<p>In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.</p> <p>But after I ssh into another machine and start <code>python</code> there, I get sessions like:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; ^[[A </code></pre> <p>where the last character comes from arrow-up. Or, using arrow-left:</p> <pre><code>&gt;&gt;&gt; impor^[[D </code></pre> <p>How can I fix this?</p> <p>In the regular bash, arrow keys work fine. The weird behavior is just in the interactive python (or perl etc.) shell.</p>
47
2009-05-21T13:55:32Z
893,089
<p>How's your env variable $TERM set [a] when things work fine and [b] when they don't? Env settings are often the key to such problems.</p>
0
2009-05-21T14:03:52Z
[ "python", "shell", "ssh", "arrow-keys" ]
Seeing escape characters when pressing the arrow keys in python shell
893,053
<p>In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.</p> <p>But after I ssh into another machine and start <code>python</code> there, I get sessions like:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; ^[[A </code></pre> <p>where the last character comes from arrow-up. Or, using arrow-left:</p> <pre><code>&gt;&gt;&gt; impor^[[D </code></pre> <p>How can I fix this?</p> <p>In the regular bash, arrow keys work fine. The weird behavior is just in the interactive python (or perl etc.) shell.</p>
47
2009-05-21T13:55:32Z
893,175
<p>Did you call ssh with the <em>-t</em> parameter to tell ssh to allocate a virtual terminal for you?</p> <p>From the man page:</p> <blockquote> <p>-t<br /> Force pseudo-tty allocation. This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g. when implementing menu services. Multiple -t options force tty allocation, even if ssh has no local tty.</p> </blockquote> <p>Additionally you may also have to set the <em>TERM</em> environment variable on the server correctly as suggested in another post.</p>
1
2009-05-21T14:22:24Z
[ "python", "shell", "ssh", "arrow-keys" ]
Seeing escape characters when pressing the arrow keys in python shell
893,053
<p>In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.</p> <p>But after I ssh into another machine and start <code>python</code> there, I get sessions like:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; ^[[A </code></pre> <p>where the last character comes from arrow-up. Or, using arrow-left:</p> <pre><code>&gt;&gt;&gt; impor^[[D </code></pre> <p>How can I fix this?</p> <p>In the regular bash, arrow keys work fine. The weird behavior is just in the interactive python (or perl etc.) shell.</p>
47
2009-05-21T13:55:32Z
893,200
<p>Looks like readline is not enabled. Check if <strong>PYTHONSTARTUP</strong> variable is defined, for me it points to <strong>/etc/pythonstart</strong> and that file is executed by the python process before going interactive, which setups readline/history handling.</p> <p>Thanks to @chown here is the docs on this: <a href="http://docs.python.org/2/tutorial/interactive.html">http://docs.python.org/2/tutorial/interactive.html</a></p>
15
2009-05-21T14:27:22Z
[ "python", "shell", "ssh", "arrow-keys" ]
Seeing escape characters when pressing the arrow keys in python shell
893,053
<p>In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.</p> <p>But after I ssh into another machine and start <code>python</code> there, I get sessions like:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; ^[[A </code></pre> <p>where the last character comes from arrow-up. Or, using arrow-left:</p> <pre><code>&gt;&gt;&gt; impor^[[D </code></pre> <p>How can I fix this?</p> <p>In the regular bash, arrow keys work fine. The weird behavior is just in the interactive python (or perl etc.) shell.</p>
47
2009-05-21T13:55:32Z
2,806,049
<ol> <li>install readline-devel package. </li> <li>recompile python with readline module</li> <li>Bingo!</li> </ol>
13
2010-05-10T20:04:31Z
[ "python", "shell", "ssh", "arrow-keys" ]
Seeing escape characters when pressing the arrow keys in python shell
893,053
<p>In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.</p> <p>But after I ssh into another machine and start <code>python</code> there, I get sessions like:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; ^[[A </code></pre> <p>where the last character comes from arrow-up. Or, using arrow-left:</p> <pre><code>&gt;&gt;&gt; impor^[[D </code></pre> <p>How can I fix this?</p> <p>In the regular bash, arrow keys work fine. The weird behavior is just in the interactive python (or perl etc.) shell.</p>
47
2009-05-21T13:55:32Z
17,307,271
<p>Try getting a key code library running on the server. If that does not work try to download a library with read-key ability.</p>
0
2013-06-25T20:49:56Z
[ "python", "shell", "ssh", "arrow-keys" ]
Seeing escape characters when pressing the arrow keys in python shell
893,053
<p>In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.</p> <p>But after I ssh into another machine and start <code>python</code> there, I get sessions like:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; ^[[A </code></pre> <p>where the last character comes from arrow-up. Or, using arrow-left:</p> <pre><code>&gt;&gt;&gt; impor^[[D </code></pre> <p>How can I fix this?</p> <p>In the regular bash, arrow keys work fine. The weird behavior is just in the interactive python (or perl etc.) shell.</p>
47
2009-05-21T13:55:32Z
17,394,195
<p>Here are the steps which worked for me in ubuntu 12.04 for python 3.3.</p> <p>1) open teminal and write <code>sudo apt-get install libreadline-dev</code></p> <p>2) download the source file of python 3.3.2 from <a href="http://www.python.org/ftp/python/3.3.2/Python-3.3.2.tar.xz" rel="nofollow">http://www.python.org/ftp/python/3.3.2/Python-3.3.2.tar.xz</a></p> <p>3) extract it and navigate to the Python-3.3.2/ directory in a shell</p> <p>4) execute the following command:</p> <pre><code>./configure make make test sudo make install </code></pre>
6
2013-06-30T19:44:05Z
[ "python", "shell", "ssh", "arrow-keys" ]
Seeing escape characters when pressing the arrow keys in python shell
893,053
<p>In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.</p> <p>But after I ssh into another machine and start <code>python</code> there, I get sessions like:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; ^[[A </code></pre> <p>where the last character comes from arrow-up. Or, using arrow-left:</p> <pre><code>&gt;&gt;&gt; impor^[[D </code></pre> <p>How can I fix this?</p> <p>In the regular bash, arrow keys work fine. The weird behavior is just in the interactive python (or perl etc.) shell.</p>
47
2009-05-21T13:55:32Z
26,356,378
<p>I've solved this issue by installing <code>readline</code> package:</p> <pre><code>pip install readline </code></pre>
33
2014-10-14T08:46:59Z
[ "python", "shell", "ssh", "arrow-keys" ]
Seeing escape characters when pressing the arrow keys in python shell
893,053
<p>In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.</p> <p>But after I ssh into another machine and start <code>python</code> there, I get sessions like:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; ^[[A </code></pre> <p>where the last character comes from arrow-up. Or, using arrow-left:</p> <pre><code>&gt;&gt;&gt; impor^[[D </code></pre> <p>How can I fix this?</p> <p>In the regular bash, arrow keys work fine. The weird behavior is just in the interactive python (or perl etc.) shell.</p>
47
2009-05-21T13:55:32Z
28,131,012
<p>On CentOS, I fix this by </p> <p><code>yum install readline-devel</code></p> <p>and then recompile python 3.4.</p> <p>On OpenSUSE, I fix this by</p> <pre><code>pip3 install readline </code></pre> <p>following Valerio Crini's answer.</p> <p>Perhaps "pip3 install readline" is a general solution. Haven't tried on my CentOS.</p>
3
2015-01-24T22:32:03Z
[ "python", "shell", "ssh", "arrow-keys" ]
Seeing escape characters when pressing the arrow keys in python shell
893,053
<p>In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.</p> <p>But after I ssh into another machine and start <code>python</code> there, I get sessions like:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; ^[[A </code></pre> <p>where the last character comes from arrow-up. Or, using arrow-left:</p> <pre><code>&gt;&gt;&gt; impor^[[D </code></pre> <p>How can I fix this?</p> <p>In the regular bash, arrow keys work fine. The weird behavior is just in the interactive python (or perl etc.) shell.</p>
47
2009-05-21T13:55:32Z
30,220,207
<p>I was trying build Python 2.7 on Ubuntu 14.0. You will need libreadline-dev. However, if you get it from apt-get, the current version is 6.3, which is incompatible with Python 2.7 (not sure about Python 3). For example, the data type "Function" and "CPPFunction", which were defined in previous versions of readline has been removed in 6.3, as reported here:</p> <p><a href="https://github.com/yyuu/pyenv/issues/126" rel="nofollow">https://github.com/yyuu/pyenv/issues/126</a></p> <p>That is to say you need to get the source code of an earlier version of readline. I installed libreadline 5.2 from apt-get for the library, and get the source code of 5.2 for the header files. Put them in /usr/include. </p> <p>Finally the issue has been resolved. </p>
0
2015-05-13T16:14:22Z
[ "python", "shell", "ssh", "arrow-keys" ]
Seeing escape characters when pressing the arrow keys in python shell
893,053
<p>In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.</p> <p>But after I ssh into another machine and start <code>python</code> there, I get sessions like:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; ^[[A </code></pre> <p>where the last character comes from arrow-up. Or, using arrow-left:</p> <pre><code>&gt;&gt;&gt; impor^[[D </code></pre> <p>How can I fix this?</p> <p>In the regular bash, arrow keys work fine. The weird behavior is just in the interactive python (or perl etc.) shell.</p>
47
2009-05-21T13:55:32Z
34,803,894
<p>I fixed this by doing the following:</p> <ul> <li>yum install readline-devel</li> <li><p>pip install readline</p> <ul> <li><p>I encountered another error here:</p> <p><code>gcc: readline/libreadline.a: No such file or directory</code></p> <p><code>gcc: readline/libhistory.a: No such file or directory</code></p> <p>I fixed this by installing <code>patch</code>:</p> <p><code>yum install patch</code></p></li> </ul></li> </ul> <p>After that I managed to run <code>pip install readline</code> successfully which solved the escape characters in my python shell.</p> <p>FYI, I'm using RedHat</p>
2
2016-01-15T03:24:25Z
[ "python", "shell", "ssh", "arrow-keys" ]
How to make a dynamic array with different values in Python
893,143
<p>I have rows in file like :</p> <pre><code>20040701 0 20040701 0 1 52.965366 61.777687 57.540783 </code></pre> <p>I want to put that in a dynamic array if it's possible ?</p> <p>Something like </p> <pre><code>try: clients = [ (107, "Ella", "Fitzgerald"), (108, "Louis", "Armstrong"), (109, "Miles", "Davis") ] cur.executemany("INSERT INTO clients (id, firstname, lastname) \ VALUES (?, ?, ?)", clients ) except: pass </code></pre>
0
2009-05-21T14:16:00Z
893,166
<p>You can easily make a list of numbers from a string like your first example, just <code>[float(x) for x in thestring.split()]</code> -- but the "Something like" is nothing like the first example and appears to have nothing to do with the question's Subject.</p>
2
2009-05-21T14:20:25Z
[ "python", "sqlite" ]
How to make a dynamic array with different values in Python
893,143
<p>I have rows in file like :</p> <pre><code>20040701 0 20040701 0 1 52.965366 61.777687 57.540783 </code></pre> <p>I want to put that in a dynamic array if it's possible ?</p> <p>Something like </p> <pre><code>try: clients = [ (107, "Ella", "Fitzgerald"), (108, "Louis", "Armstrong"), (109, "Miles", "Davis") ] cur.executemany("INSERT INTO clients (id, firstname, lastname) \ VALUES (?, ?, ?)", clients ) except: pass </code></pre>
0
2009-05-21T14:16:00Z
893,182
<pre><code>In [1]: s = "20040701 0 20040701 0 1 52.965366 61.777687 57.540783" In [2]: strings = s.split(" ") In [3]: strings Out[3]: ['20040701', '0', '20040701', '0', '1', '52.965366', '61.777687', '57.540783'] In [6]: tuple(strings) Out[6]: ('20040701', '0', '20040701', '0', '1', '52.965366', '61.777687', '57.540783') </code></pre> <p>Is that the kind of thing you're looking for? I'm not certain from your question.</p>
2
2009-05-21T14:23:55Z
[ "python", "sqlite" ]
How to make a dynamic array with different values in Python
893,143
<p>I have rows in file like :</p> <pre><code>20040701 0 20040701 0 1 52.965366 61.777687 57.540783 </code></pre> <p>I want to put that in a dynamic array if it's possible ?</p> <p>Something like </p> <pre><code>try: clients = [ (107, "Ella", "Fitzgerald"), (108, "Louis", "Armstrong"), (109, "Miles", "Davis") ] cur.executemany("INSERT INTO clients (id, firstname, lastname) \ VALUES (?, ?, ?)", clients ) except: pass </code></pre>
0
2009-05-21T14:16:00Z
893,213
<p>From my reading for your question, I think you want something like:</p> <pre>rows=[map(Decimal,x.split(' ')) for x in lines]</pre>
1
2009-05-21T14:29:26Z
[ "python", "sqlite" ]
Multiple variables in Python 'with' statement
893,333
<p>Is it possible to declare more than one variable using a <code>with</code> statement in Python?</p> <p>Something like:</p> <pre><code>from __future__ import with_statement with open("out.txt","wt"), open("in.txt") as file_out, file_in: for line in file_in: file_out.write(line) </code></pre> <p>... or is cleaning up two resources at the same time the problem?</p>
146
2009-05-21T14:51:27Z
893,356
<p>I think you want to do this instead:</p> <pre><code>from __future__ import with_statement with open("out.txt","wt") as file_out: with open("in.txt") as file_in: for line in file_in: file_out.write(line) </code></pre>
17
2009-05-21T14:55:22Z
[ "python", "with-statement" ]
Multiple variables in Python 'with' statement
893,333
<p>Is it possible to declare more than one variable using a <code>with</code> statement in Python?</p> <p>Something like:</p> <pre><code>from __future__ import with_statement with open("out.txt","wt"), open("in.txt") as file_out, file_in: for line in file_in: file_out.write(line) </code></pre> <p>... or is cleaning up two resources at the same time the problem?</p>
146
2009-05-21T14:51:27Z
893,360
<p><a href="http://docs.python.org/2/library/contextlib.html#contextlib.nested"><code>contextlib.nested</code></a> supports this:</p> <pre><code>import contextlib with contextlib.nested(open("out.txt","wt"), open("in.txt")) as (file_out, file_in): ... </code></pre> <p><strong>Update:</strong><br> To quote the documentation, regarding <a href="http://docs.python.org/2/library/contextlib.html#contextlib.nested"><code>contextlib.nested</code></a>:</p> <blockquote> <p><em>Deprecated since version 2.7</em>: The with-statement now supports this functionality directly (without the confusing error prone quirks).</p> </blockquote> <p>See <a href="http://stackoverflow.com/a/1073814/1217270">Rafał Dowgird's answer</a> for more information. </p>
52
2009-05-21T14:55:42Z
[ "python", "with-statement" ]
Multiple variables in Python 'with' statement
893,333
<p>Is it possible to declare more than one variable using a <code>with</code> statement in Python?</p> <p>Something like:</p> <pre><code>from __future__ import with_statement with open("out.txt","wt"), open("in.txt") as file_out, file_in: for line in file_in: file_out.write(line) </code></pre> <p>... or is cleaning up two resources at the same time the problem?</p>
146
2009-05-21T14:51:27Z
893,520
<pre><code>open('out.txt', 'w').writelines(open('in.txt')) </code></pre> <p>Both files will be implicity, immediately closed just after execution of this line, in CPython.</p>
-4
2009-05-21T15:21:10Z
[ "python", "with-statement" ]
Multiple variables in Python 'with' statement
893,333
<p>Is it possible to declare more than one variable using a <code>with</code> statement in Python?</p> <p>Something like:</p> <pre><code>from __future__ import with_statement with open("out.txt","wt"), open("in.txt") as file_out, file_in: for line in file_in: file_out.write(line) </code></pre> <p>... or is cleaning up two resources at the same time the problem?</p>
146
2009-05-21T14:51:27Z
1,073,814
<p>It is possible in <a href="http://docs.python.org/3.1/reference/compound_stmts.html#with">Python 3 since v3.1</a> and <a href="http://docs.python.org/dev/whatsnew/2.7.html#other-language-changes">Python 2.7</a>. The new <code>with</code> syntax supports multiple context managers:</p> <pre><code>with A() as a, B() as b, C() as c: doSomething(a,b,c) </code></pre> <p>Unlike the <code>contextlib.nested</code>, this guarantees that <code>a</code> and <code>b</code> will have their <code>__exit__()</code>'s called even if <code>C()</code> or it's <code>__enter__()</code> method raises an exception.</p>
296
2009-07-02T11:25:50Z
[ "python", "with-statement" ]
Python doctest fails on 0.0 != -0.0--what gives?
893,398
<p>Given the following code:</p> <pre><code>def slope(x1, y1, x2, y2): """ &gt;&gt;&gt; slope(5, 3, 4, 2) 1.0 &gt;&gt;&gt; slope(1, 2, 3, 2) 0.0 &gt;&gt;&gt; slope(1, 2, 3, 3) 0.5 &gt;&gt;&gt; slope(2, 4, 1, 2) 2.0 """ xa = float (x1) xb = float (x2) ya = float (y1) yb = float (y2) return (ya-yb)/(xa-xb) if name_ == '__main__': import doctest doctest.testmod() </code></pre> <p>The second doctest fails:</p> <pre><code>Failed example: slope(1, 2, 3, 2) Expected: 0.0 Got: -0.0 </code></pre> <p>However, we all know that -0.0 == 0.0. Is doctest doing a string comparison to check results here? Why does the second test fail?</p>
2
2009-05-21T15:01:39Z
893,413
<p>It fails because <a href="http://docs.python.org/3.0/library/doctest.html" rel="nofollow">doctest</a> does <em>string comparison</em>. It merely checks whether the output is identical to what would have been outputted if the code had been executed at the Python interactive interpreter:</p> <pre><code>&gt;&gt;&gt; 0 / -2 -0.0 </code></pre> <p><strong>Edit:</strong>: The link <a href="http://docs.python.org/library/doctest.html#doctest.OutputChecker.check%5Foutput" rel="nofollow">referenced</a> by <a href="http://stackoverflow.com/users/60261/daniel-lew">Daniel Lew</a> below gives some more hints about how this works, and how you may be able to influence this behaviour.</p>
9
2009-05-21T15:04:23Z
[ "python" ]
item frequency count in python
893,417
<p>I'm a python newbie, so maybe my question is very noob. Assume I have a list of words, and I want to find the number of times each word appears in that list. Obvious way to do this is:</p> <pre><code>words = "apple banana apple strawberry banana lemon" uniques = set(words.split()) freqs = [(item, words.split.count(item)) for item in uniques] print(freqs) </code></pre> <p>But I find this code not very good, because this way program runs through words list twice, once to build the set, and second time counting the number of appearances. Of course, I could write a function to run through list and do the counting, but that wouldn't be so pythonic. So, is there a more efficient and pythonic way?</p>
40
2009-05-21T15:04:36Z
893,449
<p>If you don't want to use the standard dictionary method (looping through the list incrementing the proper dict. key), you can try this:</p> <pre><code>&gt;&gt;&gt; from itertools import groupby &gt;&gt;&gt; myList = words.split() # ['apple', 'banana', 'apple', 'strawberry', 'banana', 'lemon'] &gt;&gt;&gt; [(k, len(list(g))) for k, g in groupby(sorted(myList))] [('apple', 2), ('banana', 2), ('lemon', 1), ('strawberry', 1)] </code></pre> <p>It runs in O(n log n) time.</p>
5
2009-05-21T15:09:57Z
[ "python", "count", "frequency", "counting" ]
item frequency count in python
893,417
<p>I'm a python newbie, so maybe my question is very noob. Assume I have a list of words, and I want to find the number of times each word appears in that list. Obvious way to do this is:</p> <pre><code>words = "apple banana apple strawberry banana lemon" uniques = set(words.split()) freqs = [(item, words.split.count(item)) for item in uniques] print(freqs) </code></pre> <p>But I find this code not very good, because this way program runs through words list twice, once to build the set, and second time counting the number of appearances. Of course, I could write a function to run through list and do the counting, but that wouldn't be so pythonic. So, is there a more efficient and pythonic way?</p>
40
2009-05-21T15:04:36Z
893,459
<p><a href="http://docs.python.org/library/collections.html#defaultdict-objects">defaultdict</a> to the rescue!</p> <pre><code>from collections import defaultdict words = "apple banana apple strawberry banana lemon" d = defaultdict(int) for word in words.split(): d[word] += 1 </code></pre> <p>This runs in O(n).</p>
73
2009-05-21T15:10:59Z
[ "python", "count", "frequency", "counting" ]
item frequency count in python
893,417
<p>I'm a python newbie, so maybe my question is very noob. Assume I have a list of words, and I want to find the number of times each word appears in that list. Obvious way to do this is:</p> <pre><code>words = "apple banana apple strawberry banana lemon" uniques = set(words.split()) freqs = [(item, words.split.count(item)) for item in uniques] print(freqs) </code></pre> <p>But I find this code not very good, because this way program runs through words list twice, once to build the set, and second time counting the number of appearances. Of course, I could write a function to run through list and do the counting, but that wouldn't be so pythonic. So, is there a more efficient and pythonic way?</p>
40
2009-05-21T15:04:36Z
893,463
<p>Standard approach:</p> <pre><code>from collections import defaultdict words = "apple banana apple strawberry banana lemon" words = words.split() result = collections.defaultdict(int) for word in words: result[word] += 1 print result </code></pre> <p>Groupby oneliner:</p> <pre><code>from itertools import groupby words = "apple banana apple strawberry banana lemon" words = words.split() result = dict((key, len(list(group))) for key, group in groupby(sorted(words))) print result </code></pre>
10
2009-05-21T15:11:47Z
[ "python", "count", "frequency", "counting" ]
item frequency count in python
893,417
<p>I'm a python newbie, so maybe my question is very noob. Assume I have a list of words, and I want to find the number of times each word appears in that list. Obvious way to do this is:</p> <pre><code>words = "apple banana apple strawberry banana lemon" uniques = set(words.split()) freqs = [(item, words.split.count(item)) for item in uniques] print(freqs) </code></pre> <p>But I find this code not very good, because this way program runs through words list twice, once to build the set, and second time counting the number of appearances. Of course, I could write a function to run through list and do the counting, but that wouldn't be so pythonic. So, is there a more efficient and pythonic way?</p>
40
2009-05-21T15:04:36Z
893,499
<p>If you are using python 2.7+/3.1+, there is a <a href="http://docs.python.org/dev/py3k/library/collections.html#collections.Counter">Counter Class</a> in the collections module which is purpose built to solve this type of problem:</p> <pre><code>&gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; words = "apple banana apple strawberry banana lemon" &gt;&gt;&gt; freqs = Counter(words.split()) &gt;&gt;&gt; print(freqs) Counter({'apple': 2, 'banana': 2, 'strawberry': 1, 'lemon': 1}) &gt;&gt;&gt; </code></pre> <p>Since both 2.7 and 3.1 are still in beta it's unlikely you're using it, so just keep in mind that a standard way of doing this kind of work will soon be readily available.</p>
96
2009-05-21T15:16:59Z
[ "python", "count", "frequency", "counting" ]
item frequency count in python
893,417
<p>I'm a python newbie, so maybe my question is very noob. Assume I have a list of words, and I want to find the number of times each word appears in that list. Obvious way to do this is:</p> <pre><code>words = "apple banana apple strawberry banana lemon" uniques = set(words.split()) freqs = [(item, words.split.count(item)) for item in uniques] print(freqs) </code></pre> <p>But I find this code not very good, because this way program runs through words list twice, once to build the set, and second time counting the number of appearances. Of course, I could write a function to run through list and do the counting, but that wouldn't be so pythonic. So, is there a more efficient and pythonic way?</p>
40
2009-05-21T15:04:36Z
893,676
<p>Without defaultdict:</p> <pre><code>words = "apple banana apple strawberry banana lemon" my_count = {} for word in words.split(): try: my_count[word] += 1 except KeyError: my_count[word] = 1 </code></pre>
1
2009-05-21T15:59:30Z
[ "python", "count", "frequency", "counting" ]
item frequency count in python
893,417
<p>I'm a python newbie, so maybe my question is very noob. Assume I have a list of words, and I want to find the number of times each word appears in that list. Obvious way to do this is:</p> <pre><code>words = "apple banana apple strawberry banana lemon" uniques = set(words.split()) freqs = [(item, words.split.count(item)) for item in uniques] print(freqs) </code></pre> <p>But I find this code not very good, because this way program runs through words list twice, once to build the set, and second time counting the number of appearances. Of course, I could write a function to run through list and do the counting, but that wouldn't be so pythonic. So, is there a more efficient and pythonic way?</p>
40
2009-05-21T15:04:36Z
983,434
<pre><code>freqs = {} for word in words: freqs[word] = freqs.get(word, 0) + 1 # fetch and increment OR initialize </code></pre> <p>I think this results to the same as Triptych's solution, but without importing collections. Also a bit like Selinap's solution, but more readable imho. Almost identical to Thomas Weigel's solution, but without using Exceptions.</p> <p>This could be slower than using defaultdict() from the collections library however. Since the value is fetched, incremented and then assigned again. Instead of just incremented. However using += might do just the same internally.</p>
6
2009-06-11T20:21:44Z
[ "python", "count", "frequency", "counting" ]
item frequency count in python
893,417
<p>I'm a python newbie, so maybe my question is very noob. Assume I have a list of words, and I want to find the number of times each word appears in that list. Obvious way to do this is:</p> <pre><code>words = "apple banana apple strawberry banana lemon" uniques = set(words.split()) freqs = [(item, words.split.count(item)) for item in uniques] print(freqs) </code></pre> <p>But I find this code not very good, because this way program runs through words list twice, once to build the set, and second time counting the number of appearances. Of course, I could write a function to run through list and do the counting, but that wouldn't be so pythonic. So, is there a more efficient and pythonic way?</p>
40
2009-05-21T15:04:36Z
5,576,479
<p>Can't you just use count?</p> <pre><code>words = 'the quick brown fox jumps over the lazy gray dog' words.count('z') #output: 1 </code></pre>
0
2011-04-07T05:36:08Z
[ "python", "count", "frequency", "counting" ]
item frequency count in python
893,417
<p>I'm a python newbie, so maybe my question is very noob. Assume I have a list of words, and I want to find the number of times each word appears in that list. Obvious way to do this is:</p> <pre><code>words = "apple banana apple strawberry banana lemon" uniques = set(words.split()) freqs = [(item, words.split.count(item)) for item in uniques] print(freqs) </code></pre> <p>But I find this code not very good, because this way program runs through words list twice, once to build the set, and second time counting the number of appearances. Of course, I could write a function to run through list and do the counting, but that wouldn't be so pythonic. So, is there a more efficient and pythonic way?</p>
40
2009-05-21T15:04:36Z
15,103,041
<p><strong>The answer below takes some extra cycles, but it is another method</strong></p> <pre class="lang-py prettyprint-override"><code>def func(tup): return tup[-1] def print_words(filename): f = open("small.txt",'r') whole_content = (f.read()).lower() print whole_content list_content = whole_content.split() dict = {} for one_word in list_content: dict[one_word] = 0 for one_word in list_content: dict[one_word] += 1 print dict.items() print sorted(dict.items(),key=func) </code></pre>
0
2013-02-27T02:17:20Z
[ "python", "count", "frequency", "counting" ]
item frequency count in python
893,417
<p>I'm a python newbie, so maybe my question is very noob. Assume I have a list of words, and I want to find the number of times each word appears in that list. Obvious way to do this is:</p> <pre><code>words = "apple banana apple strawberry banana lemon" uniques = set(words.split()) freqs = [(item, words.split.count(item)) for item in uniques] print(freqs) </code></pre> <p>But I find this code not very good, because this way program runs through words list twice, once to build the set, and second time counting the number of appearances. Of course, I could write a function to run through list and do the counting, but that wouldn't be so pythonic. So, is there a more efficient and pythonic way?</p>
40
2009-05-21T15:04:36Z
31,065,989
<p>I happened to work on some Spark exercise, here is my solution.</p> <pre><code>tokens = ['quick', 'brown', 'fox', 'jumps', 'lazy', 'dog'] print {n: float(tokens.count(n))/float(len(tokens)) for n in tokens} </code></pre> <p>**#output of the above **</p> <pre><code>{'brown': 0.16666666666666666, 'lazy': 0.16666666666666666, 'jumps': 0.16666666666666666, 'fox': 0.16666666666666666, 'dog': 0.16666666666666666, 'quick': 0.16666666666666666} </code></pre>
0
2015-06-26T06:02:07Z
[ "python", "count", "frequency", "counting" ]
item frequency count in python
893,417
<p>I'm a python newbie, so maybe my question is very noob. Assume I have a list of words, and I want to find the number of times each word appears in that list. Obvious way to do this is:</p> <pre><code>words = "apple banana apple strawberry banana lemon" uniques = set(words.split()) freqs = [(item, words.split.count(item)) for item in uniques] print(freqs) </code></pre> <p>But I find this code not very good, because this way program runs through words list twice, once to build the set, and second time counting the number of appearances. Of course, I could write a function to run through list and do the counting, but that wouldn't be so pythonic. So, is there a more efficient and pythonic way?</p>
40
2009-05-21T15:04:36Z
35,584,925
<p>Use reduce() to convert the list to a single dict.</p> <pre><code>words = "apple banana apple strawberry banana lemon" reduce( lambda d, c: d.update([(c, d.get(c,0)+1)]) or d, words.split(), {}) </code></pre> <p>returns</p> <pre><code>{'strawberry': 1, 'lemon': 1, 'apple': 2, 'banana': 2} </code></pre>
0
2016-02-23T18:03:45Z
[ "python", "count", "frequency", "counting" ]
Replacing Microsoft Word Newline Character in Python
893,514
<p>This feels like it should be an easy one, but I'm having trouble cleaning out the newline character in content pasted from Microsoft Word. Not a full line-break, but the <kbd>CTRL ENTER</kbd> character that shows up as a return arrow in Word. I've tried <code>chr(10)</code>, <code>chr(13)</code>, <code>\u000D</code>, <code>\u000A</code> and a few others, but I can't match it in a string.replace(). Should I be looking for a different character or do I need to use something other than the <code>string.replace</code> method?</p>
0
2009-05-21T15:19:08Z
893,535
<p>Run this:</p> <pre><code>print repr(mystringobject) </code></pre> <p>That will give a hint of which character you want to remove.</p> <p>If still no clue, paste the result of the command above in the question, and I'll edit my answer.</p>
4
2009-05-21T15:24:51Z
[ "python", "ms-word", "sanitize" ]
Replacing Microsoft Word Newline Character in Python
893,514
<p>This feels like it should be an easy one, but I'm having trouble cleaning out the newline character in content pasted from Microsoft Word. Not a full line-break, but the <kbd>CTRL ENTER</kbd> character that shows up as a return arrow in Word. I've tried <code>chr(10)</code>, <code>chr(13)</code>, <code>\u000D</code>, <code>\u000A</code> and a few others, but I can't match it in a string.replace(). Should I be looking for a different character or do I need to use something other than the <code>string.replace</code> method?</p>
0
2009-05-21T15:19:08Z
893,564
<p>you can get the ASCII value of the character like this:</p> <pre><code>for c in 'string': print ord(c), hex(ord(c)) </code></pre> <p>once you know the code, it should be easy to kill the offender.</p>
2
2009-05-21T15:31:36Z
[ "python", "ms-word", "sanitize" ]
How to define a system-wide alias for a Python script?
893,543
<p>I am working on Mac OS X and I have a Python script which is going to be called by other scripts and programs (Apple's launchd in particular). I could call it with</p> <pre><code>python /Users/xyz/long/absolute/path/to/script.py arg1 arg2 </code></pre> <p>Since the location of the script might change, I want to decouple other scripts and the launchd configuration files from the actual location, so that a call to the script looks like</p> <pre><code>script arg1 arg2 </code></pre> <p>Defining an alias for Bash in $HOME/.bash_profile does not work, since launchd does not know about the alias. </p> <p>What is the best way to define a "sytem-wide alias" or something equivalent?</p>
2
2009-05-21T15:27:01Z
893,553
<p>I usually make a symbolic link and put it in /usr/bin (assuming /usr/bin is part of your PATH)</p> <p>(In a terminal. You may have to use <em>sudo ln -s</em> depending on the permissions.</p> <pre><code>ln -s /Users/xyz/long/absolute/path/to/script.py /usr/bin/script.py </code></pre> <p>If you take <a href="http://stackoverflow.com/questions/893543/how-to-define-a-system-wide-alias-for-a-python-script/893563#893563">Rory's advice</a> and put the #!/usr/bin/python at the beginning of the script, you'll also need to make the script executable.</p> <pre><code>chmod a+x /Users/xyz/long/absolute/path/to/script.py </code></pre>
6
2009-05-21T15:29:19Z
[ "python", "osx" ]
How to define a system-wide alias for a Python script?
893,543
<p>I am working on Mac OS X and I have a Python script which is going to be called by other scripts and programs (Apple's launchd in particular). I could call it with</p> <pre><code>python /Users/xyz/long/absolute/path/to/script.py arg1 arg2 </code></pre> <p>Since the location of the script might change, I want to decouple other scripts and the launchd configuration files from the actual location, so that a call to the script looks like</p> <pre><code>script arg1 arg2 </code></pre> <p>Defining an alias for Bash in $HOME/.bash_profile does not work, since launchd does not know about the alias. </p> <p>What is the best way to define a "sytem-wide alias" or something equivalent?</p>
2
2009-05-21T15:27:01Z
893,563
<p>As well as doing a symlink, you can put "#! /path/to/python" at the start of the script and make it executabe. Then you don't have to call it with "python /Users/big/long/path/script.py"</p>
3
2009-05-21T15:31:24Z
[ "python", "osx" ]
How do I calculate r-squared using Python and Numpy?
893,657
<p>I'm using Python and Numpy to calculate a best fit polynomial of arbitrary degree. I pass a list of x values, y values, and the degree of the polynomial I want to fit (linear, quadratic, etc.).</p> <p>This much works, but I also want to calculate r (coefficient of correlation) and r-squared(coefficient of determination). I am comparing my results with Excel's best-fit trendline capability, and the r-squared value it calculates. Using this, I know I am calculating r-squared correctly for linear best-fit (degree equals 1). However, my function does not work for polynomials with degree greater than 1.</p> <p>Excel is able to do this. How do I calculate r-squared for higher-order polynomials using Numpy?</p> <p>Here's my function:</p> <pre><code>import numpy # Polynomial Regression def polyfit(x, y, degree): results = {} coeffs = numpy.polyfit(x, y, degree) # Polynomial Coefficients results['polynomial'] = coeffs.tolist() correlation = numpy.corrcoef(x, y)[0,1] # r results['correlation'] = correlation # r-squared results['determination'] = correlation**2 return results </code></pre>
38
2009-05-21T15:55:54Z
893,923
<p>R-squared is a statistic that only applies to linear regression.</p> <p>Essentially, it measures how much variation in your data can be explained by the linear regression.</p> <p>So, you calculate the "Total Sum of Squares", which is the total squared deviation of each of your outcome variables from their mean. . .</p> <p>\sum_{i}(y_{i} - y_bar)^2</p> <p>where y_bar is the mean of the y's. </p> <p>Then, you calculate the "regression sum of squares", which is how much your FITTED values differ from the mean</p> <p>\sum_{i}(yHat_{i} - y_bar)^2</p> <p>and find the ratio of those two. </p> <p>Now, all you would have to do for a polynomial fit is plug in the y_hat's from that model, but it's not accurate to call that r-squared. </p> <p><a href="http://ask.metafilter.com/65278/Statistics-tell-me-about-rsquare-for-nonlinear-models" rel="nofollow">Here</a> is a link I found that speaks to it a little.</p>
3
2009-05-21T16:54:49Z
[ "python", "math", "statistics", "numpy", "curve-fitting" ]
How do I calculate r-squared using Python and Numpy?
893,657
<p>I'm using Python and Numpy to calculate a best fit polynomial of arbitrary degree. I pass a list of x values, y values, and the degree of the polynomial I want to fit (linear, quadratic, etc.).</p> <p>This much works, but I also want to calculate r (coefficient of correlation) and r-squared(coefficient of determination). I am comparing my results with Excel's best-fit trendline capability, and the r-squared value it calculates. Using this, I know I am calculating r-squared correctly for linear best-fit (degree equals 1). However, my function does not work for polynomials with degree greater than 1.</p> <p>Excel is able to do this. How do I calculate r-squared for higher-order polynomials using Numpy?</p> <p>Here's my function:</p> <pre><code>import numpy # Polynomial Regression def polyfit(x, y, degree): results = {} coeffs = numpy.polyfit(x, y, degree) # Polynomial Coefficients results['polynomial'] = coeffs.tolist() correlation = numpy.corrcoef(x, y)[0,1] # r results['correlation'] = correlation # r-squared results['determination'] = correlation**2 return results </code></pre>
38
2009-05-21T15:55:54Z
895,063
<p>From the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html">numpy.polyfit</a> documentation, it is fitting linear regression. Specifically, numpy.polyfit with degree 'd' fits a linear regression with the mean function</p> <p>E(y|x) = p_d * x**d + p_{d-1} * x **(d-1) + ... + p_1 * x + p_0</p> <p>So you just need to calculate the R-squared for that fit. The wikipedia page on <a href="http://en.wikipedia.org/wiki/Linear_regression">linear regression</a> gives full details. You are interested in R^2 which you can calculate in a couple of ways, the easisest probably being</p> <pre><code>SST = Sum(i=1..n) (y_i - y_bar)^2 SSReg = Sum(i=1..n) (y_ihat - y_bar)^2 Rsquared = SSReg/SST </code></pre> <p>Where I use 'y_bar' for the mean of the y's, and 'y_ihat' to be the fit value for each point.</p> <p>I'm not terribly familiar with numpy (I usually work in R), so there is probably a tidier way to calculate your R-squared, but the following should be correct</p> <pre><code>import numpy # Polynomial Regression def polyfit(x, y, degree): results = {} coeffs = numpy.polyfit(x, y, degree) # Polynomial Coefficients results['polynomial'] = coeffs.tolist() # r-squared p = numpy.poly1d(coeffs) # fit values, and mean yhat = p(x) # or [p(z) for z in x] ybar = numpy.sum(y)/len(y) # or sum(y)/len(y) ssreg = numpy.sum((yhat-ybar)**2) # or sum([ (yihat - ybar)**2 for yihat in yhat]) sstot = numpy.sum((y - ybar)**2) # or sum([ (yi - ybar)**2 for yi in y]) results['determination'] = ssreg / sstot return results </code></pre>
25
2009-05-21T20:48:35Z
[ "python", "math", "statistics", "numpy", "curve-fitting" ]
How do I calculate r-squared using Python and Numpy?
893,657
<p>I'm using Python and Numpy to calculate a best fit polynomial of arbitrary degree. I pass a list of x values, y values, and the degree of the polynomial I want to fit (linear, quadratic, etc.).</p> <p>This much works, but I also want to calculate r (coefficient of correlation) and r-squared(coefficient of determination). I am comparing my results with Excel's best-fit trendline capability, and the r-squared value it calculates. Using this, I know I am calculating r-squared correctly for linear best-fit (degree equals 1). However, my function does not work for polynomials with degree greater than 1.</p> <p>Excel is able to do this. How do I calculate r-squared for higher-order polynomials using Numpy?</p> <p>Here's my function:</p> <pre><code>import numpy # Polynomial Regression def polyfit(x, y, degree): results = {} coeffs = numpy.polyfit(x, y, degree) # Polynomial Coefficients results['polynomial'] = coeffs.tolist() correlation = numpy.corrcoef(x, y)[0,1] # r results['correlation'] = correlation # r-squared results['determination'] = correlation**2 return results </code></pre>
38
2009-05-21T15:55:54Z
1,326,331
<p>The wikipedia article on <a href="http://en.wikipedia.org/wiki/Coefficient_of_determination" rel="nofollow">r-squareds</a> suggests that it may be used for general model fitting rather than just linear regression.</p>
3
2009-08-25T06:06:24Z
[ "python", "math", "statistics", "numpy", "curve-fitting" ]
How do I calculate r-squared using Python and Numpy?
893,657
<p>I'm using Python and Numpy to calculate a best fit polynomial of arbitrary degree. I pass a list of x values, y values, and the degree of the polynomial I want to fit (linear, quadratic, etc.).</p> <p>This much works, but I also want to calculate r (coefficient of correlation) and r-squared(coefficient of determination). I am comparing my results with Excel's best-fit trendline capability, and the r-squared value it calculates. Using this, I know I am calculating r-squared correctly for linear best-fit (degree equals 1). However, my function does not work for polynomials with degree greater than 1.</p> <p>Excel is able to do this. How do I calculate r-squared for higher-order polynomials using Numpy?</p> <p>Here's my function:</p> <pre><code>import numpy # Polynomial Regression def polyfit(x, y, degree): results = {} coeffs = numpy.polyfit(x, y, degree) # Polynomial Coefficients results['polynomial'] = coeffs.tolist() correlation = numpy.corrcoef(x, y)[0,1] # r results['correlation'] = correlation # r-squared results['determination'] = correlation**2 return results </code></pre>
38
2009-05-21T15:55:54Z
1,517,401
<p>A very late reply, but just in case someone needs a ready function for this:</p> <p><a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.linregress.html">scipy.stats.stats.linregress</a></p> <p>i.e.</p> <pre><code>slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(x, y) </code></pre> <p>as in @Adam Marples's answer.</p>
54
2009-10-04T21:15:51Z
[ "python", "math", "statistics", "numpy", "curve-fitting" ]
How do I calculate r-squared using Python and Numpy?
893,657
<p>I'm using Python and Numpy to calculate a best fit polynomial of arbitrary degree. I pass a list of x values, y values, and the degree of the polynomial I want to fit (linear, quadratic, etc.).</p> <p>This much works, but I also want to calculate r (coefficient of correlation) and r-squared(coefficient of determination). I am comparing my results with Excel's best-fit trendline capability, and the r-squared value it calculates. Using this, I know I am calculating r-squared correctly for linear best-fit (degree equals 1). However, my function does not work for polynomials with degree greater than 1.</p> <p>Excel is able to do this. How do I calculate r-squared for higher-order polynomials using Numpy?</p> <p>Here's my function:</p> <pre><code>import numpy # Polynomial Regression def polyfit(x, y, degree): results = {} coeffs = numpy.polyfit(x, y, degree) # Polynomial Coefficients results['polynomial'] = coeffs.tolist() correlation = numpy.corrcoef(x, y)[0,1] # r results['correlation'] = correlation # r-squared results['determination'] = correlation**2 return results </code></pre>
38
2009-05-21T15:55:54Z
13,918,150
<p>I have been using this successfully, where x and y are array-like.</p> <pre><code>def rsquared(x, y): """ Return R^2 where x and y are array-like.""" slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(x, y) return r_value**2 </code></pre>
9
2012-12-17T16:37:46Z
[ "python", "math", "statistics", "numpy", "curve-fitting" ]
How do I calculate r-squared using Python and Numpy?
893,657
<p>I'm using Python and Numpy to calculate a best fit polynomial of arbitrary degree. I pass a list of x values, y values, and the degree of the polynomial I want to fit (linear, quadratic, etc.).</p> <p>This much works, but I also want to calculate r (coefficient of correlation) and r-squared(coefficient of determination). I am comparing my results with Excel's best-fit trendline capability, and the r-squared value it calculates. Using this, I know I am calculating r-squared correctly for linear best-fit (degree equals 1). However, my function does not work for polynomials with degree greater than 1.</p> <p>Excel is able to do this. How do I calculate r-squared for higher-order polynomials using Numpy?</p> <p>Here's my function:</p> <pre><code>import numpy # Polynomial Regression def polyfit(x, y, degree): results = {} coeffs = numpy.polyfit(x, y, degree) # Polynomial Coefficients results['polynomial'] = coeffs.tolist() correlation = numpy.corrcoef(x, y)[0,1] # r results['correlation'] = correlation # r-squared results['determination'] = correlation**2 return results </code></pre>
38
2009-05-21T15:55:54Z
30,804,603
<p>From yanl (yet-another-library) <code>sklearn.metrics</code> has an <a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.r2_score.html"><code>r2_square</code></a> function;</p> <pre><code>from sklearn.metrics import r2_score coefficient_of_dermination = r2_score(y, p(x)) </code></pre>
7
2015-06-12T13:41:03Z
[ "python", "math", "statistics", "numpy", "curve-fitting" ]
How do I calculate r-squared using Python and Numpy?
893,657
<p>I'm using Python and Numpy to calculate a best fit polynomial of arbitrary degree. I pass a list of x values, y values, and the degree of the polynomial I want to fit (linear, quadratic, etc.).</p> <p>This much works, but I also want to calculate r (coefficient of correlation) and r-squared(coefficient of determination). I am comparing my results with Excel's best-fit trendline capability, and the r-squared value it calculates. Using this, I know I am calculating r-squared correctly for linear best-fit (degree equals 1). However, my function does not work for polynomials with degree greater than 1.</p> <p>Excel is able to do this. How do I calculate r-squared for higher-order polynomials using Numpy?</p> <p>Here's my function:</p> <pre><code>import numpy # Polynomial Regression def polyfit(x, y, degree): results = {} coeffs = numpy.polyfit(x, y, degree) # Polynomial Coefficients results['polynomial'] = coeffs.tolist() correlation = numpy.corrcoef(x, y)[0,1] # r results['correlation'] = correlation # r-squared results['determination'] = correlation**2 return results </code></pre>
38
2009-05-21T15:55:54Z
34,617,603
<p>I originally posted the benchmarks below with the purpose of recommending <code>numpy.corrcoef</code>, foolishly not realizing that the original question already uses <code>corrcoef</code> and was in fact asking about higher order polynomial fits. I've added an actual solution to the polynomial r-squared question using statsmodels, and I've left the original benchmarks, which while off-topic, are potentially useful to someone.</p> <hr> <p><code>statsmodels</code> has the capability to calculate the <code>r^2</code> of a polynomial fit directly, here are 2 methods...</p> <pre><code>import statsmodels.api as sm import stasmodels.formula.api as smf # Construct the columns for the different powers of x def get_r2_statsmodels(x, y, k=1): xpoly = np.column_stack([x**i for i in range(k+1)]) return sm.OLS(y, xpoly).fit().rsquared # Use the formula API and construct a formula describing the polynomial def get_r2_statsmodels_formula(x, y, k=1): formula = 'y ~ 1 + ' + ' + '.join('I(x**{})'.format(i) for i in range(1, k+1)) data = {'x': x, 'y': y} return smf.ols(formula, data).fit().rsquared </code></pre> <p>To further take advantage of <code>statsmodels</code>, one should also look at the fitted model summary, which can be printed or displayed as a rich HTML table in Jupyter/IPython notebook. The results object provides access to many useful statistical metrics in addition to <code>rsquared</code>.</p> <pre><code>model = sm.OLS(y, xpoly) results = model.fit() results.summary() </code></pre> <hr> <p>Below is my original Answer where I benchmarked various linear regression r^2 methods...</p> <p>The <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.corrcoef.html" rel="nofollow">corrcoef</a> function used in the Question calculates the correlation coefficient, <code>r</code>, only for a single linear regression, so it doesn't address the question of <code>r^2</code> for higher order polynomial fits. However, for what it's worth, I've come to find that for linear regression, it is indeed the fastest and most direct method of calculating <code>r</code>.</p> <pre><code>def get_r2_numpy_corrcoef(x, y): return np.corrcoef(x, y)[0, 1]**2 </code></pre> <p>These were my timeit results from comparing a bunch of methods for 1000 random (x, y) points:</p> <ul> <li>Pure Python (direct <code>r</code> calculation) <ul> <li>1000 loops, best of 3: 1.59 ms per loop</li> </ul></li> <li>Numpy polyfit (applicable to n-th degree polynomial fits) <ul> <li>1000 loops, best of 3: 326 µs per loop</li> </ul></li> <li>Numpy Manual (direct <code>r</code> calculation) <ul> <li>10000 loops, best of 3: 62.1 µs per loop</li> </ul></li> <li>Numpy corrcoef (direct <code>r</code> calculation) <ul> <li>10000 loops, best of 3: 56.6 µs per loop</li> </ul></li> <li>Scipy (linear regression with <code>r</code> as an output) <ul> <li>1000 loops, best of 3: 676 µs per loop</li> </ul></li> <li>Statsmodels (can do n-th degree polynomial and many other fits) <ul> <li>1000 loops, best of 3: 422 µs per loop</li> </ul></li> </ul> <p>The corrcoef method narrowly beats calculating the r^2 "manually" using numpy methods. It is >5X faster than the polyfit method and ~12X faster than the scipy.linregress. Just to reinforce what numpy is doing for you, it's 28X faster than pure python. I'm not well-versed in things like numba and pypy, so someone else would have to fill those gaps, but I think this is plenty convincing to me that <code>corrcoef</code> is the best tool for calculating <code>r</code> for a simple linear regression.</p> <p>Here's my benchmarking code. I copy-pasted from a Jupyter Notebook (hard not to call it an IPython Notebook...), so I apologize if anything broke on the way. The %timeit magic command requires IPython.</p> <pre><code>import numpy as np from scipy import stats import statsmodels.api as sm import math n=1000 x = np.random.rand(1000)*10 x.sort() y = 10 * x + (5+np.random.randn(1000)*10-5) x_list = list(x) y_list = list(y) def get_r2_numpy(x, y): slope, intercept = np.polyfit(x, y, 1) r_squared = 1 - (sum((y - (slope * x + intercept))**2) / ((len(y) - 1) * np.var(y, ddof=1))) return r_squared def get_r2_scipy(x, y): _, _, r_value, _, _ = stats.linregress(x, y) return r_value**2 def get_r2_statsmodels(x, y): return sm.OLS(y, sm.add_constant(x)).fit().rsquared def get_r2_python(x_list, y_list): n = len(x) x_bar = sum(x_list)/n y_bar = sum(y_list)/n x_std = math.sqrt(sum([(xi-x_bar)**2 for xi in x_list])/(n-1)) y_std = math.sqrt(sum([(yi-y_bar)**2 for yi in y_list])/(n-1)) zx = [(xi-x_bar)/x_std for xi in x_list] zy = [(yi-y_bar)/y_std for yi in y_list] r = sum(zxi*zyi for zxi, zyi in zip(zx, zy))/(n-1) return r**2 def get_r2_numpy_manual(x, y): zx = (x-np.mean(x))/np.std(x, ddof=1) zy = (y-np.mean(y))/np.std(y, ddof=1) r = np.sum(zx*zy)/(len(x)-1) return r**2 def get_r2_numpy_corrcoef(x, y): return np.corrcoef(x, y)[0, 1]**2 print('Python') %timeit get_r2_python(x_list, y_list) print('Numpy polyfit') %timeit get_r2_numpy(x, y) print('Numpy Manual') %timeit get_r2_numpy_manual(x, y) print('Numpy corrcoef') %timeit get_r2_numpy_corrcoef(x, y) print('Scipy') %timeit get_r2_scipy(x, y) print('Statsmodels') %timeit get_r2_statsmodels(x, y) </code></pre>
3
2016-01-05T17:21:45Z
[ "python", "math", "statistics", "numpy", "curve-fitting" ]
Python PySerial readline function wrong use
893,747
<p>I'm using a script importing PySerial to read from COM4</p> <p>messages I would like to intercept end with a couple of #</p> <p>so I tried to use </p> <pre><code>bus.readline(eol='##') </code></pre> <p>where bus is my connection.</p> <p>I expected to read like:</p> <ol> <li>*#*3##</li> <li>*#*3##</li> <li>*#*3##</li> </ol> <p>Unfortunalyy I found also</p> <ol> <li>*#*1##*1*1*99##</li> </ol> <p>that I expected to read spleetted into 2 lines</p> <ol> <li>*#*1##</li> <li>*1*1*99##</li> </ol> <p>Clearly readline is not working but why?</p>
2
2009-05-21T16:12:34Z
893,793
<p>The <code>readline()</code> method in pyserial reads one character at a time and compares it to the EOL character. You cannot specify multiple characters as the EOL. You'll have to read in and then split later using <code>string.split()</code> or <code>re.split()</code></p>
3
2009-05-21T16:25:22Z
[ "python", "pyserial" ]
Python: Stopping miniDOM from expanding escape sequences
893,930
<p>When xml.dom.minidom parses a piece of xml, it automagically converts escape characters for greater than and less than into their visual representation. For example: </p> <pre><code>&gt;&gt;&gt; import xml.dom.minidom &gt;&gt;&gt; s = "&lt;example&gt;4 &amp;lt; 5&lt;/example&gt;" &gt;&gt;&gt; x = xml.dom.minidom.parseString(s) &gt;&gt;&gt; x.firstChild.firstChild.data u'4 &lt; 5' </code></pre> <p>Does anyone know how to stop minidom from doing this?</p>
0
2009-05-21T16:55:53Z
894,328
<pre><code>&gt;&gt;&gt; import xml.dom.minidom &gt;&gt;&gt; s = "&lt;example&gt;4 &amp;lt; 5&lt;/example&gt;" &gt;&gt;&gt; x = xml.dom.minidom.parseString(s) &gt;&gt;&gt; x.firstChild.firstChild.toxml() u'4 &amp;lt; 5' </code></pre>
3
2009-05-21T18:20:27Z
[ "python", "xml", "minidom" ]
PyQt: Show menu in a system tray application
893,984
<p>First of all, I'm an experienced C programmer but new to python. I want to create a simple application in python using pyqt. Let's imagine this application it is as simple as when it is run it has to put an icon in the system tray and it has offer an option in its menu to exit the application.</p> <p>This code works, it shows the menu (I don't connect the exit action and so on to keep it simple)</p> <pre><code>import sys from PyQt4 import QtGui def main(): app = QtGui.QApplication(sys.argv) trayIcon = QtGui.QSystemTrayIcon(QtGui.QIcon("Bomb.xpm"), app) menu = QtGui.QMenu() exitAction = menu.addAction("Exit") trayIcon.setContextMenu(menu) trayIcon.show() sys.exit(app.exec_()) if __name__ == '__main__': main() </code></pre> <p>But this doesn't:</p> <pre><code>import sys from PyQt4 import QtGui class SystemTrayIcon(QtGui.QSystemTrayIcon): def __init__(self, icon, parent=None): QtGui.QSystemTrayIcon.__init__(self, icon, parent) menu = QtGui.QMenu() exitAction = menu.addAction("Exit") self.setContextMenu(menu) def main(): app = QtGui.QApplication(sys.argv) trayIcon = SystemTrayIcon(QtGui.QIcon("Bomb.xpm"), app) trayIcon.show() sys.exit(app.exec_()) if __name__ == '__main__': main() </code></pre> <p>I probably missing something. There are no errors but in the second case when I click with the right button it doesn't show the menu.</p> <p>Thanks a lot for your help!!!</p>
20
2009-05-21T17:05:35Z
895,721
<p>Well, after some debugging I found the problem. The QMenu object it is destroyed after finish <code>__init__</code> function because it doesn't have a parent. While the parent of a QSystemTrayIcon can be an object for the QMenu it has to be a Qwidget. This code works (see how QMenu gets the same parent as the QSystemTrayIcon which is an QWidget):</p> <pre><code>import sys from PyQt4 import QtGui class SystemTrayIcon(QtGui.QSystemTrayIcon): def __init__(self, icon, parent=None): QtGui.QSystemTrayIcon.__init__(self, icon, parent) menu = QtGui.QMenu(parent) exitAction = menu.addAction("Exit") self.setContextMenu(menu) def main(): app = QtGui.QApplication(sys.argv) w = QtGui.QWidget() trayIcon = SystemTrayIcon(QtGui.QIcon("Bomb.xpm"), w) trayIcon.show() sys.exit(app.exec_()) if __name__ == '__main__': main() </code></pre>
24
2009-05-21T23:08:33Z
[ "python", "menu", "pyqt", "system-tray" ]
PyQt: Show menu in a system tray application
893,984
<p>First of all, I'm an experienced C programmer but new to python. I want to create a simple application in python using pyqt. Let's imagine this application it is as simple as when it is run it has to put an icon in the system tray and it has offer an option in its menu to exit the application.</p> <p>This code works, it shows the menu (I don't connect the exit action and so on to keep it simple)</p> <pre><code>import sys from PyQt4 import QtGui def main(): app = QtGui.QApplication(sys.argv) trayIcon = QtGui.QSystemTrayIcon(QtGui.QIcon("Bomb.xpm"), app) menu = QtGui.QMenu() exitAction = menu.addAction("Exit") trayIcon.setContextMenu(menu) trayIcon.show() sys.exit(app.exec_()) if __name__ == '__main__': main() </code></pre> <p>But this doesn't:</p> <pre><code>import sys from PyQt4 import QtGui class SystemTrayIcon(QtGui.QSystemTrayIcon): def __init__(self, icon, parent=None): QtGui.QSystemTrayIcon.__init__(self, icon, parent) menu = QtGui.QMenu() exitAction = menu.addAction("Exit") self.setContextMenu(menu) def main(): app = QtGui.QApplication(sys.argv) trayIcon = SystemTrayIcon(QtGui.QIcon("Bomb.xpm"), app) trayIcon.show() sys.exit(app.exec_()) if __name__ == '__main__': main() </code></pre> <p>I probably missing something. There are no errors but in the second case when I click with the right button it doesn't show the menu.</p> <p>Thanks a lot for your help!!!</p>
20
2009-05-21T17:05:35Z
3,230,687
<p>I think I would prefer the following as it doesn't seem to depend upon QT's internal garbage collection decisions.</p> <pre><code>import sys from PyQt4 import QtGui class SystemTrayIcon(QtGui.QSystemTrayIcon): def __init__(self, icon, parent=None): QtGui.QSystemTrayIcon.__init__(self, icon, parent) self.menu = QtGui.QMenu(parent) exitAction = self.menu.addAction("Exit") self.setContextMenu(self.menu) def main(): app = QtGui.QApplication(sys.argv) style = app.style() icon = QtGui.QIcon(style.standardPixmap(QtGui.QStyle.SP_FileIcon)) trayIcon = SystemTrayIcon(icon) trayIcon.show() sys.exit(app.exec_()) if __name__ == '__main__': main() </code></pre>
6
2010-07-12T17:32:23Z
[ "python", "menu", "pyqt", "system-tray" ]
How do I get the current file, current class, and current method with Python?
894,088
<ul> <li>Name of the file from where code is running</li> <li>Name of the class from where code is running</li> <li>Name of the method (attribute of the class) where code is running</li> </ul>
28
2009-05-21T17:23:59Z
894,108
<pre><code>self.__class__.__name__ # name of class i'm in </code></pre> <p>for the rest the sys and trace modules</p> <p><a href="http://docs.python.org/library/sys.html" rel="nofollow">http://docs.python.org/library/sys.html</a> <a href="http://docs.python.org/library/trace.html" rel="nofollow">http://docs.python.org/library/trace.html</a></p> <p>Some more info: <a href="https://mail.python.org/pipermail/python-list/2001-August/096499.html" rel="nofollow">https://mail.python.org/pipermail/python-list/2001-August/096499.html</a> and <a href="http://www.dalkescientific.com/writings/diary/archive/2005/04/20/tracing_python_code.html" rel="nofollow">http://www.dalkescientific.com/writings/diary/archive/2005/04/20/tracing_python_code.html</a></p> <p>did you want it for error reporting because the traceback module can handle that:</p> <p><a href="http://docs.python.org/library/traceback.html" rel="nofollow">http://docs.python.org/library/traceback.html</a></p>
5
2009-05-21T17:28:33Z
[ "python", "filenames" ]
How do I get the current file, current class, and current method with Python?
894,088
<ul> <li>Name of the file from where code is running</li> <li>Name of the class from where code is running</li> <li>Name of the method (attribute of the class) where code is running</li> </ul>
28
2009-05-21T17:23:59Z
894,137
<p>Here is an example of each:</p> <pre><code>from inspect import stack class Foo: def __init__(self): print __file__ print self.__class__.__name__ print stack()[0][3] f = Foo() </code></pre>
30
2009-05-21T17:34:00Z
[ "python", "filenames" ]
How do I get the current file, current class, and current method with Python?
894,088
<ul> <li>Name of the file from where code is running</li> <li>Name of the class from where code is running</li> <li>Name of the method (attribute of the class) where code is running</li> </ul>
28
2009-05-21T17:23:59Z
894,138
<pre><code>import sys class A: def __init__(self): print __file__ print self.__class__.__name__ print sys._getframe().f_code.co_name a = A() </code></pre>
9
2009-05-21T17:34:10Z
[ "python", "filenames" ]
How do I get the current file, current class, and current method with Python?
894,088
<ul> <li>Name of the file from where code is running</li> <li>Name of the class from where code is running</li> <li>Name of the method (attribute of the class) where code is running</li> </ul>
28
2009-05-21T17:23:59Z
895,318
<p>Be <em>very</em> careful. Consider:</p> <pre><code>class A: pass B = A b = B() </code></pre> <p>What is the 'class name' of <code>b</code> here? Is it A, or B? Why?</p> <p>The point is, you shouldn't need to know or care. An object is what it is: its name is very rarely useful.</p>
4
2009-05-21T21:39:35Z
[ "python", "filenames" ]
More Pythonic conversion to binary?
894,157
<p>Here is a contrived example of how a lot of our classes return binary representations (to be read by C++) of themselves.</p> <pre><code>def to_binary(self): 'Return the binary representation as a string.' data = [] # Binary version number. data.append(struct.pack('&lt;I', [2])) # Image size. data.append(struct.pack('&lt;II', *self.image.size)) # Attribute count. data.append(struct.pack('&lt;I', len(self.attributes))) # Attributes. for attribute in self.attributes: # Id. data.append(struct.pack('&lt;I', attribute.id)) # Type. data.append(struct.pack('&lt;H', attribute.type)) # Extra Type. if attribute.type == 0: data.append(struct.pack('&lt;I', attribute.typeEx)) return ''.join(data) </code></pre> <p>What I dislike:</p> <ul> <li>Every line starts with <code>data.append(struct.pack(</code>, distracting from the unique part of the line.</li> <li>The byte order (<code>'&lt;'</code>) is repeated over and over again.</li> <li>You have to remember to return the boilerplate <code>''.join(data)</code>.</li> </ul> <p>What I like:</p> <ul> <li>The format specifiers appear near the attribute name. E.g., it's easy to see that <code>self.image.size</code> is written out as two unsigned ints.</li> <li>The lines are (mostly) independent. E.g., To remove the Id field from an 'attribute', you don't have to touch more than one line of code.</li> </ul> <p>Is there a more readable/pythonic way to do this?</p>
6
2009-05-21T17:39:34Z
894,209
<p>You can try to implement some sort of <a href="http://www.oreillynet.com/pub/a/python/2003/07/31/declarative%5Fpython.html" rel="nofollow">declarative syntax</a> for your data.</p> <p>Which may result in something like:</p> <pre><code>class Image(SomeClassWithMetamagic): type = PackedValue(2) attribute = PackedValue('attributes') # accessed via self.__dict__ #or using decorators @pack("&lt;II") def get_size(): pass #and a generic function in the Superclass def get_packed(): stuff </code></pre> <p>etc...</p> <p>Other examples would be SQLAlchemy's declarative_base, ToscaWidgets and sprox</p>
4
2009-05-21T17:52:09Z
[ "python" ]
More Pythonic conversion to binary?
894,157
<p>Here is a contrived example of how a lot of our classes return binary representations (to be read by C++) of themselves.</p> <pre><code>def to_binary(self): 'Return the binary representation as a string.' data = [] # Binary version number. data.append(struct.pack('&lt;I', [2])) # Image size. data.append(struct.pack('&lt;II', *self.image.size)) # Attribute count. data.append(struct.pack('&lt;I', len(self.attributes))) # Attributes. for attribute in self.attributes: # Id. data.append(struct.pack('&lt;I', attribute.id)) # Type. data.append(struct.pack('&lt;H', attribute.type)) # Extra Type. if attribute.type == 0: data.append(struct.pack('&lt;I', attribute.typeEx)) return ''.join(data) </code></pre> <p>What I dislike:</p> <ul> <li>Every line starts with <code>data.append(struct.pack(</code>, distracting from the unique part of the line.</li> <li>The byte order (<code>'&lt;'</code>) is repeated over and over again.</li> <li>You have to remember to return the boilerplate <code>''.join(data)</code>.</li> </ul> <p>What I like:</p> <ul> <li>The format specifiers appear near the attribute name. E.g., it's easy to see that <code>self.image.size</code> is written out as two unsigned ints.</li> <li>The lines are (mostly) independent. E.g., To remove the Id field from an 'attribute', you don't have to touch more than one line of code.</li> </ul> <p>Is there a more readable/pythonic way to do this?</p>
6
2009-05-21T17:39:34Z
894,237
<p>You could refactor your code to wrap boilerplate in a class. Something like:</p> <pre><code>def to_binary(self): 'Return the binary representation as a string.' binary = BinaryWrapper() # Binary version number. binary.pack('&lt;I', [2]) # alternatively, you can pass an array stuff = [ ('&lt;II', *self.image.size), # Image size. ('&lt;I', len(self.attributes)), # Attribute count ] binary.pack_all(stuff) return binary.get_packed() </code></pre>
0
2009-05-21T17:58:25Z
[ "python" ]
More Pythonic conversion to binary?
894,157
<p>Here is a contrived example of how a lot of our classes return binary representations (to be read by C++) of themselves.</p> <pre><code>def to_binary(self): 'Return the binary representation as a string.' data = [] # Binary version number. data.append(struct.pack('&lt;I', [2])) # Image size. data.append(struct.pack('&lt;II', *self.image.size)) # Attribute count. data.append(struct.pack('&lt;I', len(self.attributes))) # Attributes. for attribute in self.attributes: # Id. data.append(struct.pack('&lt;I', attribute.id)) # Type. data.append(struct.pack('&lt;H', attribute.type)) # Extra Type. if attribute.type == 0: data.append(struct.pack('&lt;I', attribute.typeEx)) return ''.join(data) </code></pre> <p>What I dislike:</p> <ul> <li>Every line starts with <code>data.append(struct.pack(</code>, distracting from the unique part of the line.</li> <li>The byte order (<code>'&lt;'</code>) is repeated over and over again.</li> <li>You have to remember to return the boilerplate <code>''.join(data)</code>.</li> </ul> <p>What I like:</p> <ul> <li>The format specifiers appear near the attribute name. E.g., it's easy to see that <code>self.image.size</code> is written out as two unsigned ints.</li> <li>The lines are (mostly) independent. E.g., To remove the Id field from an 'attribute', you don't have to touch more than one line of code.</li> </ul> <p>Is there a more readable/pythonic way to do this?</p>
6
2009-05-21T17:39:34Z
894,358
<pre><code>def to_binary(self): struct_i_pack = struct.Struct('&lt;I').pack struct_ii_pack = struct.Struct('&lt;II').pack struct_h_pack = struct.Struct('&lt;H').pack struct_ih_pack = struct.Struct('&lt;IH').pack struct_ihi_pack = struct.Struct('&lt;IHI').pack return ''.join([ struct_i_pack(2), struct_ii_pack(*self.image.size), struct_i_pack(len(self.attributes)), ''.join([ struct_ih_pack(a.id, a.type) if a.type else struct_ihi_pack(a.id, a.type, a.typeEx) for a in attributes ]) ]) </code></pre>
1
2009-05-21T18:24:41Z
[ "python" ]
More Pythonic conversion to binary?
894,157
<p>Here is a contrived example of how a lot of our classes return binary representations (to be read by C++) of themselves.</p> <pre><code>def to_binary(self): 'Return the binary representation as a string.' data = [] # Binary version number. data.append(struct.pack('&lt;I', [2])) # Image size. data.append(struct.pack('&lt;II', *self.image.size)) # Attribute count. data.append(struct.pack('&lt;I', len(self.attributes))) # Attributes. for attribute in self.attributes: # Id. data.append(struct.pack('&lt;I', attribute.id)) # Type. data.append(struct.pack('&lt;H', attribute.type)) # Extra Type. if attribute.type == 0: data.append(struct.pack('&lt;I', attribute.typeEx)) return ''.join(data) </code></pre> <p>What I dislike:</p> <ul> <li>Every line starts with <code>data.append(struct.pack(</code>, distracting from the unique part of the line.</li> <li>The byte order (<code>'&lt;'</code>) is repeated over and over again.</li> <li>You have to remember to return the boilerplate <code>''.join(data)</code>.</li> </ul> <p>What I like:</p> <ul> <li>The format specifiers appear near the attribute name. E.g., it's easy to see that <code>self.image.size</code> is written out as two unsigned ints.</li> <li>The lines are (mostly) independent. E.g., To remove the Id field from an 'attribute', you don't have to touch more than one line of code.</li> </ul> <p>Is there a more readable/pythonic way to do this?</p>
6
2009-05-21T17:39:34Z
894,469
<pre><code>from StringIO import StringIO import struct class BinaryIO(StringIO): def writepack(self, fmt, *values): self.write(struct.pack('&lt;' + fmt, *values)) def to_binary_example(): data = BinaryIO() data.writepack('I', 42) data.writepack('II', 1, 2) return data.getvalue() </code></pre>
4
2009-05-21T18:48:11Z
[ "python" ]
More Pythonic conversion to binary?
894,157
<p>Here is a contrived example of how a lot of our classes return binary representations (to be read by C++) of themselves.</p> <pre><code>def to_binary(self): 'Return the binary representation as a string.' data = [] # Binary version number. data.append(struct.pack('&lt;I', [2])) # Image size. data.append(struct.pack('&lt;II', *self.image.size)) # Attribute count. data.append(struct.pack('&lt;I', len(self.attributes))) # Attributes. for attribute in self.attributes: # Id. data.append(struct.pack('&lt;I', attribute.id)) # Type. data.append(struct.pack('&lt;H', attribute.type)) # Extra Type. if attribute.type == 0: data.append(struct.pack('&lt;I', attribute.typeEx)) return ''.join(data) </code></pre> <p>What I dislike:</p> <ul> <li>Every line starts with <code>data.append(struct.pack(</code>, distracting from the unique part of the line.</li> <li>The byte order (<code>'&lt;'</code>) is repeated over and over again.</li> <li>You have to remember to return the boilerplate <code>''.join(data)</code>.</li> </ul> <p>What I like:</p> <ul> <li>The format specifiers appear near the attribute name. E.g., it's easy to see that <code>self.image.size</code> is written out as two unsigned ints.</li> <li>The lines are (mostly) independent. E.g., To remove the Id field from an 'attribute', you don't have to touch more than one line of code.</li> </ul> <p>Is there a more readable/pythonic way to do this?</p>
6
2009-05-21T17:39:34Z
894,584
<p>The worst problem is that you need corresponding code in C++ to read the output. Can you reasonably arrange to have both the reading and writing code mechanically derive from or use a common specification? How to go about that depends on your C++ needs as much as Python.</p>
0
2009-05-21T19:12:22Z
[ "python" ]
More Pythonic conversion to binary?
894,157
<p>Here is a contrived example of how a lot of our classes return binary representations (to be read by C++) of themselves.</p> <pre><code>def to_binary(self): 'Return the binary representation as a string.' data = [] # Binary version number. data.append(struct.pack('&lt;I', [2])) # Image size. data.append(struct.pack('&lt;II', *self.image.size)) # Attribute count. data.append(struct.pack('&lt;I', len(self.attributes))) # Attributes. for attribute in self.attributes: # Id. data.append(struct.pack('&lt;I', attribute.id)) # Type. data.append(struct.pack('&lt;H', attribute.type)) # Extra Type. if attribute.type == 0: data.append(struct.pack('&lt;I', attribute.typeEx)) return ''.join(data) </code></pre> <p>What I dislike:</p> <ul> <li>Every line starts with <code>data.append(struct.pack(</code>, distracting from the unique part of the line.</li> <li>The byte order (<code>'&lt;'</code>) is repeated over and over again.</li> <li>You have to remember to return the boilerplate <code>''.join(data)</code>.</li> </ul> <p>What I like:</p> <ul> <li>The format specifiers appear near the attribute name. E.g., it's easy to see that <code>self.image.size</code> is written out as two unsigned ints.</li> <li>The lines are (mostly) independent. E.g., To remove the Id field from an 'attribute', you don't have to touch more than one line of code.</li> </ul> <p>Is there a more readable/pythonic way to do this?</p>
6
2009-05-21T17:39:34Z
894,844
<p>You can get rid of the repetition while still as readable easily like this:</p> <pre><code>def to_binary(self): output = struct.pack( '&lt;IIII', 2, self.image.size[0], self.image.size[1], len(self.attributes) ) return output + ''.join( struct.pack('&lt;IHI', attribute.id, attribute.type, attribute.typeEx) for attribute in self.attributes ) </code></pre>
0
2009-05-21T20:05:05Z
[ "python" ]
More Pythonic conversion to binary?
894,157
<p>Here is a contrived example of how a lot of our classes return binary representations (to be read by C++) of themselves.</p> <pre><code>def to_binary(self): 'Return the binary representation as a string.' data = [] # Binary version number. data.append(struct.pack('&lt;I', [2])) # Image size. data.append(struct.pack('&lt;II', *self.image.size)) # Attribute count. data.append(struct.pack('&lt;I', len(self.attributes))) # Attributes. for attribute in self.attributes: # Id. data.append(struct.pack('&lt;I', attribute.id)) # Type. data.append(struct.pack('&lt;H', attribute.type)) # Extra Type. if attribute.type == 0: data.append(struct.pack('&lt;I', attribute.typeEx)) return ''.join(data) </code></pre> <p>What I dislike:</p> <ul> <li>Every line starts with <code>data.append(struct.pack(</code>, distracting from the unique part of the line.</li> <li>The byte order (<code>'&lt;'</code>) is repeated over and over again.</li> <li>You have to remember to return the boilerplate <code>''.join(data)</code>.</li> </ul> <p>What I like:</p> <ul> <li>The format specifiers appear near the attribute name. E.g., it's easy to see that <code>self.image.size</code> is written out as two unsigned ints.</li> <li>The lines are (mostly) independent. E.g., To remove the Id field from an 'attribute', you don't have to touch more than one line of code.</li> </ul> <p>Is there a more readable/pythonic way to do this?</p>
6
2009-05-21T17:39:34Z
894,890
<p>If you just want nicer syntax, you can abuse generators/decorators:</p> <pre><code>from functools import wraps def packed(g): '''a decorator that packs the list data items that is generated by the decorated function ''' @wraps(g) def wrapper(*p, **kw): data = [] for params in g(*p, **kw): fmt = params[0] fields = params[1:] data.append(struct.pack('&lt;'+fmt, *fields)) return ''.join(data) return wrapper @packed def as_binary(self): '''just |yield|s the data items that should be packed by the decorator ''' yield 'I', [2] yield 'II', self.image.size[0], self.image.size[1] yield 'I', len(self.attributes) for attribute in self.attributes: yield 'I', attribute.id yield 'H', attribute.type if attribute.type == 0: yield 'I', attribute.typeEx </code></pre> <p>Basically this uses the generator to implement a "monad", an abstraction usually found in functional languages like Haskell. It separates the generation of some values from the code that decides how to combine these values together. It's more a functional programming approach then "pythonic", but I think it improves readability.</p>
2
2009-05-21T20:12:34Z
[ "python" ]
More Pythonic conversion to binary?
894,157
<p>Here is a contrived example of how a lot of our classes return binary representations (to be read by C++) of themselves.</p> <pre><code>def to_binary(self): 'Return the binary representation as a string.' data = [] # Binary version number. data.append(struct.pack('&lt;I', [2])) # Image size. data.append(struct.pack('&lt;II', *self.image.size)) # Attribute count. data.append(struct.pack('&lt;I', len(self.attributes))) # Attributes. for attribute in self.attributes: # Id. data.append(struct.pack('&lt;I', attribute.id)) # Type. data.append(struct.pack('&lt;H', attribute.type)) # Extra Type. if attribute.type == 0: data.append(struct.pack('&lt;I', attribute.typeEx)) return ''.join(data) </code></pre> <p>What I dislike:</p> <ul> <li>Every line starts with <code>data.append(struct.pack(</code>, distracting from the unique part of the line.</li> <li>The byte order (<code>'&lt;'</code>) is repeated over and over again.</li> <li>You have to remember to return the boilerplate <code>''.join(data)</code>.</li> </ul> <p>What I like:</p> <ul> <li>The format specifiers appear near the attribute name. E.g., it's easy to see that <code>self.image.size</code> is written out as two unsigned ints.</li> <li>The lines are (mostly) independent. E.g., To remove the Id field from an 'attribute', you don't have to touch more than one line of code.</li> </ul> <p>Is there a more readable/pythonic way to do this?</p>
6
2009-05-21T17:39:34Z
894,908
<p>How about <a href="http://code.google.com/p/protobuf/" rel="nofollow">protocol buffers</a> google's extensive cross language format and protocol of sharing data. </p>
2
2009-05-21T20:15:31Z
[ "python" ]
Programmatically make HTTP requests through proxies with Python
894,168
<p>How do I use Python to make an HTTP request through a proxy?</p> <p>What do I need to do to the following code?</p> <pre><code>urllib.urlopen('http://www.google.com') </code></pre>
4
2009-05-21T17:43:26Z
894,170
<p>The <code>urlopen</code> function supports proxies. Try something like this:</p> <pre><code>urllib.urlopen(your_url, proxies = {"http" : "http://192.168.0.1:80"}) </code></pre>
6
2009-05-21T17:44:42Z
[ "python", "http", "proxy" ]
Programmatically make HTTP requests through proxies with Python
894,168
<p>How do I use Python to make an HTTP request through a proxy?</p> <p>What do I need to do to the following code?</p> <pre><code>urllib.urlopen('http://www.google.com') </code></pre>
4
2009-05-21T17:43:26Z
894,173
<p>You could look at <a href="http://pycurl.sourceforge.net/" rel="nofollow">PycURL</a>. I use cURL a lot in PHP and i love it. Though there is probably a neat way to do this currently in Python.</p>
1
2009-05-21T17:45:03Z
[ "python", "http", "proxy" ]
How does setuptools decide which files to keep for sdist/bdist?
894,323
<p>I'm working on a Python package that uses <code>namespace_packages</code> and <code>find_packages()</code> like so in setup.py:</p> <pre><code>from setuptools import setup, find_packages setup(name="package", version="1.3.3.7", package=find_packages(), namespace_packages=['package'], ...) </code></pre> <p>It isn't in source control because it is a bundle of upstream components. There is no MANIFEST.</p> <p>When I run <code>python setup.py sdist</code> I get a tarball of most of the files under the <code>package/</code> directory but any directories that don't contain <code>.py</code> files are left out.</p> <p>What are the default rules for what <code>setup.py</code> includes and excludes from built distributions? I've fixed my problem by adding a <code>MANIFEST.in</code> with</p> <pre><code>recursive-include package * </code></pre> <p>but I would like to understand what setuptools and distutils are doing by default.</p>
6
2009-05-21T18:19:08Z
894,341
<p>You need to add a package_data directive. For example, if you want to include files with .txt or .rst extensions:</p> <pre><code>from setuptools import setup, find_packages setup(name="package", version="1.3.3.7", package=find_packages(), namespace_packages=['package'], package_data = { # If any package contains *.txt or *.rst files, include them: '': ['*.txt', '*.rst']... ) </code></pre>
4
2009-05-21T18:22:38Z
[ "python", "setuptools", "distutils" ]
Multi-server monitor/auto restarter in python
894,474
<p>I have 2 server programs that must be started with the use of GNU Screen. I'd like to harden these servers against crashes with a Python based program that kicks off each screen session then monitors the server process. If the server process crashes, I need the python code to kill the extraneous screen session and restart the server with screen again.</p> <p>I'm very new to python but I'm using this opportunity to teach myself. I'm aware this can be done in bash scripting. But I want to build on this code for future features, so it needs to be just python.</p> <p>The pseudocode is as follows:</p> <pre><code>thread-one { While 1: start server 1 using screen wait for server to end end while } thread-two { While 1: start server 2 using screen wait for server to end end while } </code></pre>
3
2009-05-21T18:51:07Z
894,648
<p>You really shouldn't run production software on a screen. If the server gets rebooted, how will You start it up? Manually? Also I think that You are trying to re-invent the wheel. There are already pretty good tools that do the thing You need.</p> <blockquote> <p><a href="http://freshmeat.net/projects/launchtool/" rel="nofollow">launchtool</a> lets you run a user-supplied command supervising its execution in many ways, such as controlling its environment, blocking signals, logging its output, changing user and group permissions, limiting resource usage, restarting it if it fails, running it continuously, turning it into a daemon, and more.</p> </blockquote> <p>.</p> <blockquote> <p><a href="http://mmonit.com/monit/" rel="nofollow">Monit</a> is a free open source utility for managing and monitoring, processes, files, directories and filesystems on a UNIX system. Monit conducts automatic maintenance and repair and can execute meaningful causal actions in error situations.</p> </blockquote>
3
2009-05-21T19:23:00Z
[ "python", "linux", "bash", "restart" ]
Multi-server monitor/auto restarter in python
894,474
<p>I have 2 server programs that must be started with the use of GNU Screen. I'd like to harden these servers against crashes with a Python based program that kicks off each screen session then monitors the server process. If the server process crashes, I need the python code to kill the extraneous screen session and restart the server with screen again.</p> <p>I'm very new to python but I'm using this opportunity to teach myself. I'm aware this can be done in bash scripting. But I want to build on this code for future features, so it needs to be just python.</p> <p>The pseudocode is as follows:</p> <pre><code>thread-one { While 1: start server 1 using screen wait for server to end end while } thread-two { While 1: start server 2 using screen wait for server to end end while } </code></pre>
3
2009-05-21T18:51:07Z
894,722
<p>"need to be multi-threaded to handle the restarting of two separate programs" </p> <p>Don't see why.</p> <pre><code>import subprocess commands = [ ["p1"], ["p2"] ] programs = [ subprocess.Popen(c) for c in commands ] while True: for i in range(len(programs)): if programs[i].returncode is None: continue # still running else: # restart this one programs[i]= subprocess.Popen(commands[i]) time.sleep(1.0) </code></pre>
5
2009-05-21T19:37:16Z
[ "python", "linux", "bash", "restart" ]
Has Python changed to more object oriented?
894,502
<p>I remember that at one point, <a href="http://www.linuxdevcenter.com/pub/a/linux/2001/11/29/ruby.html" rel="nofollow">it was said that Python is less object oriented than Ruby</a>, since in Ruby, everything is an object. Has this changed for Python as well? Is the latest Python more object oriented than the previous version?</p>
9
2009-05-21T18:56:03Z
894,541
<p>I'm not sure that I buy the argument that Ruby is more object-oriented than Python. There's more to being object-oriented than just using objects and dot syntax. A common argument that I see is that in Python to get the length of a list, you do something like this:</p> <pre><code>len(some_list) </code></pre> <p>I see this as a <a href="http://en.wikipedia.org/wiki/Color%5Fof%5Fthe%5Fbikeshed">bikeshed argument</a>. What this really translates to (almost directly) is this:</p> <pre><code>some_list.__len__() </code></pre> <p>which is perfectly object oriented. I think Rubyists may get a bit confused because typically being object-oriented involves using the dot syntax (for example <code>object.method()</code>). However, if I misunderstand Rubyists' arguments, feel free to let me know.</p> <p>Regardless of the object-orientation of this, there is one advantage to using len this way. One thing that's always annoyed me about some languages is having to remember whether to use <code>some_list.size()</code> or <code>some_list.length()</code> or <code>some_list.len</code> for a particular object. Python's way means just one function to remember</p>
12
2009-05-21T19:03:43Z
[ "python", "ruby", "oop" ]
Has Python changed to more object oriented?
894,502
<p>I remember that at one point, <a href="http://www.linuxdevcenter.com/pub/a/linux/2001/11/29/ruby.html" rel="nofollow">it was said that Python is less object oriented than Ruby</a>, since in Ruby, everything is an object. Has this changed for Python as well? Is the latest Python more object oriented than the previous version?</p>
9
2009-05-21T18:56:03Z
894,618
<p>Hold on, both Ruby and Python are object oriented. Objects are objects. There isn't more object oriented 'comparison function' that will lead you to the better one. <em>Syntax</em> is not only thing which makes some language to look like object oriented one, but also <em>data model</em>.</p> <blockquote> <p>Objects are Python’s abstraction for data. All data in a Python program is represented by objects or by relations between objects. (In a sense, and in conformance to Von Neumann’s model of a “stored program computer,” code is also represented by objects.) <a href="http://docs.python.org/reference/datamodel.html" rel="nofollow">http://docs.python.org/reference/datamodel.html</a></p> </blockquote>
2
2009-05-21T19:18:40Z
[ "python", "ruby", "oop" ]
Has Python changed to more object oriented?
894,502
<p>I remember that at one point, <a href="http://www.linuxdevcenter.com/pub/a/linux/2001/11/29/ruby.html" rel="nofollow">it was said that Python is less object oriented than Ruby</a>, since in Ruby, everything is an object. Has this changed for Python as well? Is the latest Python more object oriented than the previous version?</p>
9
2009-05-21T18:56:03Z
894,692
<p>Jian Lin — the answer is "Yes", Python is more object-oriented than when Matz decided he wanted to create Ruby, and both languages now feature "everything is an object". Back when Python was younger, "types" like strings and numbers lacked methods, whereas "objects" were built with the "class" statement (or by deliberately building a class in a C extension module) and were a bit less efficient but did support methods and inheritance. For the very early 1990s, when a fast 386 was a pretty nice machine, this compromise made sense. But types and classes were unified in Python 2.2 (released in 2001), and strings got methods and, in more recent Python versions, users can even subclass from them.</p> <p>So: Python was certainly less object oriented at one time; but, so far as I know, every one of those old barriers is now gone.</p> <p>Here's the guide to the unification that took place:</p> <p><a href="http://www.python.org/download/releases/2.2/descrintro/">http://www.python.org/download/releases/2.2/descrintro/</a></p> <p><strong>Clarification:</strong> perhaps I can put it even more simply: in Python, everything has <em>always</em> been an object; but some basic kinds of object (ints, strings) once played by "different rules" that prevent OO programming methods (like inheritance) from being used with them. That has now been fixed. The len() method, described in another response here, is probably the only thing left that I wish Guido had changed in the upgrade to Python 3.0. But at least he gave me dictionary comprehensions, so I won't complain too loudly. :-)</p>
39
2009-05-21T19:32:01Z
[ "python", "ruby", "oop" ]
Has Python changed to more object oriented?
894,502
<p>I remember that at one point, <a href="http://www.linuxdevcenter.com/pub/a/linux/2001/11/29/ruby.html" rel="nofollow">it was said that Python is less object oriented than Ruby</a>, since in Ruby, everything is an object. Has this changed for Python as well? Is the latest Python more object oriented than the previous version?</p>
9
2009-05-21T18:56:03Z
894,711
<p>This is an incorrect belief.</p> <p>See my previous answer here for more in-depth explanation:</p> <p><a href="http://stackoverflow.com/questions/865911/is-everything-an-object-in-python-like-ruby/865963#865963">http://stackoverflow.com/questions/865911/is-everything-an-object-in-python-like-ruby/865963#865963</a></p> <blockquote> <p>Why not expose .len() directly off of list then? I think you can't completely divorce OO design from the syntax, because the syntax, to a large extent, defines your code paradigm. some_list.len() is OO because you are thinking about the list as an object that will be able to tell you what its length is. len(some_list)</p> </blockquote> <p>.len() is available directly off the list. It is available as __len__(). len() is a function object. You can see all its methods with dir(len). While I do not know why Guido decided to make the __len__() method longer, it does not change the fact that all of those are still objects.</p>
2
2009-05-21T19:35:39Z
[ "python", "ruby", "oop" ]
Has Python changed to more object oriented?
894,502
<p>I remember that at one point, <a href="http://www.linuxdevcenter.com/pub/a/linux/2001/11/29/ruby.html" rel="nofollow">it was said that Python is less object oriented than Ruby</a>, since in Ruby, everything is an object. Has this changed for Python as well? Is the latest Python more object oriented than the previous version?</p>
9
2009-05-21T18:56:03Z
894,716
<p>Although this is not properly an answer... Why do you care about Python being more or less OO? The cool thing about Python is that it's <em>pythonic</em>, not object oriented or funcitonal or whichever paradigm that is fashionable at the moment! :-)</p> <p>I learnt to program with Java and Object Orientation, but now I don't give a sh.t about it because I know that OOP is not the solution to all the problems (indeed, no single paradigm is).</p> <p>see:</p> <ul> <li><a href="http://www.python.org/dev/peps/pep-0020/">The Zen of Python</a></li> <li><a href="http://faassen.n--tree.net/blog/view/weblog/2005/08/06/0">What is Pythonic</a></li> <li><a href="http://cafepy.com/article/59/">Be Pythonic</a></li> </ul>
7
2009-05-21T19:36:28Z
[ "python", "ruby", "oop" ]
Has Python changed to more object oriented?
894,502
<p>I remember that at one point, <a href="http://www.linuxdevcenter.com/pub/a/linux/2001/11/29/ruby.html" rel="nofollow">it was said that Python is less object oriented than Ruby</a>, since in Ruby, everything is an object. Has this changed for Python as well? Is the latest Python more object oriented than the previous version?</p>
9
2009-05-21T18:56:03Z
894,784
<p>I have the same <strong>"perception"</strong> perhaps derived from this:</p> <p><a href="http://www.python.org/doc/faq/general/#why-was-python-created-in-the-first-place" rel="nofollow">Why was python created in the first place:</a></p> <blockquote> <p><em>It occurred to me that a scripting language with a syntax like ABC [...] would fill the need</em></p> </blockquote> <p><a href="http://www.linuxdevcenter.com/pub/a/linux/2001/11/29/ruby.html" rel="nofollow">An Interview with the Creator of Ruby:</a></p> <blockquote> <p><em>"I wanted a scripting language that was more powerful than Perl, and more object-oriented than Python</em></p> </blockquote> <p>I know that perception is not the same as reality. Both Python and Ruby are great programming languages and both are very OO. </p>
1
2009-05-21T19:51:10Z
[ "python", "ruby", "oop" ]
Unable to replace the word in a given folder's contents by Sed/Python/Perl
894,802
<p>I have a project where I have folders, subfolders, and files. I need to replace the word Masi by the word Bond in each files.</p> <p>I run the following Sed script called replace unsuccessfully</p> <pre><code>s/Masi/Bond/ </code></pre> <p>in Zsh by </p> <pre><code>sed -f PATH/replace PATH2/project/** </code></pre> <p>It gives me all files, also the ones which do not have Masi, as an output.</p> <p>Sed is not necessarily the best tool for the task. I am interested in Python and Perl.</p> <p><strong>How would you do the replacement in Sed/Perl/Python,</strong> such that only the file contents are changed?</p>
0
2009-05-21T19:54:47Z
894,830
<p>Why not just pass the <code>-i</code> option (<code>man sed</code>) to sed and be done with it? If it doesn't find Masi in a file, the file will just be rewritten with no modification. Or am I missing something?</p> <p>If you don't want to replace the files' contents inline (which is what the <code>-i</code> will do) you can do exactly as you are now, but throw a <code>grep</code> &amp; <code>xargs</code> in front of it:</p> <pre><code>grep -rl Masi PATH/project/* | xargs sed -f PATH/replace </code></pre> <p>Lots of options, but do <strong>not</strong> write an entire perl script for this (I'll give the one-liner a pass ;)). <code>find</code>, <code>grep</code>, <code>sed</code>, <code>xargs</code>, etc. will always be more flexible, IMHO.</p> <p>In response to comment:</p> <pre><code>grep -rl Masi PATH/project/* | xargs sed -n -e '/Masi/ p' </code></pre>
3
2009-05-21T20:02:50Z
[ "python", "perl", "sed", "replace" ]
Unable to replace the word in a given folder's contents by Sed/Python/Perl
894,802
<p>I have a project where I have folders, subfolders, and files. I need to replace the word Masi by the word Bond in each files.</p> <p>I run the following Sed script called replace unsuccessfully</p> <pre><code>s/Masi/Bond/ </code></pre> <p>in Zsh by </p> <pre><code>sed -f PATH/replace PATH2/project/** </code></pre> <p>It gives me all files, also the ones which do not have Masi, as an output.</p> <p>Sed is not necessarily the best tool for the task. I am interested in Python and Perl.</p> <p><strong>How would you do the replacement in Sed/Perl/Python,</strong> such that only the file contents are changed?</p>
0
2009-05-21T19:54:47Z
894,834
<p><strong>To replace the word in all files found in the current directory and subdirectories</strong></p> <pre><code>perl -p -i -e 's/Masi/Bond/g' $(grep -rl Masi *) </code></pre> <p>The above won't work if you have spaces in filenames. Safer to do:</p> <pre><code>find . -type f -exec perl -p -i -e 's/Masi/Bond/g' {} \; </code></pre> <p>or in Mac which has spaces in filenames</p> <pre><code>find . -type f -print0 | xargs -0 perl -p -i -e 's/Masi/Bond/g' </code></pre> <p><strong>Explanations</strong></p> <ul> <li>-p means print or die</li> <li>-i means "do not make any backup files"</li> <li>-e allows you to run perl code in command line</li> </ul>
12
2009-05-21T20:03:13Z
[ "python", "perl", "sed", "replace" ]
Unable to replace the word in a given folder's contents by Sed/Python/Perl
894,802
<p>I have a project where I have folders, subfolders, and files. I need to replace the word Masi by the word Bond in each files.</p> <p>I run the following Sed script called replace unsuccessfully</p> <pre><code>s/Masi/Bond/ </code></pre> <p>in Zsh by </p> <pre><code>sed -f PATH/replace PATH2/project/** </code></pre> <p>It gives me all files, also the ones which do not have Masi, as an output.</p> <p>Sed is not necessarily the best tool for the task. I am interested in Python and Perl.</p> <p><strong>How would you do the replacement in Sed/Perl/Python,</strong> such that only the file contents are changed?</p>
0
2009-05-21T19:54:47Z
894,850
<p><strong>A solution tested on Windows</strong></p> <p>Requires CPAN module File::Slurp. Will work with standard Unix shell wildcards. Like ./replace.pl PATH/replace.txt PATH2/replace*</p> <pre><code>#!/usr/bin/perl use strict; use warnings; use File::Glob ':glob'; use File::Slurp; foreach my $dir (@ARGV) { my @filelist = bsd_glob($dir); foreach my $file (@filelist) { next if -d $file; my $c=read_file($file); if ($c=~s/Masi/Bond/g) { print "replaced in $file\n"; write_file($file,$c); } else { print "no match in $file\n"; } } } </code></pre>
0
2009-05-21T20:05:43Z
[ "python", "perl", "sed", "replace" ]
Unable to replace the word in a given folder's contents by Sed/Python/Perl
894,802
<p>I have a project where I have folders, subfolders, and files. I need to replace the word Masi by the word Bond in each files.</p> <p>I run the following Sed script called replace unsuccessfully</p> <pre><code>s/Masi/Bond/ </code></pre> <p>in Zsh by </p> <pre><code>sed -f PATH/replace PATH2/project/** </code></pre> <p>It gives me all files, also the ones which do not have Masi, as an output.</p> <p>Sed is not necessarily the best tool for the task. I am interested in Python and Perl.</p> <p><strong>How would you do the replacement in Sed/Perl/Python,</strong> such that only the file contents are changed?</p>
0
2009-05-21T19:54:47Z
894,982
<p>Renaming a folder full of files:</p> <pre><code>use warnings; use strict; use File::Find::Rule; my @list = File::Find::Rule-&gt;new()-&gt;name(qr/Masi/)-&gt;file-&gt;in('./'); for( @list ){ my $old = $_; my $new = $_; $new =~ s/Masi/Bond/g; rename $old , $new ; } </code></pre> <p>Replacing Strings in Files</p> <pre><code>use warnings; use strict; use File::Find::Rule; use File::Slurp; use File::Copy; my @list = File::Find::Rule-&gt;new()-&gt;name("*.something")-&gt;file-&gt;grep(qr/Masi/)-&gt;in('./'); for( @list ){ my $c = read_file( $_ ); if ( $c =~ s/Masi/Bond/g; ){ File::Copy::copy($_, "$_.bak"); # backup. write_file( $_ , $c ); } } </code></pre> <ul> <li><a href="http://p3rl.org/strict" rel="nofollow">strict</a> (core) - Perl pragma to restrict unsafe constructs</li> <li><a href="http://p3rl.org/warnings" rel="nofollow">warnings</a> (core) - Perl pragma to control optional warnings</li> <li><a href="http://p3rl.org/File::Find::Rule" rel="nofollow">File::Find::Rule</a> - Alternative interface to File::Find </li> <li><a href="http://p3rl.org/File::Find" rel="nofollow">File::Find</a> (core) - Traverse a directory tree.</li> <li><a href="http://p3rl.org/File::Slurp" rel="nofollow">File::Slurp</a> - Efficient Reading/Writing of Complete Files</li> <li><a href="http://p3rl.org/File::Copy" rel="nofollow">File::Copy</a> (core) - Copy files or filehandles</li> </ul>
3
2009-05-21T20:30:43Z
[ "python", "perl", "sed", "replace" ]
Unable to replace the word in a given folder's contents by Sed/Python/Perl
894,802
<p>I have a project where I have folders, subfolders, and files. I need to replace the word Masi by the word Bond in each files.</p> <p>I run the following Sed script called replace unsuccessfully</p> <pre><code>s/Masi/Bond/ </code></pre> <p>in Zsh by </p> <pre><code>sed -f PATH/replace PATH2/project/** </code></pre> <p>It gives me all files, also the ones which do not have Masi, as an output.</p> <p>Sed is not necessarily the best tool for the task. I am interested in Python and Perl.</p> <p><strong>How would you do the replacement in Sed/Perl/Python,</strong> such that only the file contents are changed?</p>
0
2009-05-21T19:54:47Z
941,257
<pre><code>import glob import os # Change the glob for different filename matching for filename in glob.glob("*"): dst=filename.replace("Masi","Bond") os.rename(filename, dst) </code></pre>
0
2009-06-02T18:52:01Z
[ "python", "perl", "sed", "replace" ]
How can I launch a python script on windows?
894,845
<p>I have run a few using batch jobs, but, I am wondering what would be the most appropriate? Maybe using time.strftime?</p>
1
2009-05-21T20:05:17Z
894,869
<p>If you're looking to do recurring scheduled tasks, then the Task Scheduler (Vista) or Scheduled Tasks (XP and, I think, earlier) is the appropriate method on Windows.</p>
5
2009-05-21T20:09:00Z
[ "python" ]
How can I launch a python script on windows?
894,845
<p>I have run a few using batch jobs, but, I am wondering what would be the most appropriate? Maybe using time.strftime?</p>
1
2009-05-21T20:05:17Z
895,987
<p>I'd second using the Task Scheduler. </p> <p>I have also read about a 'cron-like' python based application PyCron - <a href="http://www.bigbluehost.com/article4.html" rel="nofollow">http://www.bigbluehost.com/article4.html</a> . If you're from the Unix end of town you might find it more familiar than the Windows scheduler. Never used it myself but it might be of interest.</p>
0
2009-05-22T00:57:34Z
[ "python" ]
Circular dependency in Python
894,864
<p>I have two files, <code>node.py</code> and <code>path.py</code>, which define two classes, <code>Node</code> and <code>Path</code>, respectively.</p> <p>Up to today, the definition for <code>Path</code> referenced the <code>Node</code> object, and therefore I had done</p> <pre><code>from node.py import * </code></pre> <p>in the <code>path.py</code> file.</p> <p>However, as of today I created a new method for <code>Node</code> that references the <code>Path</code> object.</p> <p>I had problems when trying to import <code>path.py</code>: I tried it, and when the program ran and called the <code>Path</code> method that uses <code>Node</code>, an exception rose about <code>Node</code> not being defined.</p> <p>What do I do?</p>
40
2009-05-21T20:08:08Z
894,885
<p><em><a href="http://effbot.org/zone/import-confusion.htm">Importing Python Modules</a></em> is a great article that explains circular imports in Python.</p> <p>The easiest way to fix this is to move the path import to the end of the node module.</p>
67
2009-05-21T20:11:55Z
[ "python", "circular-dependency" ]
Circular dependency in Python
894,864
<p>I have two files, <code>node.py</code> and <code>path.py</code>, which define two classes, <code>Node</code> and <code>Path</code>, respectively.</p> <p>Up to today, the definition for <code>Path</code> referenced the <code>Node</code> object, and therefore I had done</p> <pre><code>from node.py import * </code></pre> <p>in the <code>path.py</code> file.</p> <p>However, as of today I created a new method for <code>Node</code> that references the <code>Path</code> object.</p> <p>I had problems when trying to import <code>path.py</code>: I tried it, and when the program ran and called the <code>Path</code> method that uses <code>Node</code>, an exception rose about <code>Node</code> not being defined.</p> <p>What do I do?</p>
40
2009-05-21T20:08:08Z
37,812,931
<p>One other approach is importing one of the two modules <strong>only in the function</strong> where you need it in the other. Sure, this works best if you only need it in one or a small number of functions:</p> <pre><code># in node.py from path import Path class Node ... # in path.py class Path def method_needs_node(): from node import Node n = Node() ... </code></pre>
4
2016-06-14T13:05:35Z
[ "python", "circular-dependency" ]
CreateDatabase often fails on the google data api
894,881
<p>The following test program is suppossed to create a new spreadsheet:</p> <pre><code>#!/usr/bin/python import gdata.spreadsheet.text_db import getpass import atom import gdata.contacts import gdata.contacts.service import smtplib import time password = getpass.getpass() client = gdata.spreadsheet.text_db.DatabaseClient(username='jmv@gmail.com',password=password) database = client.CreateDatabase('My Test Database') table = database.CreateTable('addresses', ['name','email', 'phonenumber', 'mailingaddress']) record = table.AddRecord({'name':'Bob', 'email':'bob@example.com', 'phonenumber':'555-555-1234', 'mailingaddress':'900 Imaginary St.'}) # Edit a record record.content['email'] = 'bob2@example.com' record.Push() </code></pre> <p>which it does, but only on about every 1 out of 5 runs. On the other 4 out of 5 runs I get:</p> <pre><code>Password: Traceback (most recent call last): File "./test.py", line 13, in &lt;module&gt; database = client.CreateDatabase('My Test Database') File "/home/jmvidal/share/progs/googleapps/google_appengine/glassboard/gdata/spreadsheet/text_db.py", line 146, in CreateDatabase db_entry = self.__docs_client.UploadSpreadsheet(virtual_media_source, name) File "/home/jmvidal/share/progs/googleapps/google_appengine/glassboard/gdata/docs/service.py", line 304, in UploadSpreadsheet return self._UploadFile(media_source, title, category, folder_or_uri) File "/home/jmvidal/share/progs/googleapps/google_appengine/glassboard/gdata/docs/service.py", line 144, in _UploadFile converter=gdata.docs.DocumentListEntryFromString) File "/home/jmvidal/share/progs/googleapps/google_appengine/glassboard/gdata/service.py", line 1151, in Post media_source=media_source, converter=converter) File "/home/jmvidal/share/progs/googleapps/google_appengine/glassboard/gdata/service.py", line 1271, in PostOrPut 'reason': server_response.reason, 'body': result_body} gdata.service.RequestError: {'status': 404, 'body': '&lt;HTML&gt;\n&lt;HEAD&gt;\n&lt;TITLE&gt;Not Found&lt;/TITLE&gt;\n&lt;/HEAD&gt;\n&lt;BODY BGCOLOR="#FFFFFF" TEXT="#000000"&gt;\n&lt;H1&gt;Not Found&lt;/H1&gt;\n&lt;H2&gt;Error 404&lt;/H2&gt;\n&lt;/BODY&gt;\n&lt;/HTML&gt;\n', 'reason': 'Not Found'} </code></pre> <p>The same thing happens when I run similar code on the appengine, so I don't think this problem is due to a slow connection (also, I have a cable modem, which works at about 1Mbps). </p> <p>So, why a 404? and, more importantly, is there anyway to improve the chances that my CreateDatabase call will succeed?</p>
0
2009-05-21T20:11:43Z
897,671
<p>Someone clued me in that this is a <a href="http://code.google.com/p/gdata-issues/issues/detail?id=1147" rel="nofollow">known bug</a> in gdata.</p>
1
2009-05-22T12:48:36Z
[ "python", "gdata-api" ]
Compiled Python CGI
895,163
<p>Assuming the webserver is configured to handle <strong><em>.exe</em></strong>, Can i compile a python CGI file into an exe for speed. What would some pros and cons be to such a desession?</p>
0
2009-05-21T21:06:11Z
895,177
<p>There is <a href="http://www.py2exe.org/" rel="nofollow">py2exe</a> (<a href="http://www.ehow.com/how%5F2091641%5Fcompile-python-code.html" rel="nofollow">and a tutorial on how to use it</a>), but there is no guarentee that it will make your script any faster. Really its more of an executable interpreter that wraps the bytecode. There are other exe compilers that do varying degrees of things to the python code, so you might want to do a general Google search.</p> <p>However, you can always use <a href="http://psyco.sourceforge.net/doc.html" rel="nofollow">psyco</a> to boost speed of many of the most intensive operations that a python script can perform, namely looping.</p>
1
2009-05-21T21:10:07Z
[ "python" ]