title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How can I print over the current line in a command line application?
465,348
<p>On Unix, I can either use \r (carriage return) or \b (backspace) to print over text already visible in the shell (i.e. overwrite the current line again).</p> <p>Can I achieve the same effect in a Windows command line from a Python script?</p> <p>I tried the curses module but it doesn't seem to be available on Windows.</p>
10
2009-01-21T13:43:17Z
465,360
<p>Look <a href="http://stackoverflow.com/questions/60221/how-to-animate-the-command-line">here</a></p> <p><a href="https://web.archive.org/web/20101025073658/http://adamv.com/dev/python/curses/" rel="nofollow">here</a> too for a curses library for python on windows...</p>
-3
2009-01-21T13:46:03Z
[ "python", "windows", "command-line" ]
How can I print over the current line in a command line application?
465,348
<p>On Unix, I can either use \r (carriage return) or \b (backspace) to print over text already visible in the shell (i.e. overwrite the current line again).</p> <p>Can I achieve the same effect in a Windows command line from a Python script?</p> <p>I tried the curses module but it doesn't seem to be available on Windows.</p>
10
2009-01-21T13:43:17Z
465,475
<p>yes:</p> <pre><code>import sys import time def restart_line(): sys.stdout.write('\r') sys.stdout.flush() sys.stdout.write('some data') sys.stdout.flush() time.sleep(2) # wait 2 seconds... restart_line() sys.stdout.write('other different data') sys.stdout.flush() </code></pre>
16
2009-01-21T14:15:10Z
[ "python", "windows", "command-line" ]
How can I print over the current line in a command line application?
465,348
<p>On Unix, I can either use \r (carriage return) or \b (backspace) to print over text already visible in the shell (i.e. overwrite the current line again).</p> <p>Can I achieve the same effect in a Windows command line from a Python script?</p> <p>I tried the curses module but it doesn't seem to be available on Windows.</p>
10
2009-01-21T13:43:17Z
467,659
<p>Simple way if you're just wanting to update the previous line:</p> <pre><code>import time for i in range(20): print str(i) + '\r', time.sleep(1) </code></pre>
1
2009-01-22T00:37:07Z
[ "python", "windows", "command-line" ]
How can I print over the current line in a command line application?
465,348
<p>On Unix, I can either use \r (carriage return) or \b (backspace) to print over text already visible in the shell (i.e. overwrite the current line again).</p> <p>Can I achieve the same effect in a Windows command line from a Python script?</p> <p>I tried the curses module but it doesn't seem to be available on Windows.</p>
10
2009-01-21T13:43:17Z
9,543,690
<p>On Windows (python 3), it seems to work (not using stdout directly):</p> <pre><code>import sys for i in reversed(range(0,20)): time.sleep(0.1) if(i == 19): print(str(i), end='', file=sys.stdout) else: print("\r{0:{width}".format(str(i), width = w, fill = ' ', align = 'right'), end='', file=sys.stdout) sys.stdout.flush() w = len(str(i)) </code></pre> <p>The same line is updated everytime print function is called.</p> <p>This algorithm can be improved, but it is posted to show what you can do. You can modify the method according to your needs.</p>
1
2012-03-03T05:13:01Z
[ "python", "windows", "command-line" ]
How can I print over the current line in a command line application?
465,348
<p>On Unix, I can either use \r (carriage return) or \b (backspace) to print over text already visible in the shell (i.e. overwrite the current line again).</p> <p>Can I achieve the same effect in a Windows command line from a Python script?</p> <p>I tried the curses module but it doesn't seem to be available on Windows.</p>
10
2009-01-21T13:43:17Z
21,672,188
<pre><code>import sys import time for i in range(10): print '\r', # print is Ok, and comma is needed. time.sleep(0.3) print i, sys.stdout.flush() # flush is needed. </code></pre> <p>And if on the IPython-notebook, just like this:</p> <pre><code>import time from IPython.display import clear_output for i in range(10): time.sleep(0.25) print(i) clear_output(wait=True) </code></pre> <p><a href="http://nbviewer.ipython.org/github/ipython/ipython/blob/master/examples/notebooks/Animations%20Using%20clear_output.ipynb" rel="nofollow">http://nbviewer.ipython.org/github/ipython/ipython/blob/master/examples/notebooks/Animations%20Using%20clear_output.ipynb</a></p>
7
2014-02-10T08:28:27Z
[ "python", "windows", "command-line" ]
How can I print over the current line in a command line application?
465,348
<p>On Unix, I can either use \r (carriage return) or \b (backspace) to print over text already visible in the shell (i.e. overwrite the current line again).</p> <p>Can I achieve the same effect in a Windows command line from a Python script?</p> <p>I tried the curses module but it doesn't seem to be available on Windows.</p>
10
2009-01-21T13:43:17Z
26,952,100
<p>I know this is old, but i wanted to tell my version (it works on my PC in the cmd, but not in the idle) to override a line in Python 3:</p> <pre><code>&gt;&gt;&gt; from time import sleep &gt;&gt;&gt; for i in range(400): &gt;&gt;&gt; print("\r" + str(i), end="") &gt;&gt;&gt; sleep(0.5) </code></pre> <p><strong>EDIT:</strong> It works on Windows and on Ubuntu</p>
2
2014-11-15T23:42:30Z
[ "python", "windows", "command-line" ]
How can I print over the current line in a command line application?
465,348
<p>On Unix, I can either use \r (carriage return) or \b (backspace) to print over text already visible in the shell (i.e. overwrite the current line again).</p> <p>Can I achieve the same effect in a Windows command line from a Python script?</p> <p>I tried the curses module but it doesn't seem to be available on Windows.</p>
10
2009-01-21T13:43:17Z
27,175,096
<p>I just had this problem. You can still use <code>\r</code>, even in Windows Command Prompt, however, it only takes you back to the previous linebreak (<code>\n</code>).</p> <p>If you do something like this:</p> <pre><code>cnt = 0 print str(cnt) while True: cnt += 1 print "\r" + str(cnt) </code></pre> <p>You'll get:</p> <pre><code>0 1 2 3 4 5 ... </code></pre> <p>That's because <code>\r</code> only goes back to the last line. Since you already wrote a newline character with the last print statement, your cursor goes from the beginning of a new empty line to the beginning of the same new empty line.</p> <p>To illustrate, after you print the first 0, your cursor would be here:</p> <pre><code>0 | # &lt;-- Cursor </code></pre> <p>When you <code>\r</code>, you go to the beginning of the line. But you're already on the beginning of the line.</p> <p>The fix is to avoid printing a <code>\n</code> character, so your cursor is on the same line and <code>\r</code> overwrites the text properly. You can do that with <code>print 'text',</code>. The comma prevents the printing of a newline character.</p> <pre><code>cnt = 0 print str(cnt), while True: cnt += 1 print "\r" + str(cnt), </code></pre> <p>Now it will properly rewrite lines.</p> <p>Note that this is Python 2.7, hence the <code>print</code> statements.</p>
3
2014-11-27T16:25:56Z
[ "python", "windows", "command-line" ]
How can I print over the current line in a command line application?
465,348
<p>On Unix, I can either use \r (carriage return) or \b (backspace) to print over text already visible in the shell (i.e. overwrite the current line again).</p> <p>Can I achieve the same effect in a Windows command line from a Python script?</p> <p>I tried the curses module but it doesn't seem to be available on Windows.</p>
10
2009-01-21T13:43:17Z
38,707,538
<p>easy method :)</p> <pre><code>import sys from time import sleep import os #print("\033[y coordinate;[x coordinateH Hello") os.system('cls') sleep(0.2) print("\033[1;1H[]") sleep(0.2) print("\033[1;1H []") sleep(0.2) print("\033[1;1H []") sleep(0.2) print("\033[1;1H []") sleep(0.2) print("\033[1;1H []") sleep(0.2) print("\033[1;1H []") sleep(0.2) print("\033[1;1H []") sleep(0.2) print("\033[1;1H []") sleep(0.2) print("\033[1;1H[]") sleep(0.2) </code></pre>
1
2016-08-01T20:27:20Z
[ "python", "windows", "command-line" ]
How do I take the output of one program and use it as the input of another?
465,421
<p>I've looked at <a href="http://stackoverflow.com/questions/316007/what-is-the-best-way-to-make-the-output-of-one-stream-the-input-to-another">this</a> and it wasn't much help.</p> <p>I have a Ruby program that puts a question to the cmd line and I would like to write a Python program that can return an answer. Does anyone know of any links or in general how I might go about doing this?</p> <p>Thanks for your help.</p> <p><b>EDIT</b> <br> Thanks to the guys that mentioned <i>piping</i>. I haven't used it too much and was glad it was brought up since it forced me too look in to it more.</p>
4
2009-01-21T14:01:11Z
465,438
<p>If you're on unix / linux you can use piping:</p> <pre><code>question.rb | answer.py </code></pre> <p>Then the output of question.rb becomes the input of answer.py</p> <p>I've not tried it recently, but I have a feeling the same syntax might work on Windows as well.</p>
4
2009-01-21T14:05:22Z
[ "python", "ruby", "io" ]
How do I take the output of one program and use it as the input of another?
465,421
<p>I've looked at <a href="http://stackoverflow.com/questions/316007/what-is-the-best-way-to-make-the-output-of-one-stream-the-input-to-another">this</a> and it wasn't much help.</p> <p>I have a Ruby program that puts a question to the cmd line and I would like to write a Python program that can return an answer. Does anyone know of any links or in general how I might go about doing this?</p> <p>Thanks for your help.</p> <p><b>EDIT</b> <br> Thanks to the guys that mentioned <i>piping</i>. I haven't used it too much and was glad it was brought up since it forced me too look in to it more.</p>
4
2009-01-21T14:01:11Z
465,454
<p>Pexpect</p> <p><a href="http://www.noah.org/wiki/Pexpect" rel="nofollow">http://www.noah.org/wiki/Pexpect</a></p> <blockquote> <p>Pexpect is a pure Python expect-like module. Pexpect makes Python a better tool for controlling other applications.</p> <p>Pexpect is a pure Python module for spawning child applications; controlling them; and responding to expected patterns in their output. Pexpect works like Don Libes' Expect. Pexpect allows your script to spawn a child application and control it as if a human were typing commands.</p> </blockquote>
3
2009-01-21T14:08:51Z
[ "python", "ruby", "io" ]
How do I take the output of one program and use it as the input of another?
465,421
<p>I've looked at <a href="http://stackoverflow.com/questions/316007/what-is-the-best-way-to-make-the-output-of-one-stream-the-input-to-another">this</a> and it wasn't much help.</p> <p>I have a Ruby program that puts a question to the cmd line and I would like to write a Python program that can return an answer. Does anyone know of any links or in general how I might go about doing this?</p> <p>Thanks for your help.</p> <p><b>EDIT</b> <br> Thanks to the guys that mentioned <i>piping</i>. I haven't used it too much and was glad it was brought up since it forced me too look in to it more.</p>
4
2009-01-21T14:01:11Z
465,455
<p>There are two ways (off the top of my head) to do this. The simplest if you're in a Unix environment is to use piping. Simple example:</p> <pre><code>cat .profile .shrc | more </code></pre> <p>This will send the output of the first command (<code>cat .profile .shrc</code>) to the <code>more</code> command using the pipe character <code>|</code>.</p> <p>The second way is to call one program from the other in your source code. I'm don't know how Ruby handles this, but in Python you can run a program and get it's output by using the popen function. See <a href="http://oreilly.com/catalog/lpython/chapter/ch09.html" rel="nofollow">this example chapter from Learning Python</a>, then Ctrl-F for "popen" for some example code.</p>
1
2009-01-21T14:08:57Z
[ "python", "ruby", "io" ]
How do I take the output of one program and use it as the input of another?
465,421
<p>I've looked at <a href="http://stackoverflow.com/questions/316007/what-is-the-best-way-to-make-the-output-of-one-stream-the-input-to-another">this</a> and it wasn't much help.</p> <p>I have a Ruby program that puts a question to the cmd line and I would like to write a Python program that can return an answer. Does anyone know of any links or in general how I might go about doing this?</p> <p>Thanks for your help.</p> <p><b>EDIT</b> <br> Thanks to the guys that mentioned <i>piping</i>. I haven't used it too much and was glad it was brought up since it forced me too look in to it more.</p>
4
2009-01-21T14:01:11Z
465,466
<pre><code>p = subprocess.Popen(['ruby', 'ruby_program.rb'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) ruby_question = p.stdout.readline() answer = calculate_answer(ruby_question) p.stdin.write(answer) print p.communicate()[0] # prints further info ruby may show. </code></pre> <p>The last 2 lines could be made into one:</p> <pre><code>print p.communicate(answer)[0] </code></pre>
10
2009-01-21T14:12:23Z
[ "python", "ruby", "io" ]
How do I take the output of one program and use it as the input of another?
465,421
<p>I've looked at <a href="http://stackoverflow.com/questions/316007/what-is-the-best-way-to-make-the-output-of-one-stream-the-input-to-another">this</a> and it wasn't much help.</p> <p>I have a Ruby program that puts a question to the cmd line and I would like to write a Python program that can return an answer. Does anyone know of any links or in general how I might go about doing this?</p> <p>Thanks for your help.</p> <p><b>EDIT</b> <br> Thanks to the guys that mentioned <i>piping</i>. I haven't used it too much and was glad it was brought up since it forced me too look in to it more.</p>
4
2009-01-21T14:01:11Z
465,468
<p>First of all check this out: [Unix piping][1]</p> <p>It works on windows or unix but it's slighly dufferent, first the programs:</p> <p>question.rb:</p> <pre><code>puts "This is the question" </code></pre> <p>answer.rb:</p> <pre><code>question = gets #calculate answer puts "This is the answer" </code></pre> <p>Then the command line: </p> <p>In unix:</p> <pre><code>question.rb | answer.rb </code></pre> <p>In windows:</p> <pre><code>ruby question.rb | ruby answer.rb </code></pre> <p>Output:</p> <pre><code>This is the question This is the answer </code></pre>
3
2009-01-21T14:12:50Z
[ "python", "ruby", "io" ]
How do I make IPython organize tab completion possibilities by class?
465,605
<p>When an object has hundreds of methods, tab completion is hard to use. More often than not the interesting methods are the ones defined or overridden by the inspected object's class and not its base classes.</p> <p>How can I get IPython to group its tab completion possibilities so the methods and properties defined in the inspected object's class come first, followed by those in base classes?</p> <p>It looks like the undocumented <code>inspect.classify_class_attrs(cls)</code> function along with <code>inspect.getmro(cls)</code> give me most of the information I need (these were originally written to implement python's <code>help(object)</code> feature).</p> <p>By default readline displays completions alphabetically, but the function used to display completions can be replaced with ctypes or the readline module included with Python 2.6 and above. I've overridden readline's completions display and it works great.</p> <p>Now all I need is a method to merge per-class information (from <code>inspect.*</code> per above) with per-instance information, sort the results by method resolution order, pretty print and paginate.</p> <p>For extra credit, it would be great to store the chosen autocompletion, and display the most popular choices first next time autocomplete is attempted on the same object.</p>
4
2009-01-21T14:50:32Z
467,430
<p>I don't think this can be accomplished easily. There's no mechanism in Ipython to perform it in any case.</p> <p>Initially I had thought you could modify Ipython's source to change the order (eg by changing the <code>dir2()</code> function in genutils.py). However it looks like readline alphabetically sorts the completions you pass to it, so this won't work (at least not without a <em>lot</em> more effort), though you could perhaps exclude methods on the base class completely.</p>
1
2009-01-21T23:06:42Z
[ "python", "readline", "ipython" ]
How do I make IPython organize tab completion possibilities by class?
465,605
<p>When an object has hundreds of methods, tab completion is hard to use. More often than not the interesting methods are the ones defined or overridden by the inspected object's class and not its base classes.</p> <p>How can I get IPython to group its tab completion possibilities so the methods and properties defined in the inspected object's class come first, followed by those in base classes?</p> <p>It looks like the undocumented <code>inspect.classify_class_attrs(cls)</code> function along with <code>inspect.getmro(cls)</code> give me most of the information I need (these were originally written to implement python's <code>help(object)</code> feature).</p> <p>By default readline displays completions alphabetically, but the function used to display completions can be replaced with ctypes or the readline module included with Python 2.6 and above. I've overridden readline's completions display and it works great.</p> <p>Now all I need is a method to merge per-class information (from <code>inspect.*</code> per above) with per-instance information, sort the results by method resolution order, pretty print and paginate.</p> <p>For extra credit, it would be great to store the chosen autocompletion, and display the most popular choices first next time autocomplete is attempted on the same object.</p>
4
2009-01-21T14:50:32Z
488,461
<p>It looks like I can use <code>readline.set_completion_display_matches_hook([function])</code> (new in Python 2.6) to display the results. The completer would return a list of possibilities as usual, but would also store the results of <code>inspect.classify_class_attrs(cls)</code> where applicable. The <code>completion_display_matches_hook</code> would have to hold a reference to the completer to retrieve the most recent list of completions plus the classification information I am looking for because only receives a list of match names in its arguments. Then the hook displays the list of completions in a pleasing way.</p>
1
2009-01-28T17:04:55Z
[ "python", "readline", "ipython" ]
How do I make IPython organize tab completion possibilities by class?
465,605
<p>When an object has hundreds of methods, tab completion is hard to use. More often than not the interesting methods are the ones defined or overridden by the inspected object's class and not its base classes.</p> <p>How can I get IPython to group its tab completion possibilities so the methods and properties defined in the inspected object's class come first, followed by those in base classes?</p> <p>It looks like the undocumented <code>inspect.classify_class_attrs(cls)</code> function along with <code>inspect.getmro(cls)</code> give me most of the information I need (these were originally written to implement python's <code>help(object)</code> feature).</p> <p>By default readline displays completions alphabetically, but the function used to display completions can be replaced with ctypes or the readline module included with Python 2.6 and above. I've overridden readline's completions display and it works great.</p> <p>Now all I need is a method to merge per-class information (from <code>inspect.*</code> per above) with per-instance information, sort the results by method resolution order, pretty print and paginate.</p> <p>For extra credit, it would be great to store the chosen autocompletion, and display the most popular choices first next time autocomplete is attempted on the same object.</p>
4
2009-01-21T14:50:32Z
492,328
<p>Since I am not using Python 2.6 or 3.0 yet and don't have <code>readline.set_completion_display_matches_hook()</code>, I can use ctypes to set <code>completion_display_func</code> like so:</p> <pre><code>from ctypes import * rl = cdll.LoadLibrary('libreadline.so') def completion_display_func(matches, num_matches, max_length): print "Hello from Python" for i in range(num_matches): print matches[i] COMPLETION_DISPLAY_FUNC = CFUNCTYPE(None, POINTER(c_char_p), c_int, c_int) hook = COMPLETION_DISPLAY_FUNC(completion_display_func) ptr = c_void_p.in_dll(rl, 'rl_completion_display_matches_hook') ptr.value = cast(hook, c_void_p).value </code></pre> <p>Now, when I press 'tab' to complete, my own function prints the list of completions. So that answers the question 'how do I change the way readline displays completions'.</p>
5
2009-01-29T16:22:23Z
[ "python", "readline", "ipython" ]
What is a simple way to generate keywords from a text?
465,795
<p>I suppose I could take a text and remove high frequency English words from it. By keywords, I mean that I want to extract words that are most the characterizing of the content of the text (tags ) . It doesn't have to be perfect, a good approximation is perfect for my needs.</p> <p>Has anyone done anything like that? Do you known a Perl or Python library that does that? </p> <p>Lingua::EN::Tagger is exactly what I asked however I needed a library that could work for french text too.</p>
17
2009-01-21T15:43:36Z
465,840
<p>The simplest way to do what you want is this...</p> <pre> >>> text = "this is some of the sample text" >>> words = [word for word in set(text.split(" ")) if len(word) > 3] >>> words ['this', 'some', 'sample', 'text'] </pre> <p>I don't know of any standard module that does this, but it wouldn't be hard to replace the limit on three letter words with a lookup into a set of common English words.</p>
3
2009-01-21T15:54:43Z
[ "python", "perl", "metadata" ]
What is a simple way to generate keywords from a text?
465,795
<p>I suppose I could take a text and remove high frequency English words from it. By keywords, I mean that I want to extract words that are most the characterizing of the content of the text (tags ) . It doesn't have to be perfect, a good approximation is perfect for my needs.</p> <p>Has anyone done anything like that? Do you known a Perl or Python library that does that? </p> <p>Lingua::EN::Tagger is exactly what I asked however I needed a library that could work for french text too.</p>
17
2009-01-21T15:43:36Z
465,909
<p>The name for the "high frequency English words" is <a href="http://en.wikipedia.org/wiki/Stop_words">stop words</a> and there are many lists available. I'm not aware of any python or perl libraries, but you could encode your stop word list in a binary tree or hash (or you could use python's frozenset), then as you read each word from the input text, check if it is in your 'stop list' and filter it out.</p> <p>Note that after you remove the stop words, you'll need to do some <a href="http://en.wikipedia.org/wiki/Stemming">stemming</a> to normalize the resulting text (remove plurals, -ings, -eds), then remove all the duplicate "keywords".</p>
16
2009-01-21T16:14:29Z
[ "python", "perl", "metadata" ]
What is a simple way to generate keywords from a text?
465,795
<p>I suppose I could take a text and remove high frequency English words from it. By keywords, I mean that I want to extract words that are most the characterizing of the content of the text (tags ) . It doesn't have to be perfect, a good approximation is perfect for my needs.</p> <p>Has anyone done anything like that? Do you known a Perl or Python library that does that? </p> <p>Lingua::EN::Tagger is exactly what I asked however I needed a library that could work for french text too.</p>
17
2009-01-21T15:43:36Z
466,013
<p>In Perl there's <a href="http://search.cpan.org/perldoc?Lingua::EN::Keywords" rel="nofollow">Lingua::EN::Keywords</a>.</p>
4
2009-01-21T16:40:40Z
[ "python", "perl", "metadata" ]
What is a simple way to generate keywords from a text?
465,795
<p>I suppose I could take a text and remove high frequency English words from it. By keywords, I mean that I want to extract words that are most the characterizing of the content of the text (tags ) . It doesn't have to be perfect, a good approximation is perfect for my needs.</p> <p>Has anyone done anything like that? Do you known a Perl or Python library that does that? </p> <p>Lingua::EN::Tagger is exactly what I asked however I needed a library that could work for french text too.</p>
17
2009-01-21T15:43:36Z
466,037
<p>You could try using the perl module <a href="http://search.cpan.org/~acoburn/Lingua-EN-Tagger-0.15/Tagger.pm">Lingua::EN::Tagger</a> for a quick and easy solution. </p> <p>A more complicated module <a href="http://code.google.com/p/lingua-en-semtags-engine/">Lingua::EN::Semtags::Engine</a> uses Lingua::EN::Tagger with a WordNet database to get a more structured output. Both are pretty easy to use, just check out the documentation on CPAN or use perldoc after you install the module.</p>
9
2009-01-21T16:44:49Z
[ "python", "perl", "metadata" ]
What is a simple way to generate keywords from a text?
465,795
<p>I suppose I could take a text and remove high frequency English words from it. By keywords, I mean that I want to extract words that are most the characterizing of the content of the text (tags ) . It doesn't have to be perfect, a good approximation is perfect for my needs.</p> <p>Has anyone done anything like that? Do you known a Perl or Python library that does that? </p> <p>Lingua::EN::Tagger is exactly what I asked however I needed a library that could work for french text too.</p>
17
2009-01-21T15:43:36Z
466,304
<p>To find the most frequently-used words in a text, do something like this:</p> <pre><code>#!/usr/bin/perl -w use strict; use warnings 'all'; # Read the text: open my $ifh, '&lt;', 'text.txt' or die "Cannot open file: $!"; local $/; my $text = &lt;$ifh&gt;; # Find all the words, and count how many times they appear: my %words = ( ); map { $words{$_}++ } grep { length &gt; 1 &amp;&amp; $_ =~ m/^[\@a-z-']+$/i } map { s/[",\.]//g; $_ } split /\s/, $text; print "Words, sorted by frequency:\n"; my (@data_line); format FMT = @&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;... @######## @data_line . local $~ = 'FMT'; # Sort them by frequency: map { @data_line = ($_, $words{$_}); write(); } sort { $words{$b} &lt;=&gt; $words{$a} } grep { $words{$_} &gt; 2 } keys(%words); </code></pre> <p>Example output looks like this:</p> <pre><code>john@ubuntu-pc1:~/Desktop$ perl frequency.pl Words, sorted by frequency: for 32 Jan 27 am 26 of 21 your 21 to 18 in 17 the 17 Get 13 you 13 OTRS 11 today 11 PSM 10 Card 10 me 9 on 9 and 9 Offline 9 with 9 Invited 9 Black 8 get 8 Web 7 Starred 7 All 7 View 7 Obama 7 </code></pre>
4
2009-01-21T17:47:07Z
[ "python", "perl", "metadata" ]
What is a simple way to generate keywords from a text?
465,795
<p>I suppose I could take a text and remove high frequency English words from it. By keywords, I mean that I want to extract words that are most the characterizing of the content of the text (tags ) . It doesn't have to be perfect, a good approximation is perfect for my needs.</p> <p>Has anyone done anything like that? Do you known a Perl or Python library that does that? </p> <p>Lingua::EN::Tagger is exactly what I asked however I needed a library that could work for french text too.</p>
17
2009-01-21T15:43:36Z
469,359
<p>One liner solution (words longer than two chars which occurred more than two times):</p> <pre><code>perl -ne'$h{$1}++while m/\b(\w{3,})\b/g}{printf"%-20s %5d\n",$_,$h{$_}for sort{$h{$b}&lt;=&gt;$h{$a}}grep{$h{$_}&gt;2}keys%h' </code></pre> <p><strong>EDIT:</strong> If one wants to sort alphabetically words with same frequency can use this enhanced one:</p> <pre><code>perl -ne'$h{$1}++while m/\b(\w{3,})\b/g}{printf"%-20s %5d\n",$_,$h{$_}for sort{$h{$b}&lt;=&gt;$h{$a}or$a cmp$b}grep{$h{$_}&gt;2}keys%h' </code></pre>
2
2009-01-22T14:36:23Z
[ "python", "perl", "metadata" ]
What is a simple way to generate keywords from a text?
465,795
<p>I suppose I could take a text and remove high frequency English words from it. By keywords, I mean that I want to extract words that are most the characterizing of the content of the text (tags ) . It doesn't have to be perfect, a good approximation is perfect for my needs.</p> <p>Has anyone done anything like that? Do you known a Perl or Python library that does that? </p> <p>Lingua::EN::Tagger is exactly what I asked however I needed a library that could work for french text too.</p>
17
2009-01-21T15:43:36Z
469,690
<p>I think the most accurate way that still maintains a semblance of simplicity would be to count the word frequencies in your source, then weight them according to their frequencies in common English (or whatever other language) usage. </p> <p>Words that appear less frequently in common use, like "coffeehouse" are more likely to be a keyword than words that appear more often, like "dog." Still, if your source mentions "dog" 500 times and "coffeehouse" twice it's more likely that "dog" is a keyword even though it's a common word.</p> <p>Deciding on the weighting scheme would be the difficult part.</p>
0
2009-01-22T15:54:08Z
[ "python", "perl", "metadata" ]
What is a simple way to generate keywords from a text?
465,795
<p>I suppose I could take a text and remove high frequency English words from it. By keywords, I mean that I want to extract words that are most the characterizing of the content of the text (tags ) . It doesn't have to be perfect, a good approximation is perfect for my needs.</p> <p>Has anyone done anything like that? Do you known a Perl or Python library that does that? </p> <p>Lingua::EN::Tagger is exactly what I asked however I needed a library that could work for french text too.</p>
17
2009-01-21T15:43:36Z
20,750,315
<p>TF-IDF (Term Frequency - Inverse Document Frequency) is designed for this. </p> <p>Basically it asks, which words are frequent in this document, compared to all documents?</p> <p>It will give a lower score to words that appear in all documents, and a higher score to words that appear in a given document frequently.</p> <p>You can see a worksheet of the calculations here:</p> <p><a href="https://docs.google.com/spreadsheet/ccc?key=0AreO9JhY28gcdFMtUFJrc0dRdkpiUWlhNHVGS1h5Y2c&amp;usp=sharing" rel="nofollow">https://docs.google.com/spreadsheet/ccc?key=0AreO9JhY28gcdFMtUFJrc0dRdkpiUWlhNHVGS1h5Y2c&amp;usp=sharing</a></p> <p>(switch to TFIDF tab at bottom)</p> <p>Here is a python library:</p> <p><a href="https://github.com/hrs/python-tf-idf" rel="nofollow">https://github.com/hrs/python-tf-idf</a></p>
0
2013-12-23T19:58:21Z
[ "python", "perl", "metadata" ]
Delphi-like GUI designer for Python
465,814
<p>Is there any GUI toolkit for Python with form designer similar to Delphi, eg where one can drag and drop controls to form, move them around etc.</p>
7
2009-01-21T15:47:39Z
465,864
<p>I recommend <a href="http://www.riverbankcomputing.co.uk/software/pyqt/intro" rel="nofollow">PyQt</a> (now from Nokia), which uses <a href="http://www.qtsoftware.com/products/appdev/developer-tools/developer-tools?currentflipperobject=73543fa58dda72c632a376b97104ff78" rel="nofollow">Qt Designer</a>. Qt designer produces XML files (.ui) which you can either convert to Python modules using a utility called <code>pyuic</code>, or load dynamically from your Python program.</p> <p>You <em>do</em> have to write your Python code in a different editor, i.e. Designer is only the GUI designer part and not a complete IDE. They have an IDE in beta called Qt Creator, but I don't think it supports Python very well at this stage.</p> <p>If you'd rather go with <a href="http://www.wxpython.org/" rel="nofollow">wxPython</a>, <a href="http://wxglade.sourceforge.net/" rel="nofollow">wxGlade</a> will output Python code.</p>
4
2009-01-21T16:02:16Z
[ "python", "user-interface", "form-designer" ]
Delphi-like GUI designer for Python
465,814
<p>Is there any GUI toolkit for Python with form designer similar to Delphi, eg where one can drag and drop controls to form, move them around etc.</p>
7
2009-01-21T15:47:39Z
465,929
<p>Use Glade + PyGTk to do GUI programming in Python. Glade is a tool which allows you to create graphical interfaces by dragging and dropping widgets. In turn Glade generates the interface definition in XML which you can hook up with your code using libglade. Check the website of <a href="http://glade.gnome.org/" rel="nofollow">Glade</a> for more info. </p>
2
2009-01-21T16:20:28Z
[ "python", "user-interface", "form-designer" ]
Delphi-like GUI designer for Python
465,814
<p>Is there any GUI toolkit for Python with form designer similar to Delphi, eg where one can drag and drop controls to form, move them around etc.</p>
7
2009-01-21T15:47:39Z
465,930
<p>If your using wxPython check out <a href="http://boa-constructor.sourceforge.net/" rel="nofollow">BoaConstructor</a>, it is a complete Python IDE with a GUI designer.</p>
2
2009-01-21T16:21:20Z
[ "python", "user-interface", "form-designer" ]
How to make a model instance read-only after saving it once?
466,135
<p>One of the functionalities in a Django project I am writing is sending a newsletter. I have a model, <code>Newsletter</code> and a function, <code>send_newsletter</code>, which I have registered to listen to <code>Newsletter</code>'s <code>post_save</code> signal. When the newsletter object is saved via the admin interface, <code>send_newsletter</code> checks if <code>created</code> is True, and if yes it actually sends the mail.</p> <p>However, it doesn't make much sense to edit a newsletter that has already been sent, for the obvious reasons. Is there a way of making the <code>Newsletter</code> object read-only once it has been saved?</p> <h2>Edit:</h2> <p>I know I can override the <code>save</code> method of the object to raise an error or do nothin if the object existed. However, I don't see the point of doing that. As for the former, I don't know where to catch that error and how to communicate the user the fact that the object wasn't saved. As for the latter, giving the user false feedback (the admin interface saying that the save succeded) doesn't seem like a Good Thing.</p> <p>What I really want is allow the user to use the Admin interface to write the newsletter and send it, and then browse the newsletters that have already been sent. I would like the admin interface to show the data for sent newsletters in an non-editable input box, without the "Save" button. Alternatively I would like the "Save" button to be inactive.</p>
3
2009-01-21T17:11:14Z
466,641
<p>You can check if it is creation or update in the model's <code>save</code> method:</p> <pre><code>def save(self, *args, **kwargs): if self.pk: raise StandardError('Can\'t modify bla bla bla.') super(Payment, self).save(*args, **kwargs) </code></pre> <p>Code above will raise an exception if you try to save an existing object. <strong>Objects not previously persisted don't have their primary keys set.</strong></p>
7
2009-01-21T19:29:25Z
[ "python", "django", "django-models", "django-admin", "django-signals" ]
How to make a model instance read-only after saving it once?
466,135
<p>One of the functionalities in a Django project I am writing is sending a newsletter. I have a model, <code>Newsletter</code> and a function, <code>send_newsletter</code>, which I have registered to listen to <code>Newsletter</code>'s <code>post_save</code> signal. When the newsletter object is saved via the admin interface, <code>send_newsletter</code> checks if <code>created</code> is True, and if yes it actually sends the mail.</p> <p>However, it doesn't make much sense to edit a newsletter that has already been sent, for the obvious reasons. Is there a way of making the <code>Newsletter</code> object read-only once it has been saved?</p> <h2>Edit:</h2> <p>I know I can override the <code>save</code> method of the object to raise an error or do nothin if the object existed. However, I don't see the point of doing that. As for the former, I don't know where to catch that error and how to communicate the user the fact that the object wasn't saved. As for the latter, giving the user false feedback (the admin interface saying that the save succeded) doesn't seem like a Good Thing.</p> <p>What I really want is allow the user to use the Admin interface to write the newsletter and send it, and then browse the newsletters that have already been sent. I would like the admin interface to show the data for sent newsletters in an non-editable input box, without the "Save" button. Alternatively I would like the "Save" button to be inactive.</p>
3
2009-01-21T17:11:14Z
531,541
<p>Suggested reading: The Zen of Admin in <a href="http://www.djangobook.com/en/1.0/chapter17/" rel="nofollow">chapter 17 of the Django Book</a>.</p> <p>Summary: The admin is not designed for what you're trying to do :(</p> <p>However, the 1.0 version of the book covers only Django 0.96, and good things have happened since.</p> <p>In Django 1.0, the <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/" rel="nofollow">admin site</a> is more customizable. Since I haven't customized admin myself, I'll have to guess based on the docs, but I'd say <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#form" rel="nofollow">overriding the model form</a> is your best bet.</p>
1
2009-02-10T08:57:23Z
[ "python", "django", "django-models", "django-admin", "django-signals" ]
How to make a model instance read-only after saving it once?
466,135
<p>One of the functionalities in a Django project I am writing is sending a newsletter. I have a model, <code>Newsletter</code> and a function, <code>send_newsletter</code>, which I have registered to listen to <code>Newsletter</code>'s <code>post_save</code> signal. When the newsletter object is saved via the admin interface, <code>send_newsletter</code> checks if <code>created</code> is True, and if yes it actually sends the mail.</p> <p>However, it doesn't make much sense to edit a newsletter that has already been sent, for the obvious reasons. Is there a way of making the <code>Newsletter</code> object read-only once it has been saved?</p> <h2>Edit:</h2> <p>I know I can override the <code>save</code> method of the object to raise an error or do nothin if the object existed. However, I don't see the point of doing that. As for the former, I don't know where to catch that error and how to communicate the user the fact that the object wasn't saved. As for the latter, giving the user false feedback (the admin interface saying that the save succeded) doesn't seem like a Good Thing.</p> <p>What I really want is allow the user to use the Admin interface to write the newsletter and send it, and then browse the newsletters that have already been sent. I would like the admin interface to show the data for sent newsletters in an non-editable input box, without the "Save" button. Alternatively I would like the "Save" button to be inactive.</p>
3
2009-01-21T17:11:14Z
2,477,830
<p>use readonlyadmin in ur amdin.py.List all the fields which u want to make readonly.After creating the object u canot edit them then</p> <p>use the link</p> <pre><code>http://www.djangosnippets.org/snippets/937/ </code></pre> <p>copy the file and then import in ur admin.py and used it</p>
0
2010-03-19T14:00:41Z
[ "python", "django", "django-models", "django-admin", "django-signals" ]
How to make a model instance read-only after saving it once?
466,135
<p>One of the functionalities in a Django project I am writing is sending a newsletter. I have a model, <code>Newsletter</code> and a function, <code>send_newsletter</code>, which I have registered to listen to <code>Newsletter</code>'s <code>post_save</code> signal. When the newsletter object is saved via the admin interface, <code>send_newsletter</code> checks if <code>created</code> is True, and if yes it actually sends the mail.</p> <p>However, it doesn't make much sense to edit a newsletter that has already been sent, for the obvious reasons. Is there a way of making the <code>Newsletter</code> object read-only once it has been saved?</p> <h2>Edit:</h2> <p>I know I can override the <code>save</code> method of the object to raise an error or do nothin if the object existed. However, I don't see the point of doing that. As for the former, I don't know where to catch that error and how to communicate the user the fact that the object wasn't saved. As for the latter, giving the user false feedback (the admin interface saying that the save succeded) doesn't seem like a Good Thing.</p> <p>What I really want is allow the user to use the Admin interface to write the newsletter and send it, and then browse the newsletters that have already been sent. I would like the admin interface to show the data for sent newsletters in an non-editable input box, without the "Save" button. Alternatively I would like the "Save" button to be inactive.</p>
3
2009-01-21T17:11:14Z
21,147,017
<p>What you can easily do, is making all fields readonly:</p> <pre><code>class MyModelAdmin(ModelAdmin): form = ... def get_readonly_fields(self, request, obj=None): if obj: return MyModelAdmin.form.Meta.fields else: # This is an addition return [] </code></pre> <p>As for making the Save disappear, it would be much easier if</p> <ol> <li><code>has_change_permission</code> returning False wouldnt disable even displaying the form</li> <li>the code snippet responsible for rendering the admin form controls (the <code>admin_modify.submit_row</code> templatetag), wouldnt use <code>show_save=True</code> unconditionally.</li> </ol> <p>Anyways, one way of making that guy not to be rendered :</p> <ol> <li><p>Create an alternate version of has_change_permission, with proper logic:</p> <pre><code>class NoSaveModelAdminMixin(object): def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None): response = super(NoSaveModelAdmin, self).render_change_form(request, context, add, change,form_url, obj) response.context_data["has_change_permission"] = self.has_real_change_permission(request, obj) def has_real_change_permission(self, request, obj): return obj==None def change_view(self, request, object_id, extra_context=None): obj = self.get_object(request, unquote(object_id)) if not self.has_real_change_permission(request, obj) and request.method == 'POST': raise PermissionDenied return super(NoSaveModelAdmin, self).change_view(request, object_id, extra_context=extra_context) </code></pre></li> <li><p>Override the submit_row templatetag similar to this:</p> <pre><code>@admin_modify.register.inclusion_tag('admin/submit_line.html', takes_context=True) def submit_row(context): ... 'show_save': context['has_change_permission'] ... admin_modify.submit_row = submit_row </code></pre></li> </ol>
0
2014-01-15T19:58:53Z
[ "python", "django", "django-models", "django-admin", "django-signals" ]
How can I hide the console window in a PyQt app running on Windows?
466,203
<p>Surely this is possible? I have been hunting through PyQt tutorials and documentation but cannot find the answer to it. Probably I just need to phrase my search query differently.</p> <p>[Edit]</p> <p>Thanks PEZ for the answer - more details including use of the <code>.pyw</code> extension in <a href="http://www.onlamp.com/pub/a/python/excerpts/chpt20/index.html?page=2">Python Programming on Win32 chapter 20</a></p>
12
2009-01-21T17:25:38Z
466,222
<p>I think you should be able to run your app with pythonw.exe.</p>
17
2009-01-21T17:28:34Z
[ "python", "windows", "command-line", "pyqt" ]
How can I hide the console window in a PyQt app running on Windows?
466,203
<p>Surely this is possible? I have been hunting through PyQt tutorials and documentation but cannot find the answer to it. Probably I just need to phrase my search query differently.</p> <p>[Edit]</p> <p>Thanks PEZ for the answer - more details including use of the <code>.pyw</code> extension in <a href="http://www.onlamp.com/pub/a/python/excerpts/chpt20/index.html?page=2">Python Programming on Win32 chapter 20</a></p>
12
2009-01-21T17:25:38Z
466,279
<p>An easy way to do this is to give your script a .pyw extension instead of the usual .py.</p> <p>This has the same effect as PEZ's answer (runs the script using pythonw.exe).</p>
14
2009-01-21T17:39:19Z
[ "python", "windows", "command-line", "pyqt" ]
How can I generate multi-line build commands?
466,293
<p>In SCons, my command generators create ridiculously long command lines. I'd like to be able to split these commands across multiple lines for readability in the build log.</p> <p>e.g. I have a SConscipt like:</p> <pre><code>import os # create dependency def my_cmd_generator(source, target, env, for_signature): return r'''echo its a small world after all \ its a small world after all''' my_cmd_builder = Builder(generator=my_cmd_generator, suffix = '.foo') env = Environment() env.Append( BUILDERS = {'MyCmd' : my_cmd_builder } ) my_cmd = env.MyCmd('foo.foo',os.popen('which bash').read().strip()) AlwaysBuild(my_cmd) </code></pre> <p>When it executes, I get:</p> <pre><code>scons: Reading SConscript files ... scons: done reading SConscript files. scons: Building targets ... echo its a small world after all \ its a small world after all its a small world after all sh: line 1: its: command not found scons: *** [foo.foo] Error 127 scons: building terminated because of errors. </code></pre> <p>Doing this in the python shell with os.system and os.popen works -- I get a readable command string and the sub-shell process interprets all the lines as one command.</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; cmd = r'''echo its a small world after all \ ... its a small world after all''' &gt;&gt;&gt; print cmd echo its a small world after all \ its a small world after all &gt;&gt;&gt; os.system( cmd) its a small world after all its a small world after all 0 </code></pre> <p>When I do this in SCons, it executes each line one at a time, which is not what I want.</p> <p>I also want to avoid building up my commands into a shell-script and then executing the shell script, because that will create string escaping madness.</p> <p>Is this possible?</p> <p>UPDATE:<BR> cournape,<BR> Thanks for the clue about the $CCCOMSTR. Unfortunately, I'm not using any of the languages that SCons supports out of the box, so I'm creating my own command generator. Using a generator, how can I get SCons to do:</p> <pre><code>echo its a small world after all its a small world after all' </code></pre> <p>but print</p> <pre><code>echo its a small world after all \ its a small world after all </code></pre> <p>?</p>
3
2009-01-21T17:44:04Z
510,842
<p>You are mixing two totally different things: the command to be executed, and its representation in the command line. By default, scons prints the command line, but if you split the command line, you are changing the commands executed.</p> <p>Now, scons has a mechanism to change the printed commands. They are registered per Action instances, and many default ones are available:</p> <pre><code>env = Environment() env['CCCOMSTR'] = "CC $SOURCE" env['CXXCOMSTR'] = "CXX $SOURCE" env['LINKCOM'] = "LINK $SOURCE" </code></pre> <p>Will print, assuming only C and CXX sources:</p> <pre><code>CC foo.c CC bla.c CXX yo.cc LINK yo.o bla.o foo.o </code></pre>
1
2009-02-04T10:49:13Z
[ "python", "build", "build-automation", "scons" ]
How can I generate multi-line build commands?
466,293
<p>In SCons, my command generators create ridiculously long command lines. I'd like to be able to split these commands across multiple lines for readability in the build log.</p> <p>e.g. I have a SConscipt like:</p> <pre><code>import os # create dependency def my_cmd_generator(source, target, env, for_signature): return r'''echo its a small world after all \ its a small world after all''' my_cmd_builder = Builder(generator=my_cmd_generator, suffix = '.foo') env = Environment() env.Append( BUILDERS = {'MyCmd' : my_cmd_builder } ) my_cmd = env.MyCmd('foo.foo',os.popen('which bash').read().strip()) AlwaysBuild(my_cmd) </code></pre> <p>When it executes, I get:</p> <pre><code>scons: Reading SConscript files ... scons: done reading SConscript files. scons: Building targets ... echo its a small world after all \ its a small world after all its a small world after all sh: line 1: its: command not found scons: *** [foo.foo] Error 127 scons: building terminated because of errors. </code></pre> <p>Doing this in the python shell with os.system and os.popen works -- I get a readable command string and the sub-shell process interprets all the lines as one command.</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; cmd = r'''echo its a small world after all \ ... its a small world after all''' &gt;&gt;&gt; print cmd echo its a small world after all \ its a small world after all &gt;&gt;&gt; os.system( cmd) its a small world after all its a small world after all 0 </code></pre> <p>When I do this in SCons, it executes each line one at a time, which is not what I want.</p> <p>I also want to avoid building up my commands into a shell-script and then executing the shell script, because that will create string escaping madness.</p> <p>Is this possible?</p> <p>UPDATE:<BR> cournape,<BR> Thanks for the clue about the $CCCOMSTR. Unfortunately, I'm not using any of the languages that SCons supports out of the box, so I'm creating my own command generator. Using a generator, how can I get SCons to do:</p> <pre><code>echo its a small world after all its a small world after all' </code></pre> <p>but print</p> <pre><code>echo its a small world after all \ its a small world after all </code></pre> <p>?</p>
3
2009-01-21T17:44:04Z
521,783
<p>Thanks to cournape's tip about Actions versus Generators ( and eclipse pydev debugger), I've finally figured out what I need to do. You want to pass in your function to the 'Builder' class as an 'action' not a 'generator'. This will allow you to actually execute the os.system or os.popen call directly. Here's the updated code:</p> <pre><code>import os def my_action(source, target, env): cmd = r'''echo its a small world after all \ its a small world after all''' print cmd return os.system(cmd) my_cmd_builder = Builder( action=my_action, # &lt;-- CRUCIAL PIECE OF SOLUTION suffix = '.foo') env = Environment() env.Append( BUILDERS = {'MyCmd' : my_cmd_builder } ) my_cmd = env.MyCmd('foo.foo',os.popen('which bash').read().strip()) </code></pre> <p>This SConstruct file will produce the following output:</p> <pre><code>scons: Reading SConscript files ... scons: done reading SConscript files. scons: Building targets ... my_action(["foo.foo"], ["/bin/bash"]) echo its a small world after all \ its a small world after all its a small world after all its a small world after all scons: done building targets. </code></pre> <p>The other crucial piece is to remember that switching from a 'generator' to an 'action' means the target you're building no longer has an implicit dependency on the actual string that you are passing to the sub-process shell. You can re-create this dependency by adding the string into your environment. </p> <p>e.g., the solution that I personally want looks like:</p> <pre><code>import os cmd = r'''echo its a small world after all \ its a small world after all''' def my_action(source, target, env): print cmd return os.system(cmd) my_cmd_builder = Builder( action=my_action, suffix = '.foo') env = Environment() env['_MY_CMD'] = cmd # &lt;-- CREATE IMPLICIT DEPENDENCY ON CMD STRING env.Append( BUILDERS = {'MyCmd' : my_cmd_builder } ) my_cmd = env.MyCmd('foo.foo',os.popen('which bash').read().strip()) </code></pre>
3
2009-02-06T19:24:02Z
[ "python", "build", "build-automation", "scons" ]
Converting string into datetime
466,345
<p>Short and simple. I've got a huge list of date-times like this as strings:</p> <pre><code>Jun 1 2005 1:33PM Aug 28 1999 12:00AM </code></pre> <p>I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects. </p> <p>Any help (even if it's just a kick in the right direction) would be appreciated.</p> <p>Edit: This is going through Django's ORM so I can't use SQL to do the conversion on insert.</p>
826
2009-01-21T18:00:29Z
466,366
<p>Check out <a href="http://docs.python.org/2/library/time.html#time.strptime">strptime</a> in the <a href="http://docs.python.org/2/library/time.html">time</a> module. It is the inverse of <a href="http://docs.python.org/2/library/time.html#time.strftime">strftime</a>.</p>
433
2009-01-21T18:07:17Z
[ "python", "datetime" ]
Converting string into datetime
466,345
<p>Short and simple. I've got a huge list of date-times like this as strings:</p> <pre><code>Jun 1 2005 1:33PM Aug 28 1999 12:00AM </code></pre> <p>I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects. </p> <p>Any help (even if it's just a kick in the right direction) would be appreciated.</p> <p>Edit: This is going through Django's ORM so I can't use SQL to do the conversion on insert.</p>
826
2009-01-21T18:00:29Z
466,376
<pre><code>from datetime import datetime date_object = datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p') </code></pre> <p><a href="https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime">Link to the Python documentation for strptime</a></p> <p><a href="https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior">and a link for the strftime format mask</a></p> <p><a href="http://strftime.org/">This is also a really nice reference for stftime</a></p>
1,383
2009-01-21T18:08:52Z
[ "python", "datetime" ]
Converting string into datetime
466,345
<p>Short and simple. I've got a huge list of date-times like this as strings:</p> <pre><code>Jun 1 2005 1:33PM Aug 28 1999 12:00AM </code></pre> <p>I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects. </p> <p>Any help (even if it's just a kick in the right direction) would be appreciated.</p> <p>Edit: This is going through Django's ORM so I can't use SQL to do the conversion on insert.</p>
826
2009-01-21T18:00:29Z
470,303
<p>Use the third party <a href="http://labix.org/python-dateutil">dateutil</a> library:</p> <pre><code>from dateutil import parser dt = parser.parse("Aug 28 1999 12:00AM") </code></pre> <p>It can handle most date formats, including the one you need to parse. It's more convenient than strptime as it can guess the correct format most of the time.</p> <p>It very useful for writing tests, where readability is more important than performance.</p> <p>You can install it with:</p> <pre><code>pip install python-dateutil </code></pre>
399
2009-01-22T18:27:18Z
[ "python", "datetime" ]
Converting string into datetime
466,345
<p>Short and simple. I've got a huge list of date-times like this as strings:</p> <pre><code>Jun 1 2005 1:33PM Aug 28 1999 12:00AM </code></pre> <p>I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects. </p> <p>Any help (even if it's just a kick in the right direction) would be appreciated.</p> <p>Edit: This is going through Django's ORM so I can't use SQL to do the conversion on insert.</p>
826
2009-01-21T18:00:29Z
7,761,860
<p>Something that isn't mentioned here and is useful: adding a suffix to the day. I decoupled the suffix logic so you can use it for any number you like, not just dates.</p> <pre><code>import time def num_suffix(n): ''' Returns the suffix for any given int ''' suf = ('th','st', 'nd', 'rd') n = abs(n) # wise guy tens = int(str(n)[-2:]) units = n % 10 if tens &gt; 10 and tens &lt; 20: return suf[0] # teens with 'th' elif units &lt;= 3: return suf[units] else: return suf[0] # 'th' def day_suffix(t): ''' Returns the suffix of the given struct_time day ''' return num_suffix(t.tm_mday) # Examples print num_suffix(123) print num_suffix(3431) print num_suffix(1234) print '' print day_suffix(time.strptime("1 Dec 00", "%d %b %y")) print day_suffix(time.strptime("2 Nov 01", "%d %b %y")) print day_suffix(time.strptime("3 Oct 02", "%d %b %y")) print day_suffix(time.strptime("4 Sep 03", "%d %b %y")) print day_suffix(time.strptime("13 Nov 90", "%d %b %y")) print day_suffix(time.strptime("14 Oct 10", "%d %b %y"))​​​​​​​ </code></pre>
17
2011-10-14T00:13:28Z
[ "python", "datetime" ]
Converting string into datetime
466,345
<p>Short and simple. I've got a huge list of date-times like this as strings:</p> <pre><code>Jun 1 2005 1:33PM Aug 28 1999 12:00AM </code></pre> <p>I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects. </p> <p>Any help (even if it's just a kick in the right direction) would be appreciated.</p> <p>Edit: This is going through Django's ORM so I can't use SQL to do the conversion on insert.</p>
826
2009-01-21T18:00:29Z
22,128,786
<p>I have put together a project that can convert some really neat expressions. Check out <strong><a href="http://github.com/stevepeak/timestring">timestring</a></strong>. </p> <h2>Here are some examples below:</h2> <a href="http://github.com/stevepeak/timestring"><code>pip install timestring</code></a> <pre><code>&gt;&gt;&gt; import timestring &gt;&gt;&gt; timestring.Range('next week') &lt;timestring.Range From 03/03/14 00:00:00 to 03/10/14 00:00:00 4496004880&gt; &gt;&gt;&gt; timestring.Date('monday, aug 15th 2015 at 8:40 pm') &lt;timestring.Date 2015-08-15 20:40:00 4491909392&gt; </code></pre>
50
2014-03-02T14:22:44Z
[ "python", "datetime" ]
Converting string into datetime
466,345
<p>Short and simple. I've got a huge list of date-times like this as strings:</p> <pre><code>Jun 1 2005 1:33PM Aug 28 1999 12:00AM </code></pre> <p>I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects. </p> <p>Any help (even if it's just a kick in the right direction) would be appreciated.</p> <p>Edit: This is going through Django's ORM so I can't use SQL to do the conversion on insert.</p>
826
2009-01-21T18:00:29Z
22,223,725
<p>Many timestamps have an implied timezone. To ensure that your code will work in every timezone, you should use UTC internally and attach a timezone each time a foreign object enters the system.</p> <p>Python 3.2+:</p> <pre><code>&gt;&gt;&gt; datetime.datetime.strptime( ... "March 5, 2014, 20:13:50", "%B %d, %Y, %H:%M:%S" ... ).replace(tzinfo=datetime.timezone(datetime.timedelta(hours=-3))) </code></pre>
24
2014-03-06T11:53:05Z
[ "python", "datetime" ]
Converting string into datetime
466,345
<p>Short and simple. I've got a huge list of date-times like this as strings:</p> <pre><code>Jun 1 2005 1:33PM Aug 28 1999 12:00AM </code></pre> <p>I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects. </p> <p>Any help (even if it's just a kick in the right direction) would be appreciated.</p> <p>Edit: This is going through Django's ORM so I can't use SQL to do the conversion on insert.</p>
826
2009-01-21T18:00:29Z
27,046,382
<p>Django Timezone aware datetime object example.</p> <pre><code>import datetime from django.utils.timezone import get_current_timezone tz = get_current_timezone() format = '%b %d %Y %I:%M%p' date_object = datetime.datetime.strptime('Jun 1 2005 1:33PM', format) date_obj = tz.localize(date_object) </code></pre> <p>This conversion is very important for Django and Python when you have <code>USE_TZ = True</code>:</p> <pre><code>RuntimeWarning: DateTimeField MyModel.created received a naive datetime (2016-03-04 00:00:00) while time zone support is active. </code></pre>
4
2014-11-20T17:58:01Z
[ "python", "datetime" ]
Converting string into datetime
466,345
<p>Short and simple. I've got a huge list of date-times like this as strings:</p> <pre><code>Jun 1 2005 1:33PM Aug 28 1999 12:00AM </code></pre> <p>I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects. </p> <p>Any help (even if it's just a kick in the right direction) would be appreciated.</p> <p>Edit: This is going through Django's ORM so I can't use SQL to do the conversion on insert.</p>
826
2009-01-21T18:00:29Z
27,401,685
<p>You string representation of datetime is</p> <p><code>Jun 1 2005 1:33PM</code></p> <p>which is equals to</p> <p><code>%b %d %Y %I:%M%p</code></p> <blockquote> <p>%b Month as locale’s abbreviated name(Jun)</p> <p>%d Day of the month as a zero-padded decimal number(1)</p> <p>%Y Year with century as a decimal number(2015)</p> <p>%I Hour (12-hour clock) as a zero-padded decimal number(01)</p> <p>%M Minute as a zero-padded decimal number(33)</p> <p>%p Locale’s equivalent of either AM or PM(PM)</p> </blockquote> <pre><code>&gt;&gt;&gt; dates = [] &gt;&gt;&gt; dates.append('Jun 1 2005 1:33PM') &gt;&gt;&gt; dates.append('Aug 28 1999 12:00AM') &gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; for d in dates: ... date = datetime.strptime(d, '%b %d %Y %I:%M%p') ... print type(date) ... print date ... </code></pre> <p>Output</p> <pre><code>&lt;type 'datetime.datetime'&gt; 2005-06-01 13:33:00 &lt;type 'datetime.datetime'&gt; 1999-08-28 00:00:00 </code></pre>
14
2014-12-10T13:00:49Z
[ "python", "datetime" ]
Converting string into datetime
466,345
<p>Short and simple. I've got a huge list of date-times like this as strings:</p> <pre><code>Jun 1 2005 1:33PM Aug 28 1999 12:00AM </code></pre> <p>I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects. </p> <p>Any help (even if it's just a kick in the right direction) would be appreciated.</p> <p>Edit: This is going through Django's ORM so I can't use SQL to do the conversion on insert.</p>
826
2009-01-21T18:00:29Z
30,577,110
<p>You can use <a href="https://github.com/ralphavalon/easy_date" rel="nofollow">easy_date</a> to make it easy:</p> <pre><code>import date_converter converted_date = date_converter.string_to_datetime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p') </code></pre>
1
2015-06-01T15:15:02Z
[ "python", "datetime" ]
Converting string into datetime
466,345
<p>Short and simple. I've got a huge list of date-times like this as strings:</p> <pre><code>Jun 1 2005 1:33PM Aug 28 1999 12:00AM </code></pre> <p>I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects. </p> <p>Any help (even if it's just a kick in the right direction) would be appreciated.</p> <p>Edit: This is going through Django's ORM so I can't use SQL to do the conversion on insert.</p>
826
2009-01-21T18:00:29Z
34,377,575
<p>Here is a solution using Pandas to convert dates formatted as strings into datetime.date objects.</p> <pre><code>import pandas as pd dates = ['2015-12-25', '2015-12-26'] &gt;&gt;&gt; [d.date() for d in pd.to_datetime(dates)] [datetime.date(2015, 12, 25), datetime.date(2015, 12, 26)] </code></pre> <p>And here is how to convert the OP's original date-time examples:</p> <pre><code>datetimes = ['Jun 1 2005 1:33PM', 'Aug 28 1999 12:00AM'] &gt;&gt;&gt; pd.to_datetime(datetimes).to_pydatetime().tolist() [datetime.datetime(2005, 6, 1, 13, 33), datetime.datetime(1999, 8, 28, 0, 0)] </code></pre> <p>There are many options for converting from the strings to Pandas Timestamps using <code>to_datetime</code>, so check the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html">docs</a> if you need anything special.</p> <p>Likewise, Timestamps have many <a href="http://pandas.pydata.org/pandas-docs/stable/api.html#datetimelike-properties">properties and methods</a> that can be accessed in addition to <code>.date</code></p>
7
2015-12-20T03:03:25Z
[ "python", "datetime" ]
Converting string into datetime
466,345
<p>Short and simple. I've got a huge list of date-times like this as strings:</p> <pre><code>Jun 1 2005 1:33PM Aug 28 1999 12:00AM </code></pre> <p>I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects. </p> <p>Any help (even if it's just a kick in the right direction) would be appreciated.</p> <p>Edit: This is going through Django's ORM so I can't use SQL to do the conversion on insert.</p>
826
2009-01-21T18:00:29Z
34,871,180
<pre><code>In [34]: import datetime In [35]: _now = datetime.datetime.now() In [36]: _now Out[36]: datetime.datetime(2016, 1, 19, 9, 47, 0, 432000) In [37]: print _now 2016-01-19 09:47:00.432000 In [38]: _parsed = datetime.datetime.strptime(str(_now),"%Y-%m-%d %H:%M:%S.%f") In [39]: _parsed Out[39]: datetime.datetime(2016, 1, 19, 9, 47, 0, 432000) In [40]: assert _now == _parsed </code></pre>
6
2016-01-19T07:48:47Z
[ "python", "datetime" ]
Converting string into datetime
466,345
<p>Short and simple. I've got a huge list of date-times like this as strings:</p> <pre><code>Jun 1 2005 1:33PM Aug 28 1999 12:00AM </code></pre> <p>I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects. </p> <p>Any help (even if it's just a kick in the right direction) would be appreciated.</p> <p>Edit: This is going through Django's ORM so I can't use SQL to do the conversion on insert.</p>
826
2009-01-21T18:00:29Z
35,202,640
<p>Create a small utility function like:</p> <pre><code>def date(datestr="", format="%Y-%m-%d"): from datetime import datetime if not datestr: return datetime.today().date() return datetime.strptime(datestr, format).date() </code></pre> <p>This is versatile enough:</p> <ul> <li>If you dont pass any arguments it will return today's date.</li> <li>theres a date format as default that you can override.</li> <li>You can easily modify it to return a datetime.</li> </ul>
3
2016-02-04T13:43:07Z
[ "python", "datetime" ]
Converting string into datetime
466,345
<p>Short and simple. I've got a huge list of date-times like this as strings:</p> <pre><code>Jun 1 2005 1:33PM Aug 28 1999 12:00AM </code></pre> <p>I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects. </p> <p>Any help (even if it's just a kick in the right direction) would be appreciated.</p> <p>Edit: This is going through Django's ORM so I can't use SQL to do the conversion on insert.</p>
826
2009-01-21T18:00:29Z
38,005,442
<p>The <a href="https://docs.python.org/2/library/datetime.html" rel="nofollow">datetime</a> python module is good for get date time and convert date time formats.</p> <pre><code>import datetime new_date_format1 = datetime.datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p') new_date_format2 = datetime.datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p').strftime('%Y/%m/%d %I:%M%p') print new_date_format1 print new_date_format2 </code></pre> <p>output :</p> <pre><code>2005-06-01 13:33:00 2005/06/01 01:33PM </code></pre>
0
2016-06-24T04:07:27Z
[ "python", "datetime" ]
How can I set it up so that threads communicate they're complete with their task?
466,525
<p>Conceptually, I would like to accomplish the following but have had trouble understand how to code it properly in Python:</p> <pre><code>from threading import Thread for i in range(0,3): t = Thread(target=myfunction) t.start() # wait until threads have finished executing print 'complete!' </code></pre>
0
2009-01-21T18:59:25Z
466,550
<p>I have never used python, but I think the concept you are looking for is a "semaphore".</p> <p>Google turned up this:</p> <p><a href="http://www.python.org/doc/2.5.2/lib/semaphore-objects.html" rel="nofollow">http://www.python.org/doc/2.5.2/lib/semaphore-objects.html</a></p>
-3
2009-01-21T19:06:02Z
[ "python", "multithreading" ]
How can I set it up so that threads communicate they're complete with their task?
466,525
<p>Conceptually, I would like to accomplish the following but have had trouble understand how to code it properly in Python:</p> <pre><code>from threading import Thread for i in range(0,3): t = Thread(target=myfunction) t.start() # wait until threads have finished executing print 'complete!' </code></pre>
0
2009-01-21T18:59:25Z
466,570
<p>add the threads to a list and <code>join()</code> them.</p> <pre><code>from threading import Thread tlist = [] for i in range(3): t = Thread(target=some_function) t.start() tlist.append(t) # wait until threads have finished executing for t in tlist: t.join() print 'complete!' </code></pre>
6
2009-01-21T19:10:02Z
[ "python", "multithreading" ]
Why do I have to specify my own class when using super(), and is there a way to get around it?
466,611
<p>When using Python's <code>super()</code> to do method chaining, you have to explicitly specify your own class, for example:</p> <pre><code>class MyDecorator(Decorator): def decorate(self): super(MyDecorator, self).decorate() </code></pre> <p>I have to specify the name of my class <code>MyDecorator</code> as an argument to <code>super()</code>. This is not DRY. When I rename my class now I will have to rename it twice. Why is this implemented this way? And is there a way to weasel out of having to write the name of the class twice(or more)?</p>
12
2009-01-21T19:20:58Z
466,638
<p>The BDFL agrees. See <a href="http://www.python.org/dev/peps/pep-0367/" rel="nofollow">Pep 367 - New Super</a> for 2.6 and <a href="http://www.python.org/dev/peps/pep-3135/" rel="nofollow">PEP 3135 - New Super</a> for 3.0.</p>
7
2009-01-21T19:28:33Z
[ "python", "multiple-inheritance" ]
Why do I have to specify my own class when using super(), and is there a way to get around it?
466,611
<p>When using Python's <code>super()</code> to do method chaining, you have to explicitly specify your own class, for example:</p> <pre><code>class MyDecorator(Decorator): def decorate(self): super(MyDecorator, self).decorate() </code></pre> <p>I have to specify the name of my class <code>MyDecorator</code> as an argument to <code>super()</code>. This is not DRY. When I rename my class now I will have to rename it twice. Why is this implemented this way? And is there a way to weasel out of having to write the name of the class twice(or more)?</p>
12
2009-01-21T19:20:58Z
466,647
<p>Your wishes come true:</p> <p>Just use python 3.0. In it you just use <code>super()</code> and it does <code>super(ThisClass, self)</code>.</p> <p>Documentation <a href="http://docs.python.org/3.0/library/functions.html#super">here</a>. Code sample from the documentation:</p> <pre><code>class C(B): def method(self, arg): super().method(arg) # This does the same thing as: super(C, self).method(arg) </code></pre>
10
2009-01-21T19:31:04Z
[ "python", "multiple-inheritance" ]
Why do I have to specify my own class when using super(), and is there a way to get around it?
466,611
<p>When using Python's <code>super()</code> to do method chaining, you have to explicitly specify your own class, for example:</p> <pre><code>class MyDecorator(Decorator): def decorate(self): super(MyDecorator, self).decorate() </code></pre> <p>I have to specify the name of my class <code>MyDecorator</code> as an argument to <code>super()</code>. This is not DRY. When I rename my class now I will have to rename it twice. Why is this implemented this way? And is there a way to weasel out of having to write the name of the class twice(or more)?</p>
12
2009-01-21T19:20:58Z
466,922
<p>you can also avoid writing a concrete class name in older versions of python by using</p> <pre><code>def __init__(self): super(self.__class__, self) ... </code></pre>
0
2009-01-21T20:49:17Z
[ "python", "multiple-inheritance" ]
Why do I have to specify my own class when using super(), and is there a way to get around it?
466,611
<p>When using Python's <code>super()</code> to do method chaining, you have to explicitly specify your own class, for example:</p> <pre><code>class MyDecorator(Decorator): def decorate(self): super(MyDecorator, self).decorate() </code></pre> <p>I have to specify the name of my class <code>MyDecorator</code> as an argument to <code>super()</code>. This is not DRY. When I rename my class now I will have to rename it twice. Why is this implemented this way? And is there a way to weasel out of having to write the name of the class twice(or more)?</p>
12
2009-01-21T19:20:58Z
25,377,660
<p>This answer is wrong, try:</p> <pre><code>def _super(cls): setattr(cls, '_super', lambda self: super(cls, self)) return cls class A(object): def f(self): print 'A.f' @_super class B(A): def f(self): self._super().f() @_super class C(B): def f(self): self._super().f() C().f() # maximum recursion error </code></pre> <hr> <p>In Python 2 there is a way using decorator:</p> <pre><code>def _super(cls): setattr(cls, '_super', lambda self: super(cls, self)) return cls class A(object): def f(self): print 'A.f' @_super class B(A): def f(self): self._super().f() B().f() # &gt;&gt;&gt; A.f </code></pre>
4
2014-08-19T07:19:10Z
[ "python", "multiple-inheritance" ]
How can I return system information in Python?
466,684
<p>Using Python, how can information such as CPU usage, memory usage (free, used, etc), process count, etc be returned in a generic manner so that the same code can be run on Linux, Windows, BSD, etc?</p> <p>Alternatively, how could this information be returned on all the above systems with the code specific to that OS being run only if that OS is indeed the operating environment?</p>
23
2009-01-21T19:40:34Z
466,714
<p>take a look at the <a href="http://docs.python.org/library/os.html" rel="nofollow">os module</a></p>
1
2009-01-21T19:53:19Z
[ "python", "operating-system" ]
How can I return system information in Python?
466,684
<p>Using Python, how can information such as CPU usage, memory usage (free, used, etc), process count, etc be returned in a generic manner so that the same code can be run on Linux, Windows, BSD, etc?</p> <p>Alternatively, how could this information be returned on all the above systems with the code specific to that OS being run only if that OS is indeed the operating environment?</p>
23
2009-01-21T19:40:34Z
466,755
<p>It looks like you want to get a lot more information than the standard Python library offers. If I were you, I would download the source code for 'ps' or 'top', or the Gnome/KDE version of the same, or any number of system monitoring/graphing programs which are more likely to have all the necessary Unix cross platform bits, see what they do, and then make the necessary native calls with ctypes.</p> <p>It's trivial to detect the platform. For example with ctypes you might try to load libc.so, if that throws an exception try to load 'msvcrt.dll' and so on. Not to mention simply checking the operating system's name with os.name. Then just delegate calls to your new cross-platform API to the appropriate platform-specific (sorry) implementation.</p> <p>When you're done, don't forget to upload the resulting package to pypi.</p>
1
2009-01-21T20:07:49Z
[ "python", "operating-system" ]
How can I return system information in Python?
466,684
<p>Using Python, how can information such as CPU usage, memory usage (free, used, etc), process count, etc be returned in a generic manner so that the same code can be run on Linux, Windows, BSD, etc?</p> <p>Alternatively, how could this information be returned on all the above systems with the code specific to that OS being run only if that OS is indeed the operating environment?</p>
23
2009-01-21T19:40:34Z
466,761
<p>In a Linux environment you could read from the /proc file system.</p> <pre><code>~$ cat /proc/meminfo MemTotal: 2076816 kB MemFree: 130284 kB Buffers: 192664 kB Cached: 1482760 kB SwapCached: 0 kB Active: 206584 kB Inactive: 1528608 kB HighTotal: 1179484 kB HighFree: 120768 kB LowTotal: 897332 kB LowFree: 9516 kB SwapTotal: 2650684 kB SwapFree: 2650632 kB Dirty: 64 kB Writeback: 12 kB AnonPages: 59668 kB Mapped: 22008 kB Slab: 200744 kB PageTables: 1220 kB NFS_Unstable: 0 kB Bounce: 0 kB CommitLimit: 3689092 kB Committed_AS: 263892 kB VmallocTotal: 114680 kB VmallocUsed: 3604 kB VmallocChunk: 110752 kB </code></pre>
5
2009-01-21T20:09:07Z
[ "python", "operating-system" ]
How can I return system information in Python?
466,684
<p>Using Python, how can information such as CPU usage, memory usage (free, used, etc), process count, etc be returned in a generic manner so that the same code can be run on Linux, Windows, BSD, etc?</p> <p>Alternatively, how could this information be returned on all the above systems with the code specific to that OS being run only if that OS is indeed the operating environment?</p>
23
2009-01-21T19:40:34Z
466,831
<p>I recommend the platform module:</p> <p><a href="http://doc.astro-wise.org/platform.html" rel="nofollow">http://doc.astro-wise.org/platform.html</a></p> <p><a href="http://docs.python.org/library/platform.html" rel="nofollow">http://docs.python.org/library/platform.html</a></p> <p><a href="http://www.doughellmann.com/PyMOTW/platform/index.html" rel="nofollow">http://www.doughellmann.com/PyMOTW/platform/index.html</a></p>
3
2009-01-21T20:25:02Z
[ "python", "operating-system" ]
How can I return system information in Python?
466,684
<p>Using Python, how can information such as CPU usage, memory usage (free, used, etc), process count, etc be returned in a generic manner so that the same code can be run on Linux, Windows, BSD, etc?</p> <p>Alternatively, how could this information be returned on all the above systems with the code specific to that OS being run only if that OS is indeed the operating environment?</p>
23
2009-01-21T19:40:34Z
466,961
<p>There's the <a href="http://www.psychofx.com/psi/" rel="nofollow">PSI</a> (Python System Information) project with that aim, but they don't cover Windows yet.</p> <p>You can probably use PSI and recpies <a href="http://code.activestate.com/recipes/511491/" rel="nofollow">like this one</a> and create a basic library that meets your needs.</p>
0
2009-01-21T20:58:19Z
[ "python", "operating-system" ]
How can I return system information in Python?
466,684
<p>Using Python, how can information such as CPU usage, memory usage (free, used, etc), process count, etc be returned in a generic manner so that the same code can be run on Linux, Windows, BSD, etc?</p> <p>Alternatively, how could this information be returned on all the above systems with the code specific to that OS being run only if that OS is indeed the operating environment?</p>
23
2009-01-21T19:40:34Z
467,291
<p>Regarding cross-platform: your best bet is probably to write platform-specific code, and then import it conditionally. e.g.</p> <pre><code>import sys if sys.platform == 'win32': import win32_sysinfo as sysinfo elif sys.platform == 'darwin': import mac_sysinfo as sysinfo elif 'linux' in sys.platform: import linux_sysinfo as sysinfo #etc print 'Memory available:', sysinfo.memory_available() </code></pre> <p>For specific resources, as Anthony points out you can access <code>/proc</code> under linux. For Windows, you could have a poke around at the <a href="http://www.microsoft.com/technet/scriptcenter/scripts/python/default.mspx?mfr=true">Microsoft Script Repository</a>. I'm not sure where to get that kind of information on Macs, but I can think of a great website where you could ask :-)</p>
16
2009-01-21T22:25:02Z
[ "python", "operating-system" ]
How can I return system information in Python?
466,684
<p>Using Python, how can information such as CPU usage, memory usage (free, used, etc), process count, etc be returned in a generic manner so that the same code can be run on Linux, Windows, BSD, etc?</p> <p>Alternatively, how could this information be returned on all the above systems with the code specific to that OS being run only if that OS is indeed the operating environment?</p>
23
2009-01-21T19:40:34Z
29,018,179
<p><a href="https://github.com/giampaolo/psutil" rel="nofollow">psutil</a> should provide what you need:</p> <blockquote> <p>[...] cross-platform library for retrieving information on running processes and system utilization (CPU, memory, disks, network) [...]</p> <p>[...] supports Linux, Windows, OSX, FreeBSD and Sun Solaris, both 32-bit and 64-bit architectures [...]</p> </blockquote>
1
2015-03-12T19:03:19Z
[ "python", "operating-system" ]
reading/writing xmp metadatas on pdf files through pypdf
466,692
<p>I can read xmp metadatas through pyPdf with this code:</p> <pre><code>a = pyPdf.PdfFileReader(open(self.fileName)) b = a.getXmpMetadata() c = b.pdf_keywords </code></pre> <p>but: is this the best way? </p> <p>And if I don't use the pdf_keywords property?</p> <p>And is there any way to set these metadatas with pyPdf?</p>
5
2009-01-21T19:43:46Z
472,721
<p>As far as I can see, this is the best way to do so - and there is no way to change the metadata with pyPDF.</p>
3
2009-01-23T12:32:54Z
[ "python", "pdf", "metadata", "xmp", "pypdf" ]
Python piping on Windows: Why does this not work?
466,801
<p>I'm trying something like this</p> <p>Output.py</p> <pre><code>print "Hello" </code></pre> <p>Input.py</p> <pre><code>greeting = raw_input("Give me the greeting. ") print "The greeting is:", greeting </code></pre> <p>At the cmd line</p> <pre><code>Output.py | Input.py </code></pre> <p>But it returns an <i>EOFError</i>. Can someone tell me what I am doing wrong?</p> <p>Thanks for your help.</p> <p><b>EDIT</b> <br> Patrick Harrington <a href="http://stackoverflow.com/questions/466801/python-piping-on-windows-why-does-this-not-work#466851">solution</a> works but I don't know why...</p>
10
2009-01-21T20:20:05Z
466,849
<p>I tested this on my Windows machine and it works if you specify the Python exe: </p> <pre><code>C:\&gt;C:\Python25\python.exe output.py | C:\Python25\python.exe input.py Give me the greeting. The greeting is: hello </code></pre> <p>But I get an EOFError also if running the commands directly as: </p> <pre><code>output.py | input.py </code></pre> <p>I'm not sure exactly why that is, I'm still looking into this one but at least this should provide you with a workaround for now. It may have something to do with the way the file handler is invoked for .py files. </p> <p><strong>UPDATE</strong>: well, what do you know. Looks like this is actually a bug in Windows where stdin/stdout redirection may not work properly when started from a file association. So the workaround is as noted by myself and Patrick, you need to specify "python" will be running input.py, otherwise it will not redirect stdout from output.py to the stdin for input.py correctly. </p> <p><em>Reference</em>:</p> <p><strong><a href="http://mail.python.org/pipermail/python-bugs-list/2004-August/024923.html">http://mail.python.org/pipermail/python-bugs-list/2004-August/024923.html</a></strong> </p> <p><strong><a href="http://support.microsoft.com/default.aspx?kbid=321788">http://support.microsoft.com/default.aspx?kbid=321788</a></strong></p> <p><strong>UPDATE 2</strong>: </p> <p>To change this behavior and make Windows pipes work as expected for stdin/stdout redirection, you can add this value to the registry (tested on my box and verified this works as desired).</p> <blockquote> <ol> <li>Start Registry Editor.</li> <li><p>Locate and then click the following key in the registry:</p> <p><strong>HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer</strong></p></li> <li><p>On the Edit menu, click Add Value, and then add the following registry value:</p> <p>Value name: <em>InheritConsoleHandles</em><br /> Data type: *REG_DWORD*<br /> Radix: Decimal<br /> Value data: 1</p></li> <li><p>Quit Registry Editor.</p></li> </ol> </blockquote>
23
2009-01-21T20:30:27Z
[ "python", "windows", "piping" ]
Python piping on Windows: Why does this not work?
466,801
<p>I'm trying something like this</p> <p>Output.py</p> <pre><code>print "Hello" </code></pre> <p>Input.py</p> <pre><code>greeting = raw_input("Give me the greeting. ") print "The greeting is:", greeting </code></pre> <p>At the cmd line</p> <pre><code>Output.py | Input.py </code></pre> <p>But it returns an <i>EOFError</i>. Can someone tell me what I am doing wrong?</p> <p>Thanks for your help.</p> <p><b>EDIT</b> <br> Patrick Harrington <a href="http://stackoverflow.com/questions/466801/python-piping-on-windows-why-does-this-not-work#466851">solution</a> works but I don't know why...</p>
10
2009-01-21T20:20:05Z
466,851
<p>Change it to:</p> <pre><code>Output.py | python Input.py </code></pre> <p>The output will be:</p> <blockquote> <p>Give me the greeting. The greeting is: hello</p> </blockquote>
4
2009-01-21T20:30:46Z
[ "python", "windows", "piping" ]
Python piping on Windows: Why does this not work?
466,801
<p>I'm trying something like this</p> <p>Output.py</p> <pre><code>print "Hello" </code></pre> <p>Input.py</p> <pre><code>greeting = raw_input("Give me the greeting. ") print "The greeting is:", greeting </code></pre> <p>At the cmd line</p> <pre><code>Output.py | Input.py </code></pre> <p>But it returns an <i>EOFError</i>. Can someone tell me what I am doing wrong?</p> <p>Thanks for your help.</p> <p><b>EDIT</b> <br> Patrick Harrington <a href="http://stackoverflow.com/questions/466801/python-piping-on-windows-why-does-this-not-work#466851">solution</a> works but I don't know why...</p>
10
2009-01-21T20:20:05Z
467,756
<p>Here's why you get the EOFError (from the documentation on raw_input):</p> <blockquote> <p>The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.</p> </blockquote> <p><a href="http://docs.python.org/library/functions.html?highlight=raw_input#raw_input" rel="nofollow">http://docs.python.org/library/functions.html?highlight=raw_input#raw_input</a></p> <p>You may want to use <strong>sys.stdin</strong>, it provides a file object from which you can use the read, readlines methods.</p> <pre><code>import sys for greeting_line in sys.stdin.readlines(): print "The greeting is:", greeting_line.strip() </code></pre>
0
2009-01-22T01:22:47Z
[ "python", "windows", "piping" ]
How will Python and Ruby applications be affected by .NET?
466,897
<p>I'm curious about how .NET will affect Python and Ruby applications. </p> <p>Will applications written in IronPython/IronRuby be so specific to the .NET environment, that they will essentially become platform specific? </p> <p>If they don't use any of the .NET features, then what is the advantage of IronPython/IronRuby over their non .NET counterparts?</p>
5
2009-01-21T20:43:40Z
466,930
<p>IronPython/IronRuby are built to work on the .net virtual machine, so they are as you say essentially platform specific. </p> <p>Apparently they are compatible with Python and Ruby as long as you don't use any of the .net framework in your programs. </p>
1
2009-01-21T20:51:04Z
[ ".net", "python", "ruby", "ironpython", "ironruby" ]
How will Python and Ruby applications be affected by .NET?
466,897
<p>I'm curious about how .NET will affect Python and Ruby applications. </p> <p>Will applications written in IronPython/IronRuby be so specific to the .NET environment, that they will essentially become platform specific? </p> <p>If they don't use any of the .NET features, then what is the advantage of IronPython/IronRuby over their non .NET counterparts?</p>
5
2009-01-21T20:43:40Z
467,031
<p>You answer your first question with the second one, if you don't use anything from .Net only the original libs provided by the implementation of the language, you could interpret your *.py or *.rb file with another implementation and it should work.</p> <p>The advantage would be if your a .Net shop you usually take care of having the right framework installed on client machine etc... well if you want python or ruby code, you now need to support another "framework" need to distribute install, take care of version problem etc... So there 2 advantages, using .Net framework power inside another language + keep the distribution/maintenance as simple as possible.</p>
0
2009-01-21T21:12:41Z
[ ".net", "python", "ruby", "ironpython", "ironruby" ]
How will Python and Ruby applications be affected by .NET?
466,897
<p>I'm curious about how .NET will affect Python and Ruby applications. </p> <p>Will applications written in IronPython/IronRuby be so specific to the .NET environment, that they will essentially become platform specific? </p> <p>If they don't use any of the .NET features, then what is the advantage of IronPython/IronRuby over their non .NET counterparts?</p>
5
2009-01-21T20:43:40Z
467,067
<p>It would be cool to run Rails/Django under IIS rather then Apache/Mongrel type solutions</p>
0
2009-01-21T21:21:19Z
[ ".net", "python", "ruby", "ironpython", "ironruby" ]
How will Python and Ruby applications be affected by .NET?
466,897
<p>I'm curious about how .NET will affect Python and Ruby applications. </p> <p>Will applications written in IronPython/IronRuby be so specific to the .NET environment, that they will essentially become platform specific? </p> <p>If they don't use any of the .NET features, then what is the advantage of IronPython/IronRuby over their non .NET counterparts?</p>
5
2009-01-21T20:43:40Z
467,145
<p>If you create a library or framework, people can use it on .NET with their .NET code. That's pretty cool for them, and for you!</p> <p>When developing an application, if you use .NET's facilities with abandon then you lose "cross-platformity", which is not always an issue.</p> <p>If you wrap these uses with an internal API, you can replace the .NET implementations later with pure-Python, wrapped C (for CPython), or Java (for Jython) later.</p>
1
2009-01-21T21:41:33Z
[ ".net", "python", "ruby", "ironpython", "ironruby" ]
How will Python and Ruby applications be affected by .NET?
466,897
<p>I'm curious about how .NET will affect Python and Ruby applications. </p> <p>Will applications written in IronPython/IronRuby be so specific to the .NET environment, that they will essentially become platform specific? </p> <p>If they don't use any of the .NET features, then what is the advantage of IronPython/IronRuby over their non .NET counterparts?</p>
5
2009-01-21T20:43:40Z
467,385
<p>According to the Mono page, IronPython is compatible with Mono's implementation of the .Net runtime, so executables should work both on Windows and Linux.</p>
1
2009-01-21T22:50:17Z
[ ".net", "python", "ruby", "ironpython", "ironruby" ]
How will Python and Ruby applications be affected by .NET?
466,897
<p>I'm curious about how .NET will affect Python and Ruby applications. </p> <p>Will applications written in IronPython/IronRuby be so specific to the .NET environment, that they will essentially become platform specific? </p> <p>If they don't use any of the .NET features, then what is the advantage of IronPython/IronRuby over their non .NET counterparts?</p>
5
2009-01-21T20:43:40Z
475,953
<p>I can't say anything about IronRuby, but most python implementations (like IronPython, Jython and PyPy) try to be as true to the CPython implementation as possible. IronPython is quickly becoming one of the best in this respect though, and there is a lot of traffic on Planet Python about it.</p> <p>The main thing that will encourage developers to write code that's different from what they would write in CPython is the lack of C extension modules like NumPy (This is a problem in Jython and PyPy as well). </p> <p>An interesting project to keep your eye on is IronClad, which will let you call C extension modules from within IronPython. This should eventually mean that you can develop code under CPython, using whatever modules you like, and it will run unmodified on IronPython.</p> <p><a href="http://www.resolversystems.com/documentation/index.php/Ironclad">http://www.resolversystems.com/documentation/index.php/Ironclad</a></p> <p>So to answer your questions:</p> <p>It should be easy enough to write IronPython applications that work on CPython as well, but I would probably aim to go the other way around: CPython programs that work on IronPython as well. That way, if it doesn't work then it's more likely to be a known bug with a known work-around.</p> <p>The advantage of IronPython et al <em>existing</em> is that they provide alternative implementations of the language, which are sometimes useful for spotting bugs in CPython. They also provide alternative methods for deploying your Python applications, if for some reason you find yourself in a situation (like silverlight) where distributing the CPython implementation with your application is not appropriate.</p>
5
2009-01-24T12:23:04Z
[ ".net", "python", "ruby", "ironpython", "ironruby" ]
How will Python and Ruby applications be affected by .NET?
466,897
<p>I'm curious about how .NET will affect Python and Ruby applications. </p> <p>Will applications written in IronPython/IronRuby be so specific to the .NET environment, that they will essentially become platform specific? </p> <p>If they don't use any of the .NET features, then what is the advantage of IronPython/IronRuby over their non .NET counterparts?</p>
5
2009-01-21T20:43:40Z
1,285,474
<blockquote> <p><em>Will applications written in IronPython/IronRuby be so specific to the .NET environment, that they will essentially become platform specific?</em></p> </blockquote> <p>IronRuby currently ships with most of the core ruby standard library, and support for ruby gems.</p> <p>This means that it will support pretty much any native ruby app that doesn't rely on C extensions.<br /> The flipside is that it will be possible to write native ruby apps in IronRuby that don't rely on the CLR, and those will be portable to MRI. </p> <p>Whether or not people choose to create or use extensions for their apps using the CLR is the same question as to whether people create or use C extensions for MRI - one is no more portable than the other.</p> <p>There is a side-question of <strong>"because it is so much easier to create IronRuby extensions in C# than it is to create CRuby extensions in C, will people create extensions where they should be sticking to native ruby code?"</strong>, but that's entirely subjective.</p> <p>On the whole though, I think anything that makes creating extensions easier is a big win.</p> <p><hr /></p> <blockquote> <p><em>If they don't use any of the .NET features, then what is the advantage of IronPython/IronRuby over their non .NET counterparts?</em></p> </blockquote> <ol> <li><p>Performance: IronRuby is already faster for the most part than MRI 1.8, and isn't far off MRI 1.9, and things will only improve in future. I think python is similar in this respect.</p></li> <li><p>Deployment: As people have mentioned, running a native ruby cross-platform rails app inside IIS is an attractive proposition to some windows-based developers, as it lets them better integrate with existing servers/management infrastructure/etc</p></li> <li><p>Stability: While MRI 1.9 is much better than 1.8 was, I don't think anyone could disagree that CLR has a much better garbage collector and base runtime than C ruby does.</p></li> </ol>
2
2009-08-16T22:16:17Z
[ ".net", "python", "ruby", "ironpython", "ironruby" ]
python: list comprehension tactics
467,094
<p>I'm looking to take a string and create a list of strings that build up the original string.</p> <p>e.g.:</p> <pre><code>"asdf" =&gt; ["a", "as", "asd", "asdf"] </code></pre> <p>I'm sure there's a "pythonic" way to do it; I think I'm just losing my mind. What's the best way to get this done?</p>
8
2009-01-21T21:27:47Z
467,102
<p>One possibility:</p> <pre><code>&gt;&gt;&gt; st = 'asdf' &gt;&gt;&gt; [st[:n+1] for n in range(len(st))] ['a', 'as', 'asd', 'asdf'] </code></pre>
19
2009-01-21T21:30:19Z
[ "python", "list-comprehension" ]
python: list comprehension tactics
467,094
<p>I'm looking to take a string and create a list of strings that build up the original string.</p> <p>e.g.:</p> <pre><code>"asdf" =&gt; ["a", "as", "asd", "asdf"] </code></pre> <p>I'm sure there's a "pythonic" way to do it; I think I'm just losing my mind. What's the best way to get this done?</p>
8
2009-01-21T21:27:47Z
467,161
<p>If you're going to be looping over the elements of your "list", you may be better off using a generator rather than list comprehension:</p> <pre><code>&gt;&gt;&gt; text = "I'm a little teapot." &gt;&gt;&gt; textgen = (text[:i + 1] for i in xrange(len(text))) &gt;&gt;&gt; textgen &lt;generator object &lt;genexpr&gt; at 0x0119BDA0&gt; &gt;&gt;&gt; for item in textgen: ... if re.search("t$", item): ... print item I'm a lit I'm a litt I'm a little t I'm a little teapot &gt;&gt;&gt; </code></pre> <p>This code never creates a list object, nor does it ever (delta garbage collection) create more than one extra string (in addition to <code>text</code>).</p>
16
2009-01-21T21:47:34Z
[ "python", "list-comprehension" ]
How to prevent overwriting an object someone else has modified
467,134
<p>I would like to find a generic way of preventing to save an object if it is saved after I checked it out.</p> <p>We can assume the object has a <code>timestamp</code> field that contains last modification time. If I had checked out (visited a view using a ModelForm for instance) at <code>t1</code> and the object is saved again at <code>t2</code>, given <code>t2</code> > <code>t1</code> I shouldn't be able to save it.</p>
2
2009-01-21T21:38:39Z
467,159
<p>Overwrite the save method that would first check the last timestamp:</p> <pre><code>def save(self): if(self.id): foo = Foo.objects.get(pk=self.id) if(foo.timestamp &gt; self.timestamp): raise Exception, "trying to save outdated Foo" super(Foo, self).save() </code></pre>
4
2009-01-21T21:47:10Z
[ "python", "django", "django-models", "locking", "blocking" ]
How can I read system information in Python on OS X?
467,600
<p>Following from this <a href="http://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python">OS-agnostic question</a>, specifically <a href="http://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python#467291">this response</a>, similar to data available from the likes of /proc/meminfo on Linux, how can I read system information from OS X using Python (including, but not limited to memory usage).</p>
1
2009-01-22T00:08:19Z
467,698
<p>I did some more googling (looking for "OS X /proc") -- it looks like the sysctl command might be what you want, although I'm not sure if it will give you all the information you need. Here's the manpage: <a href="http://developer.apple.com/DOCUMENTATION/Darwin/Reference/ManPages/man8/sysctl.8.html" rel="nofollow">http://developer.apple.com/DOCUMENTATION/Darwin/Reference/ManPages/man8/sysctl.8.html</a></p> <p>Also, <a href="http://en.wikipedia.org/wiki/Sysctl" rel="nofollow">wikipedia</a>.</p>
2
2009-01-22T00:52:59Z
[ "python", "osx", "operating-system" ]
How can I read system information in Python on OS X?
467,600
<p>Following from this <a href="http://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python">OS-agnostic question</a>, specifically <a href="http://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python#467291">this response</a>, similar to data available from the likes of /proc/meminfo on Linux, how can I read system information from OS X using Python (including, but not limited to memory usage).</p>
1
2009-01-22T00:08:19Z
467,701
<p>You can get a large amount of system information from the command line utilities <a href="http://developer.apple.com/DOCUMENTATION/Darwin/Reference/ManPages/man8/sysctl.8.html" rel="nofollow"><code>sysctl</code></a> and <a href="http://developer.apple.com/DOCUMENTATION/DARWIN/Reference/ManPages/man1/vm_stat.1.html" rel="nofollow"><code>vm_stat</code></a> (as well as <code>ps</code>, as in <a href="http://stackoverflow.com/questions/276052/how-to-get-current-cpu-and-ram-usage-in-python">this question</a>.) </p> <p>If you don't find a better way, you could always call these using <a href="http://docs.python.org/library/subprocess.html" rel="nofollow"><code>subprocess</code></a>.</p>
3
2009-01-22T00:54:13Z
[ "python", "osx", "operating-system" ]
How can I read system information in Python on OS X?
467,600
<p>Following from this <a href="http://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python">OS-agnostic question</a>, specifically <a href="http://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python#467291">this response</a>, similar to data available from the likes of /proc/meminfo on Linux, how can I read system information from OS X using Python (including, but not limited to memory usage).</p>
1
2009-01-22T00:08:19Z
467,726
<p>The only stuff that's really nicely accesible is available from the platform module, but it's extremely limited (cpu, os version, architecture, etc). For cpu usage and uptime I think you will have to wrap the command line utilities 'uptime' and 'vm_stat'.</p> <p>I built you one for vm_stat, the other one is up to you ;-)</p> <pre><code>import os, sys def memoryUsage(): result = dict() for l in [l.split(':') for l in os.popen('vm_stat').readlines()[1:8]]: result[l[0].strip(' "').replace(' ', '_').lower()] = int(l[1].strip('.\n ')) return result print memoryUsage() </code></pre>
3
2009-01-22T01:04:24Z
[ "python", "osx", "operating-system" ]
How can I read system information in Python on OS X?
467,600
<p>Following from this <a href="http://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python">OS-agnostic question</a>, specifically <a href="http://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python#467291">this response</a>, similar to data available from the likes of /proc/meminfo on Linux, how can I read system information from OS X using Python (including, but not limited to memory usage).</p>
1
2009-01-22T00:08:19Z
467,783
<p>Here's a MacFUSE-based /proc fs:</p> <p><a href="http://www.osxbook.com/book/bonus/chapter11/procfs" rel="nofollow">http://www.osxbook.com/book/bonus/chapter11/procfs</a></p> <p>If you have control of the boxes you're running your python program on it might be a reasonable solution. At any rate it's nice to have a /proc to look at!</p>
0
2009-01-22T01:42:18Z
[ "python", "osx", "operating-system" ]
How can I read system information in Python on OS X?
467,600
<p>Following from this <a href="http://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python">OS-agnostic question</a>, specifically <a href="http://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python#467291">this response</a>, similar to data available from the likes of /proc/meminfo on Linux, how can I read system information from OS X using Python (including, but not limited to memory usage).</p>
1
2009-01-22T00:08:19Z
23,185,536
<p>i was searching for this same thing, and i noticed there was no accepted answer for this question. in the intervening time since the question was originally asked, a python module called psutil was released:</p> <p><a href="https://github.com/giampaolo/psutil" rel="nofollow">https://github.com/giampaolo/psutil</a></p> <p>for memory utilization, you can use the following:</p> <pre><code>&gt;&gt;&gt; psutil.virtual_memory() svmem(total=8374149120L, available=2081050624L, percent=75.1, used=8074080256L, free=300068864L, active=3294920704, inactive=1361616896, buffers=529895424L, cached=1251086336) &gt;&gt;&gt; psutil.swap_memory() sswap(total=2097147904L, used=296128512L, free=1801019392L, percent=14.1, sin=304193536, sout=677842944) &gt;&gt;&gt; </code></pre> <p>there are functions for cpu utilization, process management, disk, and network as well. the only omission from the module is a function for retrieving load average, but the python stdlib has os.getloadavg() if you are on a UNIX-like system.</p> <p>psutil claims to support Linux, Windows, OSX, FreeBSD and Sun Solaris, but i have only tried OSX mavericks and fedora 20.</p>
0
2014-04-20T17:32:58Z
[ "python", "osx", "operating-system" ]
How can I read system information in Python on Windows?
467,602
<p>Following from this <a href="http://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python">OS-agnostic question</a>, specifically <a href="http://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python#467291">this response</a>, similar to data available from the likes of /proc/meminfo on Linux, how can I read system information from Windows using Python (including, but not limited to memory usage).</p>
1
2009-01-22T00:09:44Z
467,648
<p>There was a similar question asked:</p> <p><a href="http://stackoverflow.com/questions/276052/how-to-get-current-cpu-and-ram-usage-in-python">http://stackoverflow.com/questions/276052/how-to-get-current-cpu-and-ram-usage-in-python</a></p> <p>There are quite a few answers telling you how to accomplish this in windows.</p>
1
2009-01-22T00:32:16Z
[ "python", "windows", "operating-system" ]
How can I read system information in Python on Windows?
467,602
<p>Following from this <a href="http://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python">OS-agnostic question</a>, specifically <a href="http://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python#467291">this response</a>, similar to data available from the likes of /proc/meminfo on Linux, how can I read system information from Windows using Python (including, but not limited to memory usage).</p>
1
2009-01-22T00:09:44Z
1,996,085
<p>You can try using the systeminfo.exe wrapper I created a while back, it's a bit unorthodox but it seems to do the trick easily enough and without much code.</p> <p>This should work on 2000/XP/2003 Server, and should work on Vista and Win7 provided they come with systeminfo.exe and it is located on the path.</p> <pre><code>import os, re def SysInfo(): values = {} cache = os.popen2("SYSTEMINFO") source = cache[1].read() sysOpts = ["Host Name", "OS Name", "OS Version", "Product ID", "System Manufacturer", "System Model", "System type", "BIOS Version", "Domain", "Windows Directory", "Total Physical Memory", "Available Physical Memory", "Logon Server"] for opt in sysOpts: values[opt] = [item.strip() for item in re.findall("%s:\w*(.*?)\n" % (opt), source, re.IGNORECASE)][0] return values </code></pre> <p>You can easily append the rest of the data fields to the sysOpts variable, excluding those that provide multiple lines for their results, like CPU &amp; NIC information. A simple mod to the regexp line should be able to handle that.</p> <p>Enjoy!</p>
2
2010-01-03T19:53:01Z
[ "python", "windows", "operating-system" ]
How can I read system information in Python on Windows?
467,602
<p>Following from this <a href="http://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python">OS-agnostic question</a>, specifically <a href="http://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python#467291">this response</a>, similar to data available from the likes of /proc/meminfo on Linux, how can I read system information from Windows using Python (including, but not limited to memory usage).</p>
1
2009-01-22T00:09:44Z
11,785,020
<p>In Windows, if you want to get info like from the SYSTEMINFO command, you can use the <a href="https://pypi.python.org/pypi/WMI/" rel="nofollow">WMI module.</a></p> <pre><code>import wmi c = wmi.WMI() systeminfo = c.Win32_ComputerSystem()[0] Manufacturer = systeminfo.Manufacturer Model = systeminfo.Model </code></pre> <p>...</p> <p>similarly, the os-related info could be got from <code>osinfo = c.Win32_OperatingSystem()[0]</code> the full list of <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx" rel="nofollow">system info is here</a> and <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa394239%28v=vs.85%29.aspx" rel="nofollow">os info is here</a></p>
3
2012-08-02T20:11:41Z
[ "python", "windows", "operating-system" ]
Implementing a "rules engine" in Python
467,738
<p>I'm writing a log collection / analysis application in Python and I need to write a "rules engine" to match and act on log messages.</p> <p>It needs to feature:</p> <ul> <li>Regular expression matching for the message itself</li> <li>Arithmetic comparisons for message severity/priority</li> <li>Boolean operators</li> </ul> <p>I envision An example rule would probably be something like:</p> <pre><code>(message ~ "program\\[\d+\\]: message" and severity &gt;= high) or (severity &gt;= critical) </code></pre> <p>I'm thinking about using <a href="http://pyparsing.wikispaces.com/">PyParsing</a> or similar to actually parse the rules and construct the parse tree.</p> <p>The current (not yet implemented) design I have in mind is to have classes for each rule type, and construct and chain them together according to the parse tree. Then each rule would have a "matches" method that could take a message object return whether or not it matches the rule.</p> <p>Very quickly, something like:</p> <pre><code>class RegexRule(Rule): def __init__(self, regex): self.regex = regex def match(self, message): return self.regex.match(message.contents) class SeverityRule(Rule): def __init__(self, operator, severity): self.operator = operator def match(self, message): if operator == "&gt;=": return message.severity &gt;= severity # more conditions here... class BooleanAndRule(Rule): def __init__(self, rule1, rule2): self.rule1 = rule1 self.rule2 = rule2 def match(self, message): return self.rule1.match(message) and self.rule2.match(message) </code></pre> <p>These rule classes would then be chained together according to the parse tree of the message, and the match() method called on the top rule, which would cascade down until all the rules were evaluated.</p> <p>I'm just wondering if this is a reasonable approach, or if my design and ideas are way totally out of whack? Unfortunately I never had the chance to take a compiler design course or anything like that in Unviersity so I'm pretty much coming up with this stuff of my own accord.</p> <p>Could someone with some experience in these kinds of things please chime in and evaluate the idea?</p> <p><strong>EDIT:</strong> Some good answers so far, here's a bit of clarification.</p> <p>The aim of the program is to collect log messages from servers on the network and store them in the database. Apart from the collection of log messages, the collector will define a set of rules that will either match or ignore messages depending on the conditions and flag an alert if necessary.</p> <p>I can't see the rules being of more than a moderate complexity, and they will be applied in a chain (list) until either a matching alert or ignore rule is hit. However, this part isn't quite as relevant to the question.</p> <p>As far the syntax being close to Python syntax, yes that is true, however I think it would be difficult to filter the Python down to the point where the user couldn't inadvertently do some crazy stuff with the rules that was not intended.</p>
16
2009-01-22T01:11:24Z
467,752
<p>The only place that's different from Python syntax itself is the <code>message ~ "program\\[\d+\\]: message"</code> part, so I wonder if you really need a new syntax.</p> <p><strong>Update:</strong> OK, you have either usability or safety concerns -- that's reasonable. A couple suggestions:</p> <ul> <li><p>Take a hint from Awk and streamline the pattern-matching syntax, e.g. <code>/program\[\d+\]: message/</code> instead of <code>message ~ "program\\[\d+\\]: message"</code>.</p></li> <li><p>I'd implement it by translating to a Python expression as the input is parsed, instead of building a tree of objects to evaluate, unless you expect to be doing more operations on these things than evaluation. This should need less code and run faster. The top level might go something like:</p> <pre><code>def compile(input): return eval('lambda message, severity: %s' % parse(input)) </code></pre></li> </ul> <p>Another idea, further afield: write your app in Lua. It's designed for nonprogrammers to extend programs reasonably safely without needing to learn a lot. (It's been used that way successfully, and you can sandbox evaluation so user's code can't get at any capabilities you don't pass to it explicitly, I'm told.)</p> <p>I'll shut up now. :-) Good luck!</p>
0
2009-01-22T01:20:11Z
[ "python", "parsing", "rules" ]
Implementing a "rules engine" in Python
467,738
<p>I'm writing a log collection / analysis application in Python and I need to write a "rules engine" to match and act on log messages.</p> <p>It needs to feature:</p> <ul> <li>Regular expression matching for the message itself</li> <li>Arithmetic comparisons for message severity/priority</li> <li>Boolean operators</li> </ul> <p>I envision An example rule would probably be something like:</p> <pre><code>(message ~ "program\\[\d+\\]: message" and severity &gt;= high) or (severity &gt;= critical) </code></pre> <p>I'm thinking about using <a href="http://pyparsing.wikispaces.com/">PyParsing</a> or similar to actually parse the rules and construct the parse tree.</p> <p>The current (not yet implemented) design I have in mind is to have classes for each rule type, and construct and chain them together according to the parse tree. Then each rule would have a "matches" method that could take a message object return whether or not it matches the rule.</p> <p>Very quickly, something like:</p> <pre><code>class RegexRule(Rule): def __init__(self, regex): self.regex = regex def match(self, message): return self.regex.match(message.contents) class SeverityRule(Rule): def __init__(self, operator, severity): self.operator = operator def match(self, message): if operator == "&gt;=": return message.severity &gt;= severity # more conditions here... class BooleanAndRule(Rule): def __init__(self, rule1, rule2): self.rule1 = rule1 self.rule2 = rule2 def match(self, message): return self.rule1.match(message) and self.rule2.match(message) </code></pre> <p>These rule classes would then be chained together according to the parse tree of the message, and the match() method called on the top rule, which would cascade down until all the rules were evaluated.</p> <p>I'm just wondering if this is a reasonable approach, or if my design and ideas are way totally out of whack? Unfortunately I never had the chance to take a compiler design course or anything like that in Unviersity so I'm pretty much coming up with this stuff of my own accord.</p> <p>Could someone with some experience in these kinds of things please chime in and evaluate the idea?</p> <p><strong>EDIT:</strong> Some good answers so far, here's a bit of clarification.</p> <p>The aim of the program is to collect log messages from servers on the network and store them in the database. Apart from the collection of log messages, the collector will define a set of rules that will either match or ignore messages depending on the conditions and flag an alert if necessary.</p> <p>I can't see the rules being of more than a moderate complexity, and they will be applied in a chain (list) until either a matching alert or ignore rule is hit. However, this part isn't quite as relevant to the question.</p> <p>As far the syntax being close to Python syntax, yes that is true, however I think it would be difficult to filter the Python down to the point where the user couldn't inadvertently do some crazy stuff with the rules that was not intended.</p>
16
2009-01-22T01:11:24Z
467,906
<p>It's a little hard to answer the question without knowing what the scope of the application is.</p> <ul> <li>What are you trying to reason about?</li> <li>What level of analysis are you talking about?</li> <li>How complicated do you see the rules becoming?</li> <li>How complicated is the interplay between different rules?</li> </ul> <p>On one end of the spectrum is a simple one-off approach like you have proposed. This is fine if the rules are few, relatively simple, and you're not doing anything more complicated than aggregating log messages that match the specified rules.</p> <p>On the other side of the spectrum is a heavy-weight reasoning system, something like <a href="http://en.wikipedia.org/wiki/CLIPS" rel="nofollow">CLIPS</a> that has a <a href="http://pyclips.sourceforge.net/web/" rel="nofollow">Python interface</a>. This is a real rules engine with inferencing and offers the ability to do sophisticated reasoning. If you're building something like a diagnostic engine that operates off of a program log this could be more appropriate.</p> <p><strong>EDIT:</strong></p> <p>I would say that the current implementation idea is fine for what you're doing. Anything much more and I think you probably run the risk of over-engineering the solution. It seems to capture what you want, matching on the log messages just based on a few different criteria.</p>
0
2009-01-22T02:56:07Z
[ "python", "parsing", "rules" ]
Implementing a "rules engine" in Python
467,738
<p>I'm writing a log collection / analysis application in Python and I need to write a "rules engine" to match and act on log messages.</p> <p>It needs to feature:</p> <ul> <li>Regular expression matching for the message itself</li> <li>Arithmetic comparisons for message severity/priority</li> <li>Boolean operators</li> </ul> <p>I envision An example rule would probably be something like:</p> <pre><code>(message ~ "program\\[\d+\\]: message" and severity &gt;= high) or (severity &gt;= critical) </code></pre> <p>I'm thinking about using <a href="http://pyparsing.wikispaces.com/">PyParsing</a> or similar to actually parse the rules and construct the parse tree.</p> <p>The current (not yet implemented) design I have in mind is to have classes for each rule type, and construct and chain them together according to the parse tree. Then each rule would have a "matches" method that could take a message object return whether or not it matches the rule.</p> <p>Very quickly, something like:</p> <pre><code>class RegexRule(Rule): def __init__(self, regex): self.regex = regex def match(self, message): return self.regex.match(message.contents) class SeverityRule(Rule): def __init__(self, operator, severity): self.operator = operator def match(self, message): if operator == "&gt;=": return message.severity &gt;= severity # more conditions here... class BooleanAndRule(Rule): def __init__(self, rule1, rule2): self.rule1 = rule1 self.rule2 = rule2 def match(self, message): return self.rule1.match(message) and self.rule2.match(message) </code></pre> <p>These rule classes would then be chained together according to the parse tree of the message, and the match() method called on the top rule, which would cascade down until all the rules were evaluated.</p> <p>I'm just wondering if this is a reasonable approach, or if my design and ideas are way totally out of whack? Unfortunately I never had the chance to take a compiler design course or anything like that in Unviersity so I'm pretty much coming up with this stuff of my own accord.</p> <p>Could someone with some experience in these kinds of things please chime in and evaluate the idea?</p> <p><strong>EDIT:</strong> Some good answers so far, here's a bit of clarification.</p> <p>The aim of the program is to collect log messages from servers on the network and store them in the database. Apart from the collection of log messages, the collector will define a set of rules that will either match or ignore messages depending on the conditions and flag an alert if necessary.</p> <p>I can't see the rules being of more than a moderate complexity, and they will be applied in a chain (list) until either a matching alert or ignore rule is hit. However, this part isn't quite as relevant to the question.</p> <p>As far the syntax being close to Python syntax, yes that is true, however I think it would be difficult to filter the Python down to the point where the user couldn't inadvertently do some crazy stuff with the rules that was not intended.</p>
16
2009-01-22T01:11:24Z
468,737
<p>Do not invent yet another rules language.</p> <p>Either use Python or use some other existing, already debugged and working language like BPEL.</p> <p>Just write your rules in Python, import them and execute them. Life is simpler, far easier to debug, and you've actually solved the actual log-reading problem without creating another problem.</p> <p>Imagine this scenario. Your program breaks. It's now either the rule parsing, the rule execution, or the rule itself. You must debug all three. If you wrote the rule in Python, it would be the rule, and that would be that.</p> <p>"I think it would be difficult to filter the Python down to the point where the user couldn't inadvertently do some crazy stuff with the rules that was not intended."</p> <p>This is largely the "I want to write a compiler" argument. </p> <p>1) You're the primary user. You'll write, debug and maintain the rules. Are there really armies of crazy programmers who will be doing crazy things? Really? If there is any potential crazy user, <em>talk to them</em>. Teach Them. Don't fight against them by inventing a new language (which you will then have to maintain and debug forever.)</p> <p>2) It's just log processing. There's no real cost to the <em>craziness</em>. No one is going to subvert the world economic system with faulty log handling. Don't make a small task with a few dozen lines of Python onto a 1000 line interpreter to interpret a few dozen lines of some rule language. Just write the few dozen lines of Python.</p> <p>Just write it in Python as quickly and clearly as you can and move on to the next project.</p>
52
2009-01-22T11:22:15Z
[ "python", "parsing", "rules" ]
Implementing a "rules engine" in Python
467,738
<p>I'm writing a log collection / analysis application in Python and I need to write a "rules engine" to match and act on log messages.</p> <p>It needs to feature:</p> <ul> <li>Regular expression matching for the message itself</li> <li>Arithmetic comparisons for message severity/priority</li> <li>Boolean operators</li> </ul> <p>I envision An example rule would probably be something like:</p> <pre><code>(message ~ "program\\[\d+\\]: message" and severity &gt;= high) or (severity &gt;= critical) </code></pre> <p>I'm thinking about using <a href="http://pyparsing.wikispaces.com/">PyParsing</a> or similar to actually parse the rules and construct the parse tree.</p> <p>The current (not yet implemented) design I have in mind is to have classes for each rule type, and construct and chain them together according to the parse tree. Then each rule would have a "matches" method that could take a message object return whether or not it matches the rule.</p> <p>Very quickly, something like:</p> <pre><code>class RegexRule(Rule): def __init__(self, regex): self.regex = regex def match(self, message): return self.regex.match(message.contents) class SeverityRule(Rule): def __init__(self, operator, severity): self.operator = operator def match(self, message): if operator == "&gt;=": return message.severity &gt;= severity # more conditions here... class BooleanAndRule(Rule): def __init__(self, rule1, rule2): self.rule1 = rule1 self.rule2 = rule2 def match(self, message): return self.rule1.match(message) and self.rule2.match(message) </code></pre> <p>These rule classes would then be chained together according to the parse tree of the message, and the match() method called on the top rule, which would cascade down until all the rules were evaluated.</p> <p>I'm just wondering if this is a reasonable approach, or if my design and ideas are way totally out of whack? Unfortunately I never had the chance to take a compiler design course or anything like that in Unviersity so I'm pretty much coming up with this stuff of my own accord.</p> <p>Could someone with some experience in these kinds of things please chime in and evaluate the idea?</p> <p><strong>EDIT:</strong> Some good answers so far, here's a bit of clarification.</p> <p>The aim of the program is to collect log messages from servers on the network and store them in the database. Apart from the collection of log messages, the collector will define a set of rules that will either match or ignore messages depending on the conditions and flag an alert if necessary.</p> <p>I can't see the rules being of more than a moderate complexity, and they will be applied in a chain (list) until either a matching alert or ignore rule is hit. However, this part isn't quite as relevant to the question.</p> <p>As far the syntax being close to Python syntax, yes that is true, however I think it would be difficult to filter the Python down to the point where the user couldn't inadvertently do some crazy stuff with the rules that was not intended.</p>
16
2009-01-22T01:11:24Z
1,925,675
<p>You might also want to look at <a href="http://pyke.sourceforge.net/logic%5Fprogramming/index.html">PyKE</a>.</p>
5
2009-12-18T01:07:25Z
[ "python", "parsing", "rules" ]
Implementing a "rules engine" in Python
467,738
<p>I'm writing a log collection / analysis application in Python and I need to write a "rules engine" to match and act on log messages.</p> <p>It needs to feature:</p> <ul> <li>Regular expression matching for the message itself</li> <li>Arithmetic comparisons for message severity/priority</li> <li>Boolean operators</li> </ul> <p>I envision An example rule would probably be something like:</p> <pre><code>(message ~ "program\\[\d+\\]: message" and severity &gt;= high) or (severity &gt;= critical) </code></pre> <p>I'm thinking about using <a href="http://pyparsing.wikispaces.com/">PyParsing</a> or similar to actually parse the rules and construct the parse tree.</p> <p>The current (not yet implemented) design I have in mind is to have classes for each rule type, and construct and chain them together according to the parse tree. Then each rule would have a "matches" method that could take a message object return whether or not it matches the rule.</p> <p>Very quickly, something like:</p> <pre><code>class RegexRule(Rule): def __init__(self, regex): self.regex = regex def match(self, message): return self.regex.match(message.contents) class SeverityRule(Rule): def __init__(self, operator, severity): self.operator = operator def match(self, message): if operator == "&gt;=": return message.severity &gt;= severity # more conditions here... class BooleanAndRule(Rule): def __init__(self, rule1, rule2): self.rule1 = rule1 self.rule2 = rule2 def match(self, message): return self.rule1.match(message) and self.rule2.match(message) </code></pre> <p>These rule classes would then be chained together according to the parse tree of the message, and the match() method called on the top rule, which would cascade down until all the rules were evaluated.</p> <p>I'm just wondering if this is a reasonable approach, or if my design and ideas are way totally out of whack? Unfortunately I never had the chance to take a compiler design course or anything like that in Unviersity so I'm pretty much coming up with this stuff of my own accord.</p> <p>Could someone with some experience in these kinds of things please chime in and evaluate the idea?</p> <p><strong>EDIT:</strong> Some good answers so far, here's a bit of clarification.</p> <p>The aim of the program is to collect log messages from servers on the network and store them in the database. Apart from the collection of log messages, the collector will define a set of rules that will either match or ignore messages depending on the conditions and flag an alert if necessary.</p> <p>I can't see the rules being of more than a moderate complexity, and they will be applied in a chain (list) until either a matching alert or ignore rule is hit. However, this part isn't quite as relevant to the question.</p> <p>As far the syntax being close to Python syntax, yes that is true, however I think it would be difficult to filter the Python down to the point where the user couldn't inadvertently do some crazy stuff with the rules that was not intended.</p>
16
2009-01-22T01:11:24Z
19,260,664
<p>Have you considered NebriOS? We just released this tool after building it for our own purposes. It's a <strong>pure Python/Django rules engine</strong>. We actually use it for workflow tasks, but it's generic enough to help your in your situation. You would need to connect to the remote DB and run the rules against it. </p> <p>The Python you wrote would end up being more than one rule in the system. Here's one for example:</p> <pre><code>class SeverityRule(NebriOS): # add listener or timer here check(self): if operator == "&gt;=" return message.severity &gt;= severity # any number of checks here action(self): csv.append(message.severity, datetime.now) send_email([email protected], """Severity level alert: {{message.severity}}""") </code></pre> <p>Check it out at <a href="http://nebrios.com" rel="nofollow">http://nebrios.com</a>. I didn't realize how much there was to building a rules engine application like Nebri until after my team started. It was a HUGE task that goes much deeper that it seems. ACL, queues, forms, KVPS's, efficient checks, useful errors, email parsing, dynamic forms, and the list goes on. </p>
1
2013-10-09T00:00:33Z
[ "python", "parsing", "rules" ]
Is there a Perl equivalent of Python's re.findall/re.finditer (iterative regex results)?
467,800
<p>In Python compiled regex patterns <a href="http://docs.python.org/library/re.html#re.findall">have a <code>findall</code> method</a> that does the following:</p> <blockquote> <p>Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match.</p> </blockquote> <p>What's the canonical way of doing this in Perl? A naive algorithm I can think of is along the lines of "while a search and replace with the empty string is successful, do [suite]". I'm hoping there's a nicer way. :-)</p> <p>Thanks in advance!</p>
6
2009-01-22T01:52:54Z
467,820
<p>Use the <code>/g</code> modifier in your match. From the <code>perlop</code> manual:</p> <blockquote> <p>The "<code>/g</code>" modifier specifies global pattern matching--that is, matching as many times as possible within the string. How it behaves depends on the context. In list context, it returns a list of the substrings matched by any capturing parentheses in the regular expression. If there are no parentheses, it returns a list of all the matched strings, as if there were parentheses around the whole pattern.</p> <p>In scalar context, each execution of "<code>m//g</code>" finds the next match, returning true if it matches, and false if there is no further match. The position after the last match can be read or set using the <code>pos()</code> function; see "<code>pos</code>" in <code>perlfunc</code>. A failed match normally resets the search position to the beginning of the string, but you can avoid that by adding the "<code>/c</code>" modifier (e.g. "<code>m//gc</code>"). Modifying the target string also resets the search position.</p> </blockquote>
13
2009-01-22T02:04:14Z
[ "python", "regex", "perl", "iterator" ]
Is there a Perl equivalent of Python's re.findall/re.finditer (iterative regex results)?
467,800
<p>In Python compiled regex patterns <a href="http://docs.python.org/library/re.html#re.findall">have a <code>findall</code> method</a> that does the following:</p> <blockquote> <p>Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match.</p> </blockquote> <p>What's the canonical way of doing this in Perl? A naive algorithm I can think of is along the lines of "while a search and replace with the empty string is successful, do [suite]". I'm hoping there's a nicer way. :-)</p> <p>Thanks in advance!</p>
6
2009-01-22T01:52:54Z
467,874
<p>To build on Chris' response, it's probably most relevant to encase the <code>//g</code> regex in a <code>while</code> loop, like:</p> <pre><code>my @matches; while ( 'foobarbaz' =~ m/([aeiou])/g ) { push @matches, $1; } </code></pre> <p>Pasting some quick Python I/O:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; re.findall(r'([aeiou])([nrs])','I had a sandwich for lunch') [('a', 'n'), ('o', 'r'), ('u', 'n')] </code></pre> <p>To get something comparable in Perl, the construct could be something like:</p> <pre><code>my $matches = []; while ( 'I had a sandwich for lunch' =~ m/([aeiou])([nrs])/g ) { push @$matches, [$1,$2]; } </code></pre> <p>But in general, whatever function you're iterating for, you can probably do within the <code>while</code> loop itself.</p>
7
2009-01-22T02:35:09Z
[ "python", "regex", "perl", "iterator" ]
Is there a Perl equivalent of Python's re.findall/re.finditer (iterative regex results)?
467,800
<p>In Python compiled regex patterns <a href="http://docs.python.org/library/re.html#re.findall">have a <code>findall</code> method</a> that does the following:</p> <blockquote> <p>Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match.</p> </blockquote> <p>What's the canonical way of doing this in Perl? A naive algorithm I can think of is along the lines of "while a search and replace with the empty string is successful, do [suite]". I'm hoping there's a nicer way. :-)</p> <p>Thanks in advance!</p>
6
2009-01-22T01:52:54Z
467,877
<p>Nice beginner reference with similar content to <a href="http://stackoverflow.com/questions/467800/is-there-a-perl-equivalent-of-pythons-re-findall-re-finditer-iterative-regex-re#467874">@kyle</a>'s answer: <a href="http://perldoc.perl.org/perlretut.html#Using-regular-expressions-in-Perl" rel="nofollow">Perl Tutorial: Using regular expressions</a></p>
2
2009-01-22T02:36:28Z
[ "python", "regex", "perl", "iterator" ]
Permutations in python, with a twist
467,878
<p>I have a list of objects (for the sake of example, let's say 5). I want a list of some of the possible permutations. Specifically, given that some pairs are not together, and some triples don't make sandwiches, how can I generate all other permutations? I realize that I generate all of them first and check that they work, but I think it would be faster to not even consider the pairs and triples that don't work.</p> <p>Am I wrong that it would be faster to check first and generate later?</p> <p>How would I do it?</p>
1
2009-01-22T02:38:17Z
467,928
<p>You would have to find an algorithm that cuts off more than one unwanted permutation after a single check, in order to gain anything. The obvious strategy is to build the permutations sequentially, for example, in a tree. Each cut then eliminates a whole branch.</p> <p><em>edit:</em><br /> Example: in the set (A B C D), let's say that B and C, and A and D are not allowed to be neighbours.</p> <pre> (A) (B) (C) (D) / | \ / | \ / | \ / | \ AB AC AD BA BC BD CA CB CD DA DB DC | \ | \ X / \ X / \ / \ X / \ X / \ / \ ABC ABD ACB ACD BAC BAD BDA BDC CAB CAD CDA CDB DBA DBC DCA DCB X | X | | X X | | X X | | X | X ABDC ACDB BACD BDCA CABD CDBA DBAC DCAB v v v v v v v v </pre> <p>Each of the strings without parentheses needs a check. As you see, the Xs (where subtrees have been cut off) save checks, one if they are in the third row, but four if they are in the second row. We saved 24 of 60 checks here and got down to 36. However, there are only 24 permutations overall anyway, so if checking the restrictions (as opposed to building the lists) is the bottleneck, we would have been better off to just construct all the permutations and check them at the end... IF the checks couldn't be optimized when we go this way.</p> <p>Now, as you see, the checks only need to be performed on the new part of each list. This makes the checks much leaner; actually, we divide the check that would be needed for a full permutation into small chunks. In the above example, we only have to look whether the added letter is allowed to stand besides the last one, not all the letters before.</p> <p>However, also if we first construct, then filter, the checks could be cut short as soon as a no-no is encountered. So, on checking, there is no real gain compared to the first-build-then-filter algorithm; there is rather the danger of further overhead through more function calls.</p> <p>What we do save is the time to build the lists, and the peak memory consumption. Building a list is generally rather fast, but peak memory consumption might be a consideration if the number of object gets larger. For the first-build-then-filter, both grow linearly with the number of objects. For the tree version, it grows slower, depending on the constraints. From a certain number of objects and rules on, there is also actual check saving.</p> <p>In general, I think that you would need to try it out and time the two algorithms. If you really have only 5 objects, stick to the simple <code>(filter rules (build-permutations set))</code>. If your number of objects gets large, the tree algorithm will at some point perform noticably better (you know, big O).</p> <p>Um. Sorry, I got into lecture mode; bear with me.</p>
5
2009-01-22T03:09:38Z
[ "python" ]
In what situation should the built-in 'operator' module be used in python?
467,920
<p>I'm speaking of this module: <a href="http://docs.python.org/library/operator.html">http://docs.python.org/library/operator.html</a></p> <p>From the article:</p> <blockquote> <p>The operator module exports a set of functions implemented in C corresponding to the intrinsic operators of Python. For example, operator.add(x, y) is equivalent to the expression x+y. The function names are those used for special class methods; variants without leading and trailing __ are also provided for convenience.</p> </blockquote> <p>I'm not sure I understand the benefit or purpose of this module.</p>
21
2009-01-22T03:03:46Z
467,937
<p>One example is in the use of the <code>reduce()</code> function:</p> <pre><code>&gt;&gt;&gt; import operator &gt;&gt;&gt; a = [2, 3, 4, 5] &gt;&gt;&gt; reduce(lambda x, y: x + y, a) 14 &gt;&gt;&gt; reduce(operator.add, a) 14 </code></pre>
16
2009-01-22T03:15:07Z
[ "python", "operators" ]
In what situation should the built-in 'operator' module be used in python?
467,920
<p>I'm speaking of this module: <a href="http://docs.python.org/library/operator.html">http://docs.python.org/library/operator.html</a></p> <p>From the article:</p> <blockquote> <p>The operator module exports a set of functions implemented in C corresponding to the intrinsic operators of Python. For example, operator.add(x, y) is equivalent to the expression x+y. The function names are those used for special class methods; variants without leading and trailing __ are also provided for convenience.</p> </blockquote> <p>I'm not sure I understand the benefit or purpose of this module.</p>
21
2009-01-22T03:03:46Z
467,945
<p>Possibly the most popular usage is operator.itemgetter. Given a list <code>lst</code> of tuples, you can sort by the ith element by: <code>lst.sort(key=operator.itemgetter(i))</code></p> <p>Certainly, you could do the same thing without operator by defining your own key function, but the operator module makes it slightly neater.</p> <p>As to the rest, python allows a functional style of programming, and so it can come up -- for instance, Greg's reduce example.</p> <p>You might argue: "Why do I need <code>operator.add</code> when I can just do: <code>add = lambda x, y: x+y</code>?" The answers are:</p> <ol> <li><code>operator.add</code> is (I think) slightly faster.</li> <li>It makes the code easier to understand for you, or another person later, looking at it. They don't need to look for the definition of add, because they know what the operator module does.</li> </ol>
22
2009-01-22T03:19:40Z
[ "python", "operators" ]
Sample a running Python app
467,925
<p>I'm used to sampling C-based apps, which every few milliseconds sees what function stack is being called at that moment.</p> <p>This allows me to see where most of the time is spent in an app so I can optimize it.</p> <p>When using python, however, sample isn't so helpful, since it's sampling the C functions of the python interpreter, not the python code itself.</p> <p>Is there a useful sampling tool for python?</p>
3
2009-01-22T03:07:25Z
467,932
<p>Python includes a built-in set of <a href="http://docs.python.org/library/profile.html" rel="nofollow">profiling tools</a>. In particular, you can run cProfile on an arbitrary python script from the command-line:</p> <pre><code>$ python -m cProfile myscript.py </code></pre> <p>Much more elaborate usage is available by calling the API directly. Note that the cProfile module was added in Python 2.5. In earlier versions, you can use the pure-Python, but slower "profile" module.</p>
4
2009-01-22T03:11:30Z
[ "python", "performance", "sample" ]
Adding a generic image field onto a ModelForm in django
467,985
<p>I have two models, <code>Room</code> and <code>Image</code>. <code>Image</code> is a generic model that can tack onto any other model. I want to give users a form to upload an image when they post information about a room. I've written code that works, but I'm afraid I've done it the hard way, and specifically in a way that violates DRY.</p> <p>Was hoping someone who's a little more familiar with django forms could point out where I've gone wrong. </p> <p><strong>Update:</strong></p> <p>I've tried to clarify why I chose this design in comments to the current answers. To summarize: </p> <p>I didn't simply put an <code>ImageField</code> on the <code>Room</code> model because I wanted more than one image associated with the Room model. I chose a generic Image model because I wanted to add images to several different models. The alternatives I considered were were multiple foreign keys on a single <code>Image</code> class, which seemed messy, or multiple <code>Image</code> classes, which I thought would clutter my schema. I didn't make this clear in my first post, so sorry about that.</p> <p>Seeing as none of the answers so far has addressed how to make this a little more DRY I did come up with my own solution which was to add the upload path as a class attribute on the image model and reference that every time it's needed.</p> <pre><code># Models class Image(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') image = models.ImageField(_('Image'), height_field='', width_field='', upload_to='uploads/images', max_length=200) class Room(models.Model): name = models.CharField(max_length=50) image_set = generic.GenericRelation('Image') # The form class AddRoomForm(forms.ModelForm): image_1 = forms.ImageField() class Meta: model = Room # The view def handle_uploaded_file(f): # DRY violation, I've already specified the upload path in the image model upload_suffix = join('uploads/images', f.name) upload_path = join(settings.MEDIA_ROOT, upload_suffix) destination = open(upload_path, 'wb+') for chunk in f.chunks(): destination.write(chunk) destination.close() return upload_suffix def add_room(request, apartment_id, form_class=AddRoomForm, template='apartments/add_room.html'): apartment = Apartment.objects.get(id=apartment_id) if request.method == 'POST': form = form_class(request.POST, request.FILES) if form.is_valid(): room = form.save() image_1 = form.cleaned_data['image_1'] # Instead of writing a special function to handle the image, # shouldn't I just be able to pass it straight into Image.objects.create # ...but it doesn't seem to work for some reason, wrong syntax perhaps? upload_path = handle_uploaded_file(image_1) image = Image.objects.create(content_object=room, image=upload_path) return HttpResponseRedirect(room.get_absolute_url()) else: form = form_class() context = {'form': form, } return direct_to_template(request, template, extra_context=context) </code></pre>
2
2009-01-22T03:45:49Z
468,787
<p>Why don't you do just use a ImageField? I don't see the need for the "Image" class.</p> <pre><code># model class Room(models.Model): name = models.CharField(max_length=50) image = models.ImageField(upload_to="uploads/images/") # form from django import forms class UploadFileForm(forms.Form): name = forms.CharField(max_length=50) image = forms.FileField() </code></pre> <p>Take a look at <a href="http://docs.djangoproject.com/en/dev/topics/http/file-uploads/#basic-file-uploads" rel="nofollow">Basic file uploads</a> and <a href="http://docs.djangoproject.com/en/dev/faq/usage/#how-do-i-use-image-and-file-fields" rel="nofollow">How do I use image and file fields?</a></p>
4
2009-01-22T11:39:09Z
[ "python", "django", "django-forms" ]
Adding a generic image field onto a ModelForm in django
467,985
<p>I have two models, <code>Room</code> and <code>Image</code>. <code>Image</code> is a generic model that can tack onto any other model. I want to give users a form to upload an image when they post information about a room. I've written code that works, but I'm afraid I've done it the hard way, and specifically in a way that violates DRY.</p> <p>Was hoping someone who's a little more familiar with django forms could point out where I've gone wrong. </p> <p><strong>Update:</strong></p> <p>I've tried to clarify why I chose this design in comments to the current answers. To summarize: </p> <p>I didn't simply put an <code>ImageField</code> on the <code>Room</code> model because I wanted more than one image associated with the Room model. I chose a generic Image model because I wanted to add images to several different models. The alternatives I considered were were multiple foreign keys on a single <code>Image</code> class, which seemed messy, or multiple <code>Image</code> classes, which I thought would clutter my schema. I didn't make this clear in my first post, so sorry about that.</p> <p>Seeing as none of the answers so far has addressed how to make this a little more DRY I did come up with my own solution which was to add the upload path as a class attribute on the image model and reference that every time it's needed.</p> <pre><code># Models class Image(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') image = models.ImageField(_('Image'), height_field='', width_field='', upload_to='uploads/images', max_length=200) class Room(models.Model): name = models.CharField(max_length=50) image_set = generic.GenericRelation('Image') # The form class AddRoomForm(forms.ModelForm): image_1 = forms.ImageField() class Meta: model = Room # The view def handle_uploaded_file(f): # DRY violation, I've already specified the upload path in the image model upload_suffix = join('uploads/images', f.name) upload_path = join(settings.MEDIA_ROOT, upload_suffix) destination = open(upload_path, 'wb+') for chunk in f.chunks(): destination.write(chunk) destination.close() return upload_suffix def add_room(request, apartment_id, form_class=AddRoomForm, template='apartments/add_room.html'): apartment = Apartment.objects.get(id=apartment_id) if request.method == 'POST': form = form_class(request.POST, request.FILES) if form.is_valid(): room = form.save() image_1 = form.cleaned_data['image_1'] # Instead of writing a special function to handle the image, # shouldn't I just be able to pass it straight into Image.objects.create # ...but it doesn't seem to work for some reason, wrong syntax perhaps? upload_path = handle_uploaded_file(image_1) image = Image.objects.create(content_object=room, image=upload_path) return HttpResponseRedirect(room.get_absolute_url()) else: form = form_class() context = {'form': form, } return direct_to_template(request, template, extra_context=context) </code></pre>
2
2009-01-22T03:45:49Z
468,889
<p>You don't have to use the Image class. As <a href="http://stackoverflow.com/users/30300/dzpm">DZPM</a> suggested, convert the image field to an ImageField. You also need to make some changes to the view.</p> <p>Instead of using an upload handler, you can create a Image object with the uploaded data and attach the Image object to the Room object.</p> <p>To save the Image object you need to do something like this in the view:</p> <pre><code>from django.core.files.base import ContentFile if request.FILES.has_key('image_1'): image_obj = Image() image_obj.file.save(request.FILES['image_1'].name,\ ContentFile(request.FILES['image_1'].read())) image_obj.save() room_obj.image_set.create(image_obj) room_obj.save() </code></pre> <p>Also, I think instead of the GenericRelation, you should use a ManyToManyField, in which case the syntax for adding an Image to a Room will change slightly.</p>
1
2009-01-22T12:12:45Z
[ "python", "django", "django-forms" ]
Adding a generic image field onto a ModelForm in django
467,985
<p>I have two models, <code>Room</code> and <code>Image</code>. <code>Image</code> is a generic model that can tack onto any other model. I want to give users a form to upload an image when they post information about a room. I've written code that works, but I'm afraid I've done it the hard way, and specifically in a way that violates DRY.</p> <p>Was hoping someone who's a little more familiar with django forms could point out where I've gone wrong. </p> <p><strong>Update:</strong></p> <p>I've tried to clarify why I chose this design in comments to the current answers. To summarize: </p> <p>I didn't simply put an <code>ImageField</code> on the <code>Room</code> model because I wanted more than one image associated with the Room model. I chose a generic Image model because I wanted to add images to several different models. The alternatives I considered were were multiple foreign keys on a single <code>Image</code> class, which seemed messy, or multiple <code>Image</code> classes, which I thought would clutter my schema. I didn't make this clear in my first post, so sorry about that.</p> <p>Seeing as none of the answers so far has addressed how to make this a little more DRY I did come up with my own solution which was to add the upload path as a class attribute on the image model and reference that every time it's needed.</p> <pre><code># Models class Image(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') image = models.ImageField(_('Image'), height_field='', width_field='', upload_to='uploads/images', max_length=200) class Room(models.Model): name = models.CharField(max_length=50) image_set = generic.GenericRelation('Image') # The form class AddRoomForm(forms.ModelForm): image_1 = forms.ImageField() class Meta: model = Room # The view def handle_uploaded_file(f): # DRY violation, I've already specified the upload path in the image model upload_suffix = join('uploads/images', f.name) upload_path = join(settings.MEDIA_ROOT, upload_suffix) destination = open(upload_path, 'wb+') for chunk in f.chunks(): destination.write(chunk) destination.close() return upload_suffix def add_room(request, apartment_id, form_class=AddRoomForm, template='apartments/add_room.html'): apartment = Apartment.objects.get(id=apartment_id) if request.method == 'POST': form = form_class(request.POST, request.FILES) if form.is_valid(): room = form.save() image_1 = form.cleaned_data['image_1'] # Instead of writing a special function to handle the image, # shouldn't I just be able to pass it straight into Image.objects.create # ...but it doesn't seem to work for some reason, wrong syntax perhaps? upload_path = handle_uploaded_file(image_1) image = Image.objects.create(content_object=room, image=upload_path) return HttpResponseRedirect(room.get_absolute_url()) else: form = form_class() context = {'form': form, } return direct_to_template(request, template, extra_context=context) </code></pre>
2
2009-01-22T03:45:49Z
531,471
<p>What about using two forms on the page: one for the room and one for the image?</p> <p>You'll just have to make the generic foreign key fields of the image form not required, and fill in their values in the view after saving the room.</p>
0
2009-02-10T08:28:03Z
[ "python", "django", "django-forms" ]
Adding a generic image field onto a ModelForm in django
467,985
<p>I have two models, <code>Room</code> and <code>Image</code>. <code>Image</code> is a generic model that can tack onto any other model. I want to give users a form to upload an image when they post information about a room. I've written code that works, but I'm afraid I've done it the hard way, and specifically in a way that violates DRY.</p> <p>Was hoping someone who's a little more familiar with django forms could point out where I've gone wrong. </p> <p><strong>Update:</strong></p> <p>I've tried to clarify why I chose this design in comments to the current answers. To summarize: </p> <p>I didn't simply put an <code>ImageField</code> on the <code>Room</code> model because I wanted more than one image associated with the Room model. I chose a generic Image model because I wanted to add images to several different models. The alternatives I considered were were multiple foreign keys on a single <code>Image</code> class, which seemed messy, or multiple <code>Image</code> classes, which I thought would clutter my schema. I didn't make this clear in my first post, so sorry about that.</p> <p>Seeing as none of the answers so far has addressed how to make this a little more DRY I did come up with my own solution which was to add the upload path as a class attribute on the image model and reference that every time it's needed.</p> <pre><code># Models class Image(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') image = models.ImageField(_('Image'), height_field='', width_field='', upload_to='uploads/images', max_length=200) class Room(models.Model): name = models.CharField(max_length=50) image_set = generic.GenericRelation('Image') # The form class AddRoomForm(forms.ModelForm): image_1 = forms.ImageField() class Meta: model = Room # The view def handle_uploaded_file(f): # DRY violation, I've already specified the upload path in the image model upload_suffix = join('uploads/images', f.name) upload_path = join(settings.MEDIA_ROOT, upload_suffix) destination = open(upload_path, 'wb+') for chunk in f.chunks(): destination.write(chunk) destination.close() return upload_suffix def add_room(request, apartment_id, form_class=AddRoomForm, template='apartments/add_room.html'): apartment = Apartment.objects.get(id=apartment_id) if request.method == 'POST': form = form_class(request.POST, request.FILES) if form.is_valid(): room = form.save() image_1 = form.cleaned_data['image_1'] # Instead of writing a special function to handle the image, # shouldn't I just be able to pass it straight into Image.objects.create # ...but it doesn't seem to work for some reason, wrong syntax perhaps? upload_path = handle_uploaded_file(image_1) image = Image.objects.create(content_object=room, image=upload_path) return HttpResponseRedirect(room.get_absolute_url()) else: form = form_class() context = {'form': form, } return direct_to_template(request, template, extra_context=context) </code></pre>
2
2009-01-22T03:45:49Z
531,501
<p>Django does support your use case at least up to a point:</p> <ul> <li>formsets display repeated forms</li> <li>model formsets handle repeated model forms</li> <li>inline formsets bind model formsets to related objects of an instance</li> <li><em>generic inline formsets</em> do the same for generic relations</li> </ul> <p>Generic inline formsets were introduced in <a href="http://code.djangoproject.com/changeset/8279" rel="nofollow">changeset [8279]</a>. See <a href="http://code.djangoproject.com/changeset/8279#file4" rel="nofollow">the changes to unit tests</a> to see how they are used.</p> <p>With generic inline formsets you'll also be able to display multiple already saved images for existing rooms in your form.</p> <p>Inline formsets seem to expect an existing parent instance in the <code>instance=</code> argument. The admin interface does let you fill in inlines before saving the parent instance, so there must be a way to achieve that. I've just never tried that myself.</p>
0
2009-02-10T08:38:50Z
[ "python", "django", "django-forms" ]
Adding a generic image field onto a ModelForm in django
467,985
<p>I have two models, <code>Room</code> and <code>Image</code>. <code>Image</code> is a generic model that can tack onto any other model. I want to give users a form to upload an image when they post information about a room. I've written code that works, but I'm afraid I've done it the hard way, and specifically in a way that violates DRY.</p> <p>Was hoping someone who's a little more familiar with django forms could point out where I've gone wrong. </p> <p><strong>Update:</strong></p> <p>I've tried to clarify why I chose this design in comments to the current answers. To summarize: </p> <p>I didn't simply put an <code>ImageField</code> on the <code>Room</code> model because I wanted more than one image associated with the Room model. I chose a generic Image model because I wanted to add images to several different models. The alternatives I considered were were multiple foreign keys on a single <code>Image</code> class, which seemed messy, or multiple <code>Image</code> classes, which I thought would clutter my schema. I didn't make this clear in my first post, so sorry about that.</p> <p>Seeing as none of the answers so far has addressed how to make this a little more DRY I did come up with my own solution which was to add the upload path as a class attribute on the image model and reference that every time it's needed.</p> <pre><code># Models class Image(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') image = models.ImageField(_('Image'), height_field='', width_field='', upload_to='uploads/images', max_length=200) class Room(models.Model): name = models.CharField(max_length=50) image_set = generic.GenericRelation('Image') # The form class AddRoomForm(forms.ModelForm): image_1 = forms.ImageField() class Meta: model = Room # The view def handle_uploaded_file(f): # DRY violation, I've already specified the upload path in the image model upload_suffix = join('uploads/images', f.name) upload_path = join(settings.MEDIA_ROOT, upload_suffix) destination = open(upload_path, 'wb+') for chunk in f.chunks(): destination.write(chunk) destination.close() return upload_suffix def add_room(request, apartment_id, form_class=AddRoomForm, template='apartments/add_room.html'): apartment = Apartment.objects.get(id=apartment_id) if request.method == 'POST': form = form_class(request.POST, request.FILES) if form.is_valid(): room = form.save() image_1 = form.cleaned_data['image_1'] # Instead of writing a special function to handle the image, # shouldn't I just be able to pass it straight into Image.objects.create # ...but it doesn't seem to work for some reason, wrong syntax perhaps? upload_path = handle_uploaded_file(image_1) image = Image.objects.create(content_object=room, image=upload_path) return HttpResponseRedirect(room.get_absolute_url()) else: form = form_class() context = {'form': form, } return direct_to_template(request, template, extra_context=context) </code></pre>
2
2009-01-22T03:45:49Z
549,978
<p>I found this page look for a solution to this same problem.</p> <p>Here is my info -- hopefully helps some.</p> <p>MODELS: Image, Review, Manufacturer, Profile</p> <p>I want Review, Manufacturer, Profile to have a relationship to the Image model. But you have to beable to have multiple Images per object. (Ie, One Review can have 5 images a different Review can have 3, etc)</p> <p>Originally I did a </p> <pre><code>images = ManyToManyField(Image) </code></pre> <p>in each of the other models. This works fine, but sucks for admin (combo select box). This may be a solution for you though. I dont like it for what I'm trying to do.</p> <p>The other thing I'm working on now is having multiple foreign keys.</p> <pre><code>class Image(models.Model): description = models.TextField(blank=True) image = models.ImageField(upload_to="media/") user_profile = models.ForeignKey(UserProfile) mfgr = models.ForeignKey(Manufacturer) review = models.ForeignKey(Review) </code></pre> <p>but like you said. This is pretty sloppy looking and I just dont like it.</p> <p>One other thing I just found but don't have my brain completely wrapped around (and not sure how transparent it is after implementation is Generic Relationships (or Generic Foreign Keys), which may be a solution. Well once I comprehend it all. Need more caffeine.</p> <p><a href="http://www.djangoproject.com/documentation/models/generic_relations/" rel="nofollow">http://www.djangoproject.com/documentation/models/generic_relations/</a></p> <p>Let me know if you get this sorted out or any of this helps. Thanks!</p> <p>Let me know if this helps or you have a different solutions.</p>
0
2009-02-14T23:26:50Z
[ "python", "django", "django-forms" ]