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
Using web.py as non blocking http-server
500,935
<p>while learning some basic programming with python, i found web.py. i got stuck with a stupid problem:</p> <p>i wrote a simple console app with a main loop that proccesses items from a queue in seperate threads. my goal is to use web.py to add items to my queue and report status of the queue via web request. i got this running as a module but can´t integrate it into my main app. my problem is when i start the http server with app.run() it blocks my main loop. also tried to start it with thread.start_new_thread but it still blocks. is there an easy way to run web.py´s integrated http server in the background within my app.</p> <p>in the likely event that i am a victim of a fundamental missunderstanding, any attempt to clarify my error in reasoning would help ;.) ( please bear with me, i am a beginner :-) </p>
14
2009-02-01T14:47:24Z
501,570
<p>Wouldn't is be simpler to re-write your main-loop code to be a function that you call over and over again, and then call that from the function that you pass to <code>runsimple</code>...</p> <p>It's guaranteed not to fully satisfy your requirements, but if you're in a rush, it might be easiest.</p>
1
2009-02-01T21:01:21Z
[ "python", "multithreading", "web-services", "web.py" ]
Using web.py as non blocking http-server
500,935
<p>while learning some basic programming with python, i found web.py. i got stuck with a stupid problem:</p> <p>i wrote a simple console app with a main loop that proccesses items from a queue in seperate threads. my goal is to use web.py to add items to my queue and report status of the queue via web request. i got this running as a module but can´t integrate it into my main app. my problem is when i start the http server with app.run() it blocks my main loop. also tried to start it with thread.start_new_thread but it still blocks. is there an easy way to run web.py´s integrated http server in the background within my app.</p> <p>in the likely event that i am a victim of a fundamental missunderstanding, any attempt to clarify my error in reasoning would help ;.) ( please bear with me, i am a beginner :-) </p>
14
2009-02-01T14:47:24Z
1,872,235
<p>or just use Tornado, a non-blocking webserver for Python that has an API similar to webpy - <a href="http://www.tornadoweb.org/" rel="nofollow">http://www.tornadoweb.org/</a></p>
1
2009-12-09T07:39:09Z
[ "python", "multithreading", "web-services", "web.py" ]
Using web.py as non blocking http-server
500,935
<p>while learning some basic programming with python, i found web.py. i got stuck with a stupid problem:</p> <p>i wrote a simple console app with a main loop that proccesses items from a queue in seperate threads. my goal is to use web.py to add items to my queue and report status of the queue via web request. i got this running as a module but can´t integrate it into my main app. my problem is when i start the http server with app.run() it blocks my main loop. also tried to start it with thread.start_new_thread but it still blocks. is there an easy way to run web.py´s integrated http server in the background within my app.</p> <p>in the likely event that i am a victim of a fundamental missunderstanding, any attempt to clarify my error in reasoning would help ;.) ( please bear with me, i am a beginner :-) </p>
14
2009-02-01T14:47:24Z
3,949,776
<p>I found a working solution. In a seperate module i create my webserver:</p> <pre><code>import web import threading class MyWebserver(threading.Thread): def run (self): urls = ('/', 'MyWebserver') app = web.application(urls, globals()) app.run() def POST ... </code></pre> <p>In the main programm i just call</p> <pre><code>MyWebserver().start() </code></pre> <p>and than go on with whatever i want while having the webserver working in the background.</p>
6
2010-10-16T16:42:00Z
[ "python", "multithreading", "web-services", "web.py" ]
Using web.py as non blocking http-server
500,935
<p>while learning some basic programming with python, i found web.py. i got stuck with a stupid problem:</p> <p>i wrote a simple console app with a main loop that proccesses items from a queue in seperate threads. my goal is to use web.py to add items to my queue and report status of the queue via web request. i got this running as a module but can´t integrate it into my main app. my problem is when i start the http server with app.run() it blocks my main loop. also tried to start it with thread.start_new_thread but it still blocks. is there an easy way to run web.py´s integrated http server in the background within my app.</p> <p>in the likely event that i am a victim of a fundamental missunderstanding, any attempt to clarify my error in reasoning would help ;.) ( please bear with me, i am a beginner :-) </p>
14
2009-02-01T14:47:24Z
4,382,828
<p>I have also recently used <a href="http://kr.github.com/beanstalkd/" rel="nofollow">Beanstalkd</a> to queue up tasks that will run in a separate thread. Your web.py handler just drops a job into a pipe and a completely separate script executes it. You could have any number of these, and you get the benefits of advanced queue control, etc..</p>
0
2010-12-07T23:39:22Z
[ "python", "multithreading", "web-services", "web.py" ]
Python + SQLite query to find entries that sit in a specified time slot
501,021
<p>I want to store a row in an SQLite 3 table for each booking in my diary.</p> <p>Each row will have a 'start time' and a 'end time'.</p> <p>Does any one know how I can query the table for an event at a given time?</p> <p>E.g. Return any rows that happen at say 10:30am</p> <p>Thanks </p>
1
2009-02-01T15:45:53Z
501,037
<p>SQLite3 doesn't have a datetime type, though it does have <a href="http://www.sqlite.org/lang_datefunc.html" rel="nofollow">date and time functions</a>.</p> <p>Typically you store dates and times in your database in something like ISO 8601 format: <code>YYYY-MM-DD HH:MM:SS</code>. Then datetimes sort lexicographically into time order.</p> <p>With your datetimes stored this way, you simply use text comparisons such as </p> <pre><code>SELECT * FROM tbl WHERE tbl.start = '2009-02-01 10:30:00' </code></pre> <p>or</p> <pre><code>SELECT * FROM tbl WHERE '2009-02-01 10:30:00' BETWEEN tbl.start AND tbl.end; </code></pre>
2
2009-02-01T15:53:22Z
[ "python", "sql", "sqlite" ]
list named with a function argument in python
501,027
<p>I get the feeling this is probably something I should know but I can't think of it right now. I'm trying to get a function to build a list where the name of the list is an argument given in the function;</p> <p>e.g.</p> <pre><code>def make_hand(deck, handname): handname = [] for c in range(5): handname.append(deck.pop()) return handname # deck being a list containing all the cards in a deck of cards earlier </code></pre> <p>The issue is that this creates a list called handname when i want it to be called whatever the user enters as handname when creating the hand.</p> <p>Anyone can help? thanks</p>
1
2009-02-01T15:48:34Z
501,041
<p>You can keep a dictionary where the keys are the name of the hand and the values are the list. </p> <p>Then you can just say dictionary[handname] to access a particular hand. Along the lines of:</p> <pre><code>hands = {} # Create a new dictionary to hold the hands. hands["flush"] = make_hand(deck) # Generate some hands using your function. hands["straight"] = make_hand(deck) # Generate another hand with a different name. print hands["flush"] # Access the hand later. </code></pre>
6
2009-02-01T15:55:08Z
[ "python", "list", "arguments" ]
list named with a function argument in python
501,027
<p>I get the feeling this is probably something I should know but I can't think of it right now. I'm trying to get a function to build a list where the name of the list is an argument given in the function;</p> <p>e.g.</p> <pre><code>def make_hand(deck, handname): handname = [] for c in range(5): handname.append(deck.pop()) return handname # deck being a list containing all the cards in a deck of cards earlier </code></pre> <p>The issue is that this creates a list called handname when i want it to be called whatever the user enters as handname when creating the hand.</p> <p>Anyone can help? thanks</p>
1
2009-02-01T15:48:34Z
501,061
<p>While you can create variables with arbitrary names at runtime, using <code>exec</code> (as sykora suggested), or by meddlings with <code>locals</code>, <code>globals</code> or <code>setattr</code> on objects, your question is somewhat moot.</p> <p>An object (just about anything, from integers to classes with 1000 members) is just a chunk of memory. It does not have <em>a</em> name, it can have arbitrarily many names, and all names are treated equal: they just introduce a reference to some object and prevent it from being collected.</p> <p>If you want to name items in the sense that a user of your program gives a user-visible name to an object, you should use a dictionary to associated objects with names.</p> <p>Your approach of user-supplied variable names has several other severe implications: * what if the user supplies the name of an existing variable? * what if the user supplies an invalid name?</p> <p>You're introducing a <a href="http://www.joelonsoftware.com/articles/LeakyAbstractions.html" rel="nofollow">leaky abstraction</a>, so unless it is really, really important for the purpose of your program that the user can specify a new variable name, the user should not have to worry about how you store your objects - an not be presented with seemingly strange restrictions.</p>
2
2009-02-01T16:05:21Z
[ "python", "list", "arguments" ]
XMP image tagging and Python
501,087
<p>If I were to tag a bunch of images via XMP, in Python, what would be the best way? I've used Perl's <strong>Image::ExifTool</strong> and I am very much used to its reliability. I mean the thing never bricked on tens of thousands of images.</p> <p>I found <a href="http://code.google.com/p/python-xmp-toolkit/" rel="nofollow">this</a>, backed by some heavy-hitters like the European Space Agency, but it's clearly marked as unstable.</p> <p>Now, assuming I am comfortable with C++, how easy is it to, say, use the <a href="http://www.adobe.com/devnet/xmp/" rel="nofollow">Adobe XMP toolkit</a> directly, in Python? Having never done this before, I am not sure what I'd sign up for.</p> <p><strong>Update:</strong> I tried some libraries out there and, including the fore mentioned toolkit, they are still pretty immature and have glaring problems. I resorted to actually writing an Perl-based server that accepts XML requests to read and write metadata, with the combat-tested Image::EXIF. The amount of code is actually very light, and definitely beats torturing yourself by trying to get the Python libraries to work. The server solution is language-agnostic, so it's a twofer. </p>
2
2009-02-01T16:28:14Z
501,120
<p>Well, they website says that the python-xmp-toolkit uses Exempi, which is based on the Adobe XMP toolkit, via ctypes. What I'm trying to say is that you're not likely to create a better wrapping of the C++ code yourself. If it's unstable (i.e. buggy), it's most likely still cheaper for you to create patches than doing it yourself from scratch.</p> <p>However, in your special situation, it depends on how much functionality you need. If you just need a single function, then wrapping the C++ code into a small C extension library or with Cython is feasible. When you need to have all functionality &amp; flexibility, you have to create wrappers manually or using SWIG, basically repeating the work already done by other people.</p>
4
2009-02-01T16:44:56Z
[ "python", "xmp" ]
XMP image tagging and Python
501,087
<p>If I were to tag a bunch of images via XMP, in Python, what would be the best way? I've used Perl's <strong>Image::ExifTool</strong> and I am very much used to its reliability. I mean the thing never bricked on tens of thousands of images.</p> <p>I found <a href="http://code.google.com/p/python-xmp-toolkit/" rel="nofollow">this</a>, backed by some heavy-hitters like the European Space Agency, but it's clearly marked as unstable.</p> <p>Now, assuming I am comfortable with C++, how easy is it to, say, use the <a href="http://www.adobe.com/devnet/xmp/" rel="nofollow">Adobe XMP toolkit</a> directly, in Python? Having never done this before, I am not sure what I'd sign up for.</p> <p><strong>Update:</strong> I tried some libraries out there and, including the fore mentioned toolkit, they are still pretty immature and have glaring problems. I resorted to actually writing an Perl-based server that accepts XML requests to read and write metadata, with the combat-tested Image::EXIF. The amount of code is actually very light, and definitely beats torturing yourself by trying to get the Python libraries to work. The server solution is language-agnostic, so it's a twofer. </p>
2
2009-02-01T16:28:14Z
510,053
<p>You can use ImageMagic <a href="http://www.imagemagick.org/www/convert.html" rel="nofollow">convert</a>, IIRC there's a Python module to it as well.</p>
0
2009-02-04T04:21:00Z
[ "python", "xmp" ]
XMP image tagging and Python
501,087
<p>If I were to tag a bunch of images via XMP, in Python, what would be the best way? I've used Perl's <strong>Image::ExifTool</strong> and I am very much used to its reliability. I mean the thing never bricked on tens of thousands of images.</p> <p>I found <a href="http://code.google.com/p/python-xmp-toolkit/" rel="nofollow">this</a>, backed by some heavy-hitters like the European Space Agency, but it's clearly marked as unstable.</p> <p>Now, assuming I am comfortable with C++, how easy is it to, say, use the <a href="http://www.adobe.com/devnet/xmp/" rel="nofollow">Adobe XMP toolkit</a> directly, in Python? Having never done this before, I am not sure what I'd sign up for.</p> <p><strong>Update:</strong> I tried some libraries out there and, including the fore mentioned toolkit, they are still pretty immature and have glaring problems. I resorted to actually writing an Perl-based server that accepts XML requests to read and write metadata, with the combat-tested Image::EXIF. The amount of code is actually very light, and definitely beats torturing yourself by trying to get the Python libraries to work. The server solution is language-agnostic, so it's a twofer. </p>
2
2009-02-01T16:28:14Z
3,698,634
<p>I struggled for several hours with python-xmp-toolkit, and eventually gave up and just wrapped calls to <a href="http://www.sno.phy.queensu.ca/~phil/exiftool/" rel="nofollow">ExifTool</a>.</p> <p>There is <a href="http://miniexiftool.rubyforge.org/" rel="nofollow">a Ruby library</a> that wraps ExifTool as well (albeit, much better than what I created); I feel it'd be worth porting it to Python for a simple way of dealing with XMP.</p>
4
2010-09-13T07:52:36Z
[ "python", "xmp" ]
"EOL while scanning single-quoted string"? (backslash in string)
501,187
<pre><code>import os xp1 = "\Documents and Settings\" xp2 = os.getenv("USERNAME") print xp1+xp2 </code></pre> <p>Gives me error</p> <pre><code> File "1.py", line 2 xp1 = "\Documents and Settings\" ^ SyntaxError: EOL while scannning single-quoted string </code></pre> <p>Can you help me please, do you see the problem?</p>
1
2009-02-01T17:20:02Z
501,197
<p>The backslash character is interpreted as an escape. Use double backslashes for windows paths:</p> <pre><code>&gt;&gt;&gt; xp1 = "\\Documents and Settings\\" &gt;&gt;&gt; xp1 '\\Documents and Settings\\' &gt;&gt;&gt; print xp1 \Documents and Settings\ &gt;&gt;&gt; </code></pre>
19
2009-02-01T17:25:09Z
[ "python", "syntax-error" ]
"EOL while scanning single-quoted string"? (backslash in string)
501,187
<pre><code>import os xp1 = "\Documents and Settings\" xp2 = os.getenv("USERNAME") print xp1+xp2 </code></pre> <p>Gives me error</p> <pre><code> File "1.py", line 2 xp1 = "\Documents and Settings\" ^ SyntaxError: EOL while scannning single-quoted string </code></pre> <p>Can you help me please, do you see the problem?</p>
1
2009-02-01T17:20:02Z
501,202
<p>Additionally to the blackslash problem, don't join paths with the "+" operator -- use <code>os.path.join</code> instead.</p> <p>Also, construct the path to a user's home directory like that is likely to fail on new versions of Windows. There are API functions for that in pywin32.</p>
10
2009-02-01T17:26:31Z
[ "python", "syntax-error" ]
"EOL while scanning single-quoted string"? (backslash in string)
501,187
<pre><code>import os xp1 = "\Documents and Settings\" xp2 = os.getenv("USERNAME") print xp1+xp2 </code></pre> <p>Gives me error</p> <pre><code> File "1.py", line 2 xp1 = "\Documents and Settings\" ^ SyntaxError: EOL while scannning single-quoted string </code></pre> <p>Can you help me please, do you see the problem?</p>
1
2009-02-01T17:20:02Z
501,225
<p>You can use the <code>os.path.expanduser</code> function to get the path to a users home-directory. It doesn't even have to be an existing user.</p> <pre><code>&gt;&gt;&gt; import os.path &gt;&gt;&gt; os.path.expanduser('~foo') 'C:\\Documents and Settings\\foo' &gt;&gt;&gt; print os.path.expanduser('~foo') C:\Documents and Settings\foo &gt;&gt;&gt; print os.path.expanduser('~') C:\Documents and Settings\MizardX </code></pre> <p>"<code>~user</code>" is expanded to the path to <em>user</em>'s home directory. Just a single "<code>~</code>" gets expanded to the current users home directory.</p>
7
2009-02-01T17:39:28Z
[ "python", "syntax-error" ]
"EOL while scanning single-quoted string"? (backslash in string)
501,187
<pre><code>import os xp1 = "\Documents and Settings\" xp2 = os.getenv("USERNAME") print xp1+xp2 </code></pre> <p>Gives me error</p> <pre><code> File "1.py", line 2 xp1 = "\Documents and Settings\" ^ SyntaxError: EOL while scannning single-quoted string </code></pre> <p>Can you help me please, do you see the problem?</p>
1
2009-02-01T17:20:02Z
501,251
<p>Python, as many other languages, uses the backslash as an escape character (the double-quotes at the end of your xp1=... line are therefore considered as part of the string, not as the delimiter of the string).</p> <p>This is actually pretty basic stuff, so I strongly recommend you read the <a href="http://docs.python.org/tutorial/introduction.html#strings">python tutorial</a> before going any further.</p> <p>You might be interested in <em>raw</em> strings, which do <em>not</em> escape backslashes. Just add <em>r</em> just before the string:</p> <pre><code>xp1 = r"\Documents and Settings\" </code></pre> <p>Moreover, when manipulating file paths, you should use the <em>os.path</em> module, which will use "/" or "\" depending on the O.S. on which the program is run. For example:</p> <pre><code>import os.path xp1 = os.path.join("data","cities","geo.txt") </code></pre> <p>will produce "data/cities/geo.txt" on Linux and "data\cities\geo.txt" on Windows.</p>
5
2009-02-01T17:53:46Z
[ "python", "syntax-error" ]
"EOL while scanning single-quoted string"? (backslash in string)
501,187
<pre><code>import os xp1 = "\Documents and Settings\" xp2 = os.getenv("USERNAME") print xp1+xp2 </code></pre> <p>Gives me error</p> <pre><code> File "1.py", line 2 xp1 = "\Documents and Settings\" ^ SyntaxError: EOL while scannning single-quoted string </code></pre> <p>Can you help me please, do you see the problem?</p>
1
2009-02-01T17:20:02Z
8,442,196
<p><code>\"</code> is interpreted as "insert a double-quote into the string, so you are missing a terminating quote for the string literal. Note that a raw string <code>r"\"</code> can't help either.</p> <p>Quote from the <a href="http://docs.python.org/reference/lexical_analysis.html#string-literals" rel="nofollow">documentation</a> (bold is mine):</p> <blockquote> <p>When an 'r' or 'R' prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string. For example, the string literal r"\n" consists of two characters: a backslash and a lowercase 'n'. String quotes can be escaped with a backslash, but the backslash remains in the string; for example, r"\"" is a valid string literal consisting of two characters: a backslash and a double quote; r"\" is not a valid string literal (<strong>even a raw string cannot end in an odd number of backslashes</strong>). Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character). Note also that a single backslash followed by a newline is interpreted as those two characters as part of the string, not as a line continuation.</p> </blockquote> <p>The answer @MizardX gave is the right way to code what you are doing, regardless.</p>
1
2011-12-09T07:09:22Z
[ "python", "syntax-error" ]
Problem in understanding Python list comprehensions
501,308
<p>What does the last line mean in the following code?</p> <pre><code>import pickle, urllib handle = urllib.urlopen("http://www.pythonchallenge.com/pc/def/banner.p") data = pickle.load(handle) handle.close() for elt in data: print "".join([e[1] * e[0] for e in elt]) </code></pre> <p>My attempt to the problem:</p> <ul> <li>"".join... uses join -method to empty text</li> <li>e[1] * e[0] multiplies two subsequent values in the sequence, e</li> <li>I am not sure what is e</li> <li>I am not sure, what it means, when you have something before for -loop, like: <code>e[1] * e[0] for e in elt</code></li> </ul>
4
2009-02-01T18:22:26Z
501,318
<p><code>[e[1] * e[0] for e in elt]</code> is a list comprehension, which evaluates to a list itself by looping through another list, in this case <code>elt</code>. Each element in the new list is <code>e[1]*e[0]</code>, where <code>e</code> is the corresponding element in <code>elt</code>.</p>
4
2009-02-01T18:28:03Z
[ "python", "list-comprehension" ]
Problem in understanding Python list comprehensions
501,308
<p>What does the last line mean in the following code?</p> <pre><code>import pickle, urllib handle = urllib.urlopen("http://www.pythonchallenge.com/pc/def/banner.p") data = pickle.load(handle) handle.close() for elt in data: print "".join([e[1] * e[0] for e in elt]) </code></pre> <p>My attempt to the problem:</p> <ul> <li>"".join... uses join -method to empty text</li> <li>e[1] * e[0] multiplies two subsequent values in the sequence, e</li> <li>I am not sure what is e</li> <li>I am not sure, what it means, when you have something before for -loop, like: <code>e[1] * e[0] for e in elt</code></li> </ul>
4
2009-02-01T18:22:26Z
501,320
<p>join() is a string method, that works on a separator in new string</p> <pre><code>&gt;&gt;&gt; ':'.join(['ab', 'cd']) &gt;&gt;&gt; 'ab:cd' </code></pre> <p>and list comprehension is not necessary there, generator would suffice</p>
1
2009-02-01T18:33:19Z
[ "python", "list-comprehension" ]
Problem in understanding Python list comprehensions
501,308
<p>What does the last line mean in the following code?</p> <pre><code>import pickle, urllib handle = urllib.urlopen("http://www.pythonchallenge.com/pc/def/banner.p") data = pickle.load(handle) handle.close() for elt in data: print "".join([e[1] * e[0] for e in elt]) </code></pre> <p>My attempt to the problem:</p> <ul> <li>"".join... uses join -method to empty text</li> <li>e[1] * e[0] multiplies two subsequent values in the sequence, e</li> <li>I am not sure what is e</li> <li>I am not sure, what it means, when you have something before for -loop, like: <code>e[1] * e[0] for e in elt</code></li> </ul>
4
2009-02-01T18:22:26Z
501,321
<p>Firstly, you need to put http:// in front of the URL, ie: handle = urllib.urlopen("http://www.pythonchallenge.com/pc/def/banner.p")</p> <p>An expression [e for e in aList] is a <a href="http://en.wikipedia.org/wiki/List_comprehension" rel="nofollow">list comprehension</a> which generates a list of values.</p> <p>With Python strings, the * operator is used to repeat a string. Try typing in the commands one by one into an interpreter then look at data:</p> <pre><code>&gt;&gt;&gt; data[0] [(' ', 95)] </code></pre> <p>This shows us each line of data is a tuple containing two elements.</p> <p>Thus the expression e[1] * e[0] is effectively the string in e[0] repeated e[1] times.</p> <p>Hence the program draws a banner.</p>
6
2009-02-01T18:34:12Z
[ "python", "list-comprehension" ]
Problem in understanding Python list comprehensions
501,308
<p>What does the last line mean in the following code?</p> <pre><code>import pickle, urllib handle = urllib.urlopen("http://www.pythonchallenge.com/pc/def/banner.p") data = pickle.load(handle) handle.close() for elt in data: print "".join([e[1] * e[0] for e in elt]) </code></pre> <p>My attempt to the problem:</p> <ul> <li>"".join... uses join -method to empty text</li> <li>e[1] * e[0] multiplies two subsequent values in the sequence, e</li> <li>I am not sure what is e</li> <li>I am not sure, what it means, when you have something before for -loop, like: <code>e[1] * e[0] for e in elt</code></li> </ul>
4
2009-02-01T18:22:26Z
501,323
<p>Maybe best explained with an example:</p> <pre><code>print "".join([e[1] * e[0] for e in elt]) </code></pre> <p>is the short form of</p> <pre><code>x = [] for e in elt: x.append(e[1] * e[0]) print "".join(x) </code></pre> <p>List comprehensions are simply syntactic sugar for <code>for</code> loops, which make an expression out of a sequence of statements.</p> <p><code>elt</code> can be an arbitrary object, since you load it from pickles, and <code>e</code> likewise. The usage suggests that is it a <a href="http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange">sequence</a> type, but it could just be anything that implements the sequence protocol.</p>
18
2009-02-01T18:34:33Z
[ "python", "list-comprehension" ]
Problem in understanding Python list comprehensions
501,308
<p>What does the last line mean in the following code?</p> <pre><code>import pickle, urllib handle = urllib.urlopen("http://www.pythonchallenge.com/pc/def/banner.p") data = pickle.load(handle) handle.close() for elt in data: print "".join([e[1] * e[0] for e in elt]) </code></pre> <p>My attempt to the problem:</p> <ul> <li>"".join... uses join -method to empty text</li> <li>e[1] * e[0] multiplies two subsequent values in the sequence, e</li> <li>I am not sure what is e</li> <li>I am not sure, what it means, when you have something before for -loop, like: <code>e[1] * e[0] for e in elt</code></li> </ul>
4
2009-02-01T18:22:26Z
501,402
<p>Andy's is a great answer!</p> <p>If you want to see every step of the loop (with line-breaks) try this out:</p> <pre><code>for elt in data: for e in elt: print "e[0] == %s, e[1] == %d, which gives us: '%s'" % (e[0], e[1], ''.join(e[1] * e[0])) </code></pre>
1
2009-02-01T19:15:46Z
[ "python", "list-comprehension" ]
Problem in understanding Python list comprehensions
501,308
<p>What does the last line mean in the following code?</p> <pre><code>import pickle, urllib handle = urllib.urlopen("http://www.pythonchallenge.com/pc/def/banner.p") data = pickle.load(handle) handle.close() for elt in data: print "".join([e[1] * e[0] for e in elt]) </code></pre> <p>My attempt to the problem:</p> <ul> <li>"".join... uses join -method to empty text</li> <li>e[1] * e[0] multiplies two subsequent values in the sequence, e</li> <li>I am not sure what is e</li> <li>I am not sure, what it means, when you have something before for -loop, like: <code>e[1] * e[0] for e in elt</code></li> </ul>
4
2009-02-01T18:22:26Z
508,898
<p>The question itself has already been fully answered but I'd like to add that a list comprehension also supports filtering. Your original line</p> <pre><code>print "".join([e[1] * e[0] for e in elt]) </code></pre> <p>could, as an example, become</p> <pre><code>print "".join([e[1] * e[0] for e in elt if len(e) == 2]) </code></pre> <p>to only operate on items in elt that have two elements.</p>
2
2009-02-03T21:06:38Z
[ "python", "list-comprehension" ]
How can you use Python in Vim?
501,585
<p>I waste a lot of time between Vim and Python. I find it too slow to manually copy-paste from Python to Vim and vice versa. A good broken example is:</p> <blockquote> <p>%!python for i in xrange(25); print 6*i \n </p> </blockquote> <p>How can you do such tweaks direcly in Vim? <strong>[Solved]</strong></p> <p><strong>[Clarification]</strong> I need things to Vim, like printing sequences, arithmetics... - things I cannot do in Vim.</p> <p><strong>[?]</strong> Can someone elaborate this point: "your script can read from stdin to operate directly on the lines given <em>(., %, ...).</em>" </p> <p><strong>[Further Clarification]</strong></p> <p>If I want to print 'Hello' to lines 4,5, 6 and 7, what is wrong:</p> <blockquote> <p>:4-7!python -c "print 'hello'"</p> </blockquote> <p>The dot . modifies the current line. Can I print on multiple lines 7, 32 and 99:</p> <blockquote> <p>:7,32,99!python -c "print 'hello'"</p> </blockquote> <p>Clearly not working. How?</p>
50
2009-02-01T21:10:02Z
501,606
<p>From your example, it appears as though you want to execute a Python script and have the output of the script appear in the current Vim buffer. If that's correct, then you can do the following at the command line in Vim:</p> <pre><code>%!python -c "for i in xrange(25): print 6*i" </code></pre> <p>The <code>-c</code> option to <code>python</code> gives it a script to run. However, you may find this technique useful only in very short cases, because unlike some other languages, Python does not lend itself well to writing complete programs all on one line.</p>
5
2009-02-01T21:21:47Z
[ "python", "vim" ]
How can you use Python in Vim?
501,585
<p>I waste a lot of time between Vim and Python. I find it too slow to manually copy-paste from Python to Vim and vice versa. A good broken example is:</p> <blockquote> <p>%!python for i in xrange(25); print 6*i \n </p> </blockquote> <p>How can you do such tweaks direcly in Vim? <strong>[Solved]</strong></p> <p><strong>[Clarification]</strong> I need things to Vim, like printing sequences, arithmetics... - things I cannot do in Vim.</p> <p><strong>[?]</strong> Can someone elaborate this point: "your script can read from stdin to operate directly on the lines given <em>(., %, ...).</em>" </p> <p><strong>[Further Clarification]</strong></p> <p>If I want to print 'Hello' to lines 4,5, 6 and 7, what is wrong:</p> <blockquote> <p>:4-7!python -c "print 'hello'"</p> </blockquote> <p>The dot . modifies the current line. Can I print on multiple lines 7, 32 and 99:</p> <blockquote> <p>:7,32,99!python -c "print 'hello'"</p> </blockquote> <p>Clearly not working. How?</p>
50
2009-02-01T21:10:02Z
501,619
<p>I think you't just missing the <code>-c</code> flag. For example:</p> <pre><code>:.!python -c "print 'hello'" </code></pre> <p>You should not that the script that you provide acts as a filter on the line selection. That is, your script can read from <code>stdin</code> to operate directly on the lines given (<code>.</code>, <code>%</code>, ...). Anything more than the simplest tasks, however, and you'd be better off putting the python commands into a script file of its own.</p>
1
2009-02-01T21:27:04Z
[ "python", "vim" ]
How can you use Python in Vim?
501,585
<p>I waste a lot of time between Vim and Python. I find it too slow to manually copy-paste from Python to Vim and vice versa. A good broken example is:</p> <blockquote> <p>%!python for i in xrange(25); print 6*i \n </p> </blockquote> <p>How can you do such tweaks direcly in Vim? <strong>[Solved]</strong></p> <p><strong>[Clarification]</strong> I need things to Vim, like printing sequences, arithmetics... - things I cannot do in Vim.</p> <p><strong>[?]</strong> Can someone elaborate this point: "your script can read from stdin to operate directly on the lines given <em>(., %, ...).</em>" </p> <p><strong>[Further Clarification]</strong></p> <p>If I want to print 'Hello' to lines 4,5, 6 and 7, what is wrong:</p> <blockquote> <p>:4-7!python -c "print 'hello'"</p> </blockquote> <p>The dot . modifies the current line. Can I print on multiple lines 7, 32 and 99:</p> <blockquote> <p>:7,32,99!python -c "print 'hello'"</p> </blockquote> <p>Clearly not working. How?</p>
50
2009-02-01T21:10:02Z
501,698
<p>In any of your vim windows, type something like this:</p> <pre><code>for x in range(1,10): print '-&gt; %d' % x </code></pre> <p>Visually select both of those lines (V to start visual mode), and type the following:</p> <pre><code>:!python </code></pre> <p>Because you pressed ':' in visual mode, that will end up looking like:</p> <pre><code>:'&lt;,'&gt;!python </code></pre> <p>Hit enter and the selection is replaced by the output of the <code>print</code> statements. You could easily turn it into a mapping:</p> <pre><code>:vnoremap &lt;f5&gt; :!python&lt;CR&gt; </code></pre>
155
2009-02-01T22:17:12Z
[ "python", "vim" ]
How can you use Python in Vim?
501,585
<p>I waste a lot of time between Vim and Python. I find it too slow to manually copy-paste from Python to Vim and vice versa. A good broken example is:</p> <blockquote> <p>%!python for i in xrange(25); print 6*i \n </p> </blockquote> <p>How can you do such tweaks direcly in Vim? <strong>[Solved]</strong></p> <p><strong>[Clarification]</strong> I need things to Vim, like printing sequences, arithmetics... - things I cannot do in Vim.</p> <p><strong>[?]</strong> Can someone elaborate this point: "your script can read from stdin to operate directly on the lines given <em>(., %, ...).</em>" </p> <p><strong>[Further Clarification]</strong></p> <p>If I want to print 'Hello' to lines 4,5, 6 and 7, what is wrong:</p> <blockquote> <p>:4-7!python -c "print 'hello'"</p> </blockquote> <p>The dot . modifies the current line. Can I print on multiple lines 7, 32 and 99:</p> <blockquote> <p>:7,32,99!python -c "print 'hello'"</p> </blockquote> <p>Clearly not working. How?</p>
50
2009-02-01T21:10:02Z
501,790
<blockquote> <p>Can someone elaborate this point: "your script can read from stdin to operate directly on the lines given (., %, ...)."</p> </blockquote> <p>One common use is to sort lines of text using the 'sort' command available in your shell. For example, you can sort the whole file using this command:</p> <pre><code>:%!sort </code></pre> <p>Or, you could sort just a few lines by selecting them in visual mode and then typing:</p> <pre><code>:!sort </code></pre> <p>You could sort lines 5-10 using this command:</p> <pre><code>:5,10!sort </code></pre> <p>You could write your own command-line script (presuming you know how to do that) which reverses lines of text. It works like this:</p> <pre><code>bash$ myreverse 'hello world!' !dlrow olleh </code></pre> <p>You could apply it to one of your open files in vim in exactly the same way you used <code>sort</code>:</p> <pre><code>:%!myreverse &lt;- all lines in your file are reversed </code></pre>
6
2009-02-01T23:00:46Z
[ "python", "vim" ]
How can you use Python in Vim?
501,585
<p>I waste a lot of time between Vim and Python. I find it too slow to manually copy-paste from Python to Vim and vice versa. A good broken example is:</p> <blockquote> <p>%!python for i in xrange(25); print 6*i \n </p> </blockquote> <p>How can you do such tweaks direcly in Vim? <strong>[Solved]</strong></p> <p><strong>[Clarification]</strong> I need things to Vim, like printing sequences, arithmetics... - things I cannot do in Vim.</p> <p><strong>[?]</strong> Can someone elaborate this point: "your script can read from stdin to operate directly on the lines given <em>(., %, ...).</em>" </p> <p><strong>[Further Clarification]</strong></p> <p>If I want to print 'Hello' to lines 4,5, 6 and 7, what is wrong:</p> <blockquote> <p>:4-7!python -c "print 'hello'"</p> </blockquote> <p>The dot . modifies the current line. Can I print on multiple lines 7, 32 and 99:</p> <blockquote> <p>:7,32,99!python -c "print 'hello'"</p> </blockquote> <p>Clearly not working. How?</p>
50
2009-02-01T21:10:02Z
501,812
<blockquote> <p>If I want to print 'Hello' to lines 4,5, 6 and 7, what is wrong:</p> </blockquote> <p>If you want to do something in randomly chosen places throughout your file, you're better of recording keystrokes and replaying them. Go to the first line you want to change, and hit <code>qz</code> to starting recording into register <code>z</code>. Do whatever edits you want for that line and hit <code>q</code> again when you're finished. Go to the next line you want to change and press <code>@z</code> to replay the macro.</p>
0
2009-02-01T23:17:23Z
[ "python", "vim" ]
How can you use Python in Vim?
501,585
<p>I waste a lot of time between Vim and Python. I find it too slow to manually copy-paste from Python to Vim and vice versa. A good broken example is:</p> <blockquote> <p>%!python for i in xrange(25); print 6*i \n </p> </blockquote> <p>How can you do such tweaks direcly in Vim? <strong>[Solved]</strong></p> <p><strong>[Clarification]</strong> I need things to Vim, like printing sequences, arithmetics... - things I cannot do in Vim.</p> <p><strong>[?]</strong> Can someone elaborate this point: "your script can read from stdin to operate directly on the lines given <em>(., %, ...).</em>" </p> <p><strong>[Further Clarification]</strong></p> <p>If I want to print 'Hello' to lines 4,5, 6 and 7, what is wrong:</p> <blockquote> <p>:4-7!python -c "print 'hello'"</p> </blockquote> <p>The dot . modifies the current line. Can I print on multiple lines 7, 32 and 99:</p> <blockquote> <p>:7,32,99!python -c "print 'hello'"</p> </blockquote> <p>Clearly not working. How?</p>
50
2009-02-01T21:10:02Z
506,938
<p>If you want to do some python calls without compiling vim with the python interpreter (that would allow you to write plug-ins in Python, and it's also needed for Omnicomplete anyway) you can try as this:</p> <pre><code>:.!python -c "import os; print os.getcwd()" </code></pre> <p>That would tell you where you are in the drive (current path).</p> <p>Now let's number a few lines, starting from an empty file so we can see the result easily:</p> <pre><code>:.!python -c "for i in range(1,101): print i" </code></pre> <p>(vim numbers lines from 1 not 0) Now we have just the number of each line in every line up to line 100.</p> <p>Let's now put a small script in your current path (as shown above) and run it, see how it works. Let's copy paste this silly one. In reality you will find most useful to do script that output one line per line, but you don't have to do that as this script shows:</p> <pre><code>print "hi" try: while True: i=raw_input() print "this was:",i except EOFError: print "bye" </code></pre> <p>So you can call, for instance (imagine you called it "what.py"):</p> <p>:10,20!python what.py</p> <p>(Note that tab completion of file names works, so you can verify it's actually in the path)</p> <p>As you can see, everyline is fed to the script as standard input. First it outputs "hi", at the end "bye" and in between, for each line you output "this was: " plus the line. This way you can process line-by-line. Notice you can do more complex stuff than processing line by line, you can actually consider previous lines. For such stuff I'd rather import sys and do it like this:</p> <pre><code>import sys print "hello" for i in sys.stdin.readlines(): i = i.rstrip("\n") # you can also prevent print from doing \n instead print "here lyeth",i print "see you" </code></pre> <p>Hope that helps.</p>
0
2009-02-03T12:41:55Z
[ "python", "vim" ]
How can you use Python in Vim?
501,585
<p>I waste a lot of time between Vim and Python. I find it too slow to manually copy-paste from Python to Vim and vice versa. A good broken example is:</p> <blockquote> <p>%!python for i in xrange(25); print 6*i \n </p> </blockquote> <p>How can you do such tweaks direcly in Vim? <strong>[Solved]</strong></p> <p><strong>[Clarification]</strong> I need things to Vim, like printing sequences, arithmetics... - things I cannot do in Vim.</p> <p><strong>[?]</strong> Can someone elaborate this point: "your script can read from stdin to operate directly on the lines given <em>(., %, ...).</em>" </p> <p><strong>[Further Clarification]</strong></p> <p>If I want to print 'Hello' to lines 4,5, 6 and 7, what is wrong:</p> <blockquote> <p>:4-7!python -c "print 'hello'"</p> </blockquote> <p>The dot . modifies the current line. Can I print on multiple lines 7, 32 and 99:</p> <blockquote> <p>:7,32,99!python -c "print 'hello'"</p> </blockquote> <p>Clearly not working. How?</p>
50
2009-02-01T21:10:02Z
513,634
<p>I think what you really want is explained <a href="http://vim.wikia.com/wiki/Execute_Python_from_within_current_file" rel="nofollow">here</a>. </p>
0
2009-02-04T22:18:09Z
[ "python", "vim" ]
How can you use Python in Vim?
501,585
<p>I waste a lot of time between Vim and Python. I find it too slow to manually copy-paste from Python to Vim and vice versa. A good broken example is:</p> <blockquote> <p>%!python for i in xrange(25); print 6*i \n </p> </blockquote> <p>How can you do such tweaks direcly in Vim? <strong>[Solved]</strong></p> <p><strong>[Clarification]</strong> I need things to Vim, like printing sequences, arithmetics... - things I cannot do in Vim.</p> <p><strong>[?]</strong> Can someone elaborate this point: "your script can read from stdin to operate directly on the lines given <em>(., %, ...).</em>" </p> <p><strong>[Further Clarification]</strong></p> <p>If I want to print 'Hello' to lines 4,5, 6 and 7, what is wrong:</p> <blockquote> <p>:4-7!python -c "print 'hello'"</p> </blockquote> <p>The dot . modifies the current line. Can I print on multiple lines 7, 32 and 99:</p> <blockquote> <p>:7,32,99!python -c "print 'hello'"</p> </blockquote> <p>Clearly not working. How?</p>
50
2009-02-01T21:10:02Z
1,275,093
<p>I am unsure of their usefulness, perhaps for further reading:</p> <ul> <li><a href="http://www.tummy.com/Community/Presentations/vimpython-20070225/vim.html" rel="nofollow">Python and vim: Two great tastes that go great together by Sean Reifschneider (Advanced)</a></li> <li><a href="http://dancingpenguinsoflight.com/2009/02/python-and-vim-make-your-own-ide/" rel="nofollow">Python and vim: Make your own IDE</a></li> <li><a href="http://www.cmdln.org/2008/10/18/vim-customization-for-python/" rel="nofollow">Vim customization for python</a></li> </ul>
2
2009-08-13T22:55:18Z
[ "python", "vim" ]
How can you use Python in Vim?
501,585
<p>I waste a lot of time between Vim and Python. I find it too slow to manually copy-paste from Python to Vim and vice versa. A good broken example is:</p> <blockquote> <p>%!python for i in xrange(25); print 6*i \n </p> </blockquote> <p>How can you do such tweaks direcly in Vim? <strong>[Solved]</strong></p> <p><strong>[Clarification]</strong> I need things to Vim, like printing sequences, arithmetics... - things I cannot do in Vim.</p> <p><strong>[?]</strong> Can someone elaborate this point: "your script can read from stdin to operate directly on the lines given <em>(., %, ...).</em>" </p> <p><strong>[Further Clarification]</strong></p> <p>If I want to print 'Hello' to lines 4,5, 6 and 7, what is wrong:</p> <blockquote> <p>:4-7!python -c "print 'hello'"</p> </blockquote> <p>The dot . modifies the current line. Can I print on multiple lines 7, 32 and 99:</p> <blockquote> <p>:7,32,99!python -c "print 'hello'"</p> </blockquote> <p>Clearly not working. How?</p>
50
2009-02-01T21:10:02Z
4,660,124
<p>You can execute the code, read the output on the cursor and finish with <code>u</code>, supposing you are executing python code. Simple and quick.</p> <pre><code>:r !python % u </code></pre> <p>I like it over mapping and selecting-in-visual-mode, like with <a href="http://stackoverflow.com/questions/501585/how-can-you-use-python-in-vim/501698#501698">too-much-php</a>, because it keeps the base simple!</p>
0
2011-01-11T16:46:02Z
[ "python", "vim" ]
How can you use Python in Vim?
501,585
<p>I waste a lot of time between Vim and Python. I find it too slow to manually copy-paste from Python to Vim and vice versa. A good broken example is:</p> <blockquote> <p>%!python for i in xrange(25); print 6*i \n </p> </blockquote> <p>How can you do such tweaks direcly in Vim? <strong>[Solved]</strong></p> <p><strong>[Clarification]</strong> I need things to Vim, like printing sequences, arithmetics... - things I cannot do in Vim.</p> <p><strong>[?]</strong> Can someone elaborate this point: "your script can read from stdin to operate directly on the lines given <em>(., %, ...).</em>" </p> <p><strong>[Further Clarification]</strong></p> <p>If I want to print 'Hello' to lines 4,5, 6 and 7, what is wrong:</p> <blockquote> <p>:4-7!python -c "print 'hello'"</p> </blockquote> <p>The dot . modifies the current line. Can I print on multiple lines 7, 32 and 99:</p> <blockquote> <p>:7,32,99!python -c "print 'hello'"</p> </blockquote> <p>Clearly not working. How?</p>
50
2009-02-01T21:10:02Z
15,468,245
<p>I just wrote the following module that lets you edit a temporary buffer in vim directly in the Python interpreter.</p> <p><a href="http://philipbjorge.github.com/EditREPL/" rel="nofollow">http://philipbjorge.github.com/EditREPL/</a></p>
1
2013-03-18T01:01:46Z
[ "python", "vim" ]
How can you use Python in Vim?
501,585
<p>I waste a lot of time between Vim and Python. I find it too slow to manually copy-paste from Python to Vim and vice versa. A good broken example is:</p> <blockquote> <p>%!python for i in xrange(25); print 6*i \n </p> </blockquote> <p>How can you do such tweaks direcly in Vim? <strong>[Solved]</strong></p> <p><strong>[Clarification]</strong> I need things to Vim, like printing sequences, arithmetics... - things I cannot do in Vim.</p> <p><strong>[?]</strong> Can someone elaborate this point: "your script can read from stdin to operate directly on the lines given <em>(., %, ...).</em>" </p> <p><strong>[Further Clarification]</strong></p> <p>If I want to print 'Hello' to lines 4,5, 6 and 7, what is wrong:</p> <blockquote> <p>:4-7!python -c "print 'hello'"</p> </blockquote> <p>The dot . modifies the current line. Can I print on multiple lines 7, 32 and 99:</p> <blockquote> <p>:7,32,99!python -c "print 'hello'"</p> </blockquote> <p>Clearly not working. How?</p>
50
2009-02-01T21:10:02Z
18,146,697
<p>On Windows, if you are editing the python script, just do:</p> <pre><code>!start python my... </code></pre> <p>and press <code>tab</code> to cycle along the available file names, until you find your match:</p> <pre><code>!start python myscript.py </code></pre> <p>It will run in a new <code>cmd</code> window. Personally I prefer to do <code>!start cmd</code> and from there run Python, since it is easier to debug from the eventual error messages.</p>
0
2013-08-09T12:28:55Z
[ "python", "vim" ]
How to distribute `.desktop` files and icons for a Python package in Gnome (with distutils or setuptools)?
501,597
<p>Currently I'm using the auto-tools to build/install and package a project of mine, but I would really like to move to something that feels more "pythonic".</p> <p>My project consists of two scripts, one module, two glade GUI descriptions, and two .desktop files. It's currently a pure python project, though that's likely to change soon-ish.</p> <p>Looking at setuptools I can easily see how to deal with everything except the .desktop files; they have to end up in a specific directory so that Gnome can find them.</p> <p>Is using distuils/setuptools a good idea to begin with?</p>
8
2009-02-01T21:18:01Z
501,624
<p>In general, yes - everything is better than autotools when building Python projects.</p> <p>I have good experiences with setuptools so far. However, installing files into fixed locations is not a strength of setuptools - after all, it's not something to build installaters for Python apps, but distribute Python libraries.</p> <p>For the installation of files which are not application data files (like images, UI files etc) but provide integration into the operating system, you are better off with using a real packaging format (like RPM or deb).</p> <p>That said, nothing stops you from having the build process based on setuptools and a small make file for installing everything into its rightful place.</p>
1
2009-02-01T21:31:36Z
[ "python", "packaging", "setuptools", "gnome", "distutils2" ]
How to distribute `.desktop` files and icons for a Python package in Gnome (with distutils or setuptools)?
501,597
<p>Currently I'm using the auto-tools to build/install and package a project of mine, but I would really like to move to something that feels more "pythonic".</p> <p>My project consists of two scripts, one module, two glade GUI descriptions, and two .desktop files. It's currently a pure python project, though that's likely to change soon-ish.</p> <p>Looking at setuptools I can easily see how to deal with everything except the .desktop files; they have to end up in a specific directory so that Gnome can find them.</p> <p>Is using distuils/setuptools a good idea to begin with?</p>
8
2009-02-01T21:18:01Z
2,291,791
<p>You can try to use <a href="https://launchpad.net/python-distutils-extra" rel="nofollow">python-distutils-extra</a>. The <code>DistUtilsExtra.auto</code> module automatically <a href="http://bazaar.launchpad.net/~python-distutils-extra-hackers/python-distutils-extra/debian/annotate/head:/doc/README" rel="nofollow">supports</a> .desktop files, as well as Glade/GtkBuilder .ui files, Python modules and scripts, misc data files, etc.</p> <p>It should work both with Distutils and Setuptools.</p>
1
2010-02-18T20:02:37Z
[ "python", "packaging", "setuptools", "gnome", "distutils2" ]
How to distribute `.desktop` files and icons for a Python package in Gnome (with distutils or setuptools)?
501,597
<p>Currently I'm using the auto-tools to build/install and package a project of mine, but I would really like to move to something that feels more "pythonic".</p> <p>My project consists of two scripts, one module, two glade GUI descriptions, and two .desktop files. It's currently a pure python project, though that's likely to change soon-ish.</p> <p>Looking at setuptools I can easily see how to deal with everything except the .desktop files; they have to end up in a specific directory so that Gnome can find them.</p> <p>Is using distuils/setuptools a good idea to begin with?</p>
8
2009-02-01T21:18:01Z
24,116,911
<p><strong>I managed to get this to work, but it kinda feels to me more like a <em>workaround</em>.</strong> </p> <p>Don't know what's the preferred way to handle this...</p> <p>I used the following <code>setup.py</code> file (full version is <a href="https://gist.github.com/brutus/e4bdb1d2c1705558b2ff" rel="nofollow">here</a>):</p> <pre><code>from setuptools import setup setup( # ... data_files=[ ('share/icons/hicolor/scalable/apps', ['data/mypackage.svg']), ('share/applications', ['data/mypackage.desktop']) ], entry_points={ 'console_scripts': ['startit=mypackage.cli:run'] } ) </code></pre> <p>The starter script trough <code>entry_points</code> works. But the <code>data_files</code> where put in an egg file and not in the folders specified, so they can't be accessed by the desktop shell.</p> <p><strong>To work around this, I used the following <code>setup.cfg</code> file:</strong></p> <pre><code>[install] single-version-externally-managed=1 record=install.txt </code></pre> <p>This works. Both data files are created in the right place and the <code>.desktop</code> file is recognized by Gnome.</p>
4
2014-06-09T09:03:00Z
[ "python", "packaging", "setuptools", "gnome", "distutils2" ]
How to distribute `.desktop` files and icons for a Python package in Gnome (with distutils or setuptools)?
501,597
<p>Currently I'm using the auto-tools to build/install and package a project of mine, but I would really like to move to something that feels more "pythonic".</p> <p>My project consists of two scripts, one module, two glade GUI descriptions, and two .desktop files. It's currently a pure python project, though that's likely to change soon-ish.</p> <p>Looking at setuptools I can easily see how to deal with everything except the .desktop files; they have to end up in a specific directory so that Gnome can find them.</p> <p>Is using distuils/setuptools a good idea to begin with?</p>
8
2009-02-01T21:18:01Z
28,157,740
<p>I've created <a href="https://pypi.python.org/pypi/install-freedesktop" rel="nofollow">https://pypi.python.org/pypi/install-freedesktop</a>. It creates .desktop files automatically for the gui_scripts entry points, which can be customized through a setup argument, and supports <code>--user</code> as well as system-wide installation. Compared to <code>DistUtilsExtra</code>, it's more narrow in scope and IMHO more pythonic (explicit is better than implicit).</p>
1
2015-01-26T19:57:46Z
[ "python", "packaging", "setuptools", "gnome", "distutils2" ]
Both Python 2 and 3 in Emacs
501,626
<p>I have been using Emacs to write Python 2 code. Now I have both Python 2.6 and 3.0 installed on my system, and I need to write Python 3 code as well.</p> <p>Here is how the different versions are set up in /usr/bin:</p> <pre><code>python -&gt; python2.6* python2 -&gt; python2.6* python2.6* python3 -&gt; python3.0* python3.0* </code></pre> <p>Is there any way to set this up so that Emacs uses the correct version of Python, depending on which language I am using? For instance, C-c C-c currently runs the buffer, but it always calls python2.6, even if I am writing Python 3 code.</p>
16
2009-02-01T21:32:47Z
502,304
<p>The answer is yes. If you can distinguish Python 2 from Python 3, then it is a Simple Matter Of Programming to get emacs to do what you want.</p> <pre><code>(define run-python (&amp;optional buffer) (with-current-buffer (or buffer (current-buffer)) (if (is-python3-p) (run-python3) (run-python2)))) (define-key python-mode-map (kbd "C-c C-c") #'run-python) </code></pre> <p>All that's left to do is implement <code>is-python3-p</code> and <code>run-python3</code> (etc.)</p>
4
2009-02-02T05:49:42Z
[ "python", "emacs", "python-3.x" ]
Both Python 2 and 3 in Emacs
501,626
<p>I have been using Emacs to write Python 2 code. Now I have both Python 2.6 and 3.0 installed on my system, and I need to write Python 3 code as well.</p> <p>Here is how the different versions are set up in /usr/bin:</p> <pre><code>python -&gt; python2.6* python2 -&gt; python2.6* python2.6* python3 -&gt; python3.0* python3.0* </code></pre> <p>Is there any way to set this up so that Emacs uses the correct version of Python, depending on which language I am using? For instance, C-c C-c currently runs the buffer, but it always calls python2.6, even if I am writing Python 3 code.</p>
16
2009-02-01T21:32:47Z
502,422
<p>If you are using python-mode.el you can try to change <code>py-which-shell</code>. In order to do this on a per-file basis you can put</p> <pre><code># -*- py-which-shell: "python3"; -*- </code></pre> <p>at the first line of your file - or at the second line if the first line starts with <code>#!</code>. Another choice is to put</p> <pre><code># Local Variables: # py-which-shell: "python3" # End: </code></pre> <p>at the end of your file. Perhaps you should give the full path to python3 instead of just "python3".</p>
10
2009-02-02T07:14:45Z
[ "python", "emacs", "python-3.x" ]
Both Python 2 and 3 in Emacs
501,626
<p>I have been using Emacs to write Python 2 code. Now I have both Python 2.6 and 3.0 installed on my system, and I need to write Python 3 code as well.</p> <p>Here is how the different versions are set up in /usr/bin:</p> <pre><code>python -&gt; python2.6* python2 -&gt; python2.6* python2.6* python3 -&gt; python3.0* python3.0* </code></pre> <p>Is there any way to set this up so that Emacs uses the correct version of Python, depending on which language I am using? For instance, C-c C-c currently runs the buffer, but it always calls python2.6, even if I am writing Python 3 code.</p>
16
2009-02-01T21:32:47Z
1,460,880
<p>My comment on <a href="http://stackoverflow.com/questions/501626/both-python-2-and-3-in-emacs/502422#502422">this answer</a>. </p> <p>I wrote /t/min.py which will run fine in python3 but not in python2 (dictionary comprehension works in python3)</p> <p>Contents of /t/min.py</p> <pre><code>#!/usr/bin/python3 # -*- py-python-command: "/usr/bin/python3"; -*- a = {i:i**2 for i in range(10)} print(a) </code></pre> <p>Note that the shebang indicates python3 and the file local variable py-python-command too.</p> <p>I also wrote /t/min-py.el which makes sure that python-mode.el (ver 5.1.0)is used instead of python.el.</p> <p>Contents of /t/min-py.el</p> <pre><code>(add-to-list 'load-path "~/m/em/lisp/") (autoload 'python-mode "python-mode" "Python Mode." t) ;; (setq py-python-command "python3") </code></pre> <p>Note that the last line is commented out.</p> <p>I start emacs with the following command:</p> <pre><code>emacs -Q -l /t/min-py.el /t/min.py &amp; </code></pre> <p>Now emacs is started with my alternate dotemacs /t/min-py.el and it opens /t/min.py.</p> <p>When I press C-c C-c to send the buffer to python, it says the "for" part is wrong and that indicates that python2 is being used instead of python3. When I press C-c ! to start the python interpreter, it says python 2.5 is started.</p> <p>I can even change the second line of /t/min.py to this:</p> <pre><code># -*- py-python-command: "chunkybacon"; -*- </code></pre> <p>and do this experiment again and emacs still uses python2.</p> <p>If the last line of /t/min-py.el is not commented out, then C-c C-c and C-c ! both use python3.</p>
3
2009-09-22T15:42:25Z
[ "python", "emacs", "python-3.x" ]
Both Python 2 and 3 in Emacs
501,626
<p>I have been using Emacs to write Python 2 code. Now I have both Python 2.6 and 3.0 installed on my system, and I need to write Python 3 code as well.</p> <p>Here is how the different versions are set up in /usr/bin:</p> <pre><code>python -&gt; python2.6* python2 -&gt; python2.6* python2.6* python3 -&gt; python3.0* python3.0* </code></pre> <p>Is there any way to set this up so that Emacs uses the correct version of Python, depending on which language I am using? For instance, C-c C-c currently runs the buffer, but it always calls python2.6, even if I am writing Python 3 code.</p>
16
2009-02-01T21:32:47Z
6,006,909
<p>regarding jrockway's comment:</p> <pre><code>(defun is-python3-p () "Check whether we're running python 2 or 3." (setq mystr (first (split-string (buffer-string) "\n" t))) (with-temp-buffer (insert mystr) (goto-char 0) (search-forward "python3" nil t))) (defun run-python () "Call the python interpreter." (interactive) (if (is-python3-p) (setq py-python-command "/usr/bin/python3") (setq py-python-command "/usr/bin/python")) (py-execute-buffer)) </code></pre> <p>This will call <code>python3</code> if "python3" is in the top line of your buffer (shebang, usually). For some reason the <code>(setq py-pyton-command ...)</code> doesn't let you change versions once you've run <code>py-execute-buffer</code> once. That shouldn't be an issue unless you change your file on the same buffer back and forth.</p>
2
2011-05-15T06:39:38Z
[ "python", "emacs", "python-3.x" ]
Both Python 2 and 3 in Emacs
501,626
<p>I have been using Emacs to write Python 2 code. Now I have both Python 2.6 and 3.0 installed on my system, and I need to write Python 3 code as well.</p> <p>Here is how the different versions are set up in /usr/bin:</p> <pre><code>python -&gt; python2.6* python2 -&gt; python2.6* python2.6* python3 -&gt; python3.0* python3.0* </code></pre> <p>Is there any way to set this up so that Emacs uses the correct version of Python, depending on which language I am using? For instance, C-c C-c currently runs the buffer, but it always calls python2.6, even if I am writing Python 3 code.</p>
16
2009-02-01T21:32:47Z
11,674,725
<p>With current <code>python-mode.el</code> shebang is honored.</p> <p>Interactively open a Python shell just with</p> <pre><code>M-x pythonVERSION M-x python </code></pre> <p>will call the installed default.</p> <p><a href="http://launchpad.net/python-mode" rel="nofollow">http://launchpad.net/python-mode</a></p>
0
2012-07-26T17:27:19Z
[ "python", "emacs", "python-3.x" ]
How can I execute Python code without Komodo -ide?
501,817
<p>I do that without the IDE: </p> <pre><code>$ ipython $ edit file.py $ :x (save and close) </code></pre> <p>It executes Python code, but not the one, where I use Pygame. It gives:</p> <blockquote> <p>WARNING: Failure executing file: </p> </blockquote> <p>In the IDE, my code executes.</p>
-1
2009-02-01T23:19:44Z
501,882
<p>If something doesn't work in <code>ipython</code>, try the real Python interpreter (just <code>python</code>); <code>ipython</code> has known bugs, and not infrequently code known to work in the real interpreter fails there.</p> <p>On UNIXlike platforms, your script should start with a shebang -- that is, a line like the following:</p> <pre><code>#!/usr/bin/env python </code></pre> <p>should be the very first line (and should have a standard UNIX line ending). This tells the operating system to execute your code with the first python interpreter found in the <code>PATH</code>, presuming that your script has executable permission set and is invoked as a program.</p> <p>The other option is to start the program manually -- as per the following example:</p> <pre><code>$ python yourprogram.py </code></pre> <p>...or, to use a specific version of the interpreter (if more than one is installed):</p> <pre><code>$ python2.5 yourprogram.py </code></pre>
1
2009-02-02T00:09:58Z
[ "python", "ide", "executable" ]
Simple simulations for Physics in Python?
501,940
<p>I would like to know similar, concrete simulations, as the simulation about watering a field <a href="http://stackoverflow.com/questions/494184/simulation-problem-with-mouse-in-pygame">here</a>.</p> <p>What is your favorite library/internet page for such simulations in Python?</p> <p>I know little Simpy, Numpy and Pygame. I would like to get examples about them.</p>
7
2009-02-02T00:55:03Z
502,377
<p>Here is some simple <a href="http://www.astro.sunysb.edu/mzingale/software/astro/" rel="nofollow">astronomy related python</a>. And here is a <a href="http://www.astro.sunysb.edu/mzingale/pyro/" rel="nofollow">hardcore code</a> from the same guy.</p> <p>And <a href="http://kingkong.amath.washington.edu/claw/examples/index.html" rel="nofollow">Eagleclaw</a> solves and plots various hyperbolic equations using some python. However, most of the code is written in Fortran to do the computations and python to plot the results. If you are studying physics though you may have to get used to this kind of Fortran wrapped code. It is a reality. But this isn't really what your looking for I guess. The good thing it that it is documented in a literate programming style so it should be understandable.</p>
3
2009-02-02T06:35:35Z
[ "python", "modeling", "simulation" ]
Simple simulations for Physics in Python?
501,940
<p>I would like to know similar, concrete simulations, as the simulation about watering a field <a href="http://stackoverflow.com/questions/494184/simulation-problem-with-mouse-in-pygame">here</a>.</p> <p>What is your favorite library/internet page for such simulations in Python?</p> <p>I know little Simpy, Numpy and Pygame. I would like to get examples about them.</p>
7
2009-02-02T00:55:03Z
502,627
<p>If you are looking for some <em>game</em> physics (collisions, deformations, gravity, etc.) which <em>looks</em> real and is reasonably <em>fast</em> consider re-using some <em>physics engine</em> libraries.</p> <p>As a first reference, you may want to look into <a href="http://www.pymunk.org/" rel="nofollow">pymunk</a>, a Python wrapper of <a href="http://wiki.slembcke.net/main/published/Chipmunk" rel="nofollow">Chipmunk</a> 2D physics library. You can find a list of various Open Source physics engines (2D and 3D) in Wikipedia.</p> <p>If you are looking for <em>physically correct</em> simulations, no matter what language you want to use, it will be much <em>slower</em> (almost never real-time), and you need to use some <em>numerical analysis</em> software (and probably to write something yourself). Exact answer depends on the problem you want to solve. It is a fairly complicated field (of math).</p> <p>For example, if you need to do simulations in continuum mechanics or electromagnetism, you probably need Finite Difference, Finite Volume or Finite Element methods. For Python, there are some ready-to-use libraries, for example: <a href="http://www.ctcms.nist.gov/fipy/" rel="nofollow">FiPy</a> (FVM), <a href="http://home.gna.org/getfem/" rel="nofollow">GetFem++</a> (FEM), <a href="http://www.fenics.org/wiki/FEniCS_Project" rel="nofollow">FEniCS/DOLFIN</a> (FEM), and some other.</p>
10
2009-02-02T09:06:01Z
[ "python", "modeling", "simulation" ]
Simple simulations for Physics in Python?
501,940
<p>I would like to know similar, concrete simulations, as the simulation about watering a field <a href="http://stackoverflow.com/questions/494184/simulation-problem-with-mouse-in-pygame">here</a>.</p> <p>What is your favorite library/internet page for such simulations in Python?</p> <p>I know little Simpy, Numpy and Pygame. I would like to get examples about them.</p>
7
2009-02-02T00:55:03Z
503,010
<p>Maybe <a href="http://pyode.sourceforge.net/" rel="nofollow">PyODE</a>?</p>
2
2009-02-02T12:15:30Z
[ "python", "modeling", "simulation" ]
Simple simulations for Physics in Python?
501,940
<p>I would like to know similar, concrete simulations, as the simulation about watering a field <a href="http://stackoverflow.com/questions/494184/simulation-problem-with-mouse-in-pygame">here</a>.</p> <p>What is your favorite library/internet page for such simulations in Python?</p> <p>I know little Simpy, Numpy and Pygame. I would like to get examples about them.</p>
7
2009-02-02T00:55:03Z
505,002
<p>I've heard of <a href="http://www.box2d.org/wiki/index.php?title=PyBox2D" rel="nofollow">PyBox2D</a>, which is a port of the really nice Box2D. To quote the site:</p> <blockquote> <p>Box2D is a feature rich 2d rigid body physics engine, written in C++ by Erin Catto. It has been used in many games, including Crayon Physics Deluxe, winner of the 2008 Independent Game Festival Grand Prize.</p> </blockquote>
1
2009-02-02T21:24:26Z
[ "python", "modeling", "simulation" ]
How to modularize a Python application
501,945
<p>I've got a number of scripts that use common definitions. How do I split them in multiple files? Furthermore, the application can not be installed in any way in my scenario; it must be possible to have an arbitrary number of versions concurrently running and it must work without superuser rights. Solutions I've come up with are:</p> <ul> <li><b>Duplicate code</b> in every script. Messy, and probably the worst scheme.</li> <li><b>Put all scripts and common code in a single directory,</b> and use <code>from . import</code> to load them. The downside of this approach is that I'd like to put my libraries in other directory than the applications.</li> <li><b>Put common code in its own directory</b>, write a <code>__init__.py</code> that imports all submodules and finally use <code>from . import</code> to load them. Keeps code organized, but it's a little bit of overhead to maintain <code>__init__.py</code> and qualify names.</li> <li><b>Add the library directory to <code>sys.path</code> and <code>import</code>.</b> I tend to this, but I'm not sure whether fiddling with <code>sys.path</code> is nice code.</li> <li><b>Load using <code>execfile</code></b> (<code>exec</code> in Python 3). Combines the advantages of the previous two approaches: Only one line per module needed, and I can use a dedicated. On the other hand, this evades the python module concept and polutes the global namespace.</li> <li><b>Write and install a module using <code>distutils</code>.</b> This installs the library for all python scripts and needs superuser rights and impacts other applications and is hence not applicable in my case.</li> </ul> <p>What is the best method?</p>
5
2009-02-02T00:59:26Z
501,958
<p>You can set the <code>PYTHONPATH</code> environment variable to the directory where your library files are located. This adds that path to the library search path and you can use a normal <code>import</code> to import them.</p>
4
2009-02-02T01:13:15Z
[ "python" ]
How to modularize a Python application
501,945
<p>I've got a number of scripts that use common definitions. How do I split them in multiple files? Furthermore, the application can not be installed in any way in my scenario; it must be possible to have an arbitrary number of versions concurrently running and it must work without superuser rights. Solutions I've come up with are:</p> <ul> <li><b>Duplicate code</b> in every script. Messy, and probably the worst scheme.</li> <li><b>Put all scripts and common code in a single directory,</b> and use <code>from . import</code> to load them. The downside of this approach is that I'd like to put my libraries in other directory than the applications.</li> <li><b>Put common code in its own directory</b>, write a <code>__init__.py</code> that imports all submodules and finally use <code>from . import</code> to load them. Keeps code organized, but it's a little bit of overhead to maintain <code>__init__.py</code> and qualify names.</li> <li><b>Add the library directory to <code>sys.path</code> and <code>import</code>.</b> I tend to this, but I'm not sure whether fiddling with <code>sys.path</code> is nice code.</li> <li><b>Load using <code>execfile</code></b> (<code>exec</code> in Python 3). Combines the advantages of the previous two approaches: Only one line per module needed, and I can use a dedicated. On the other hand, this evades the python module concept and polutes the global namespace.</li> <li><b>Write and install a module using <code>distutils</code>.</b> This installs the library for all python scripts and needs superuser rights and impacts other applications and is hence not applicable in my case.</li> </ul> <p>What is the best method?</p>
5
2009-02-02T00:59:26Z
501,960
<p>Another alternative to manually adding the path to <code>sys.path</code> is to use the environment variable <a href="http://docs.python.org/using/cmdline.html#envvar-PYTHONPATH" rel="nofollow"><code>PYTHONPATH</code></a>.</p> <p>Also, <a href="http://docs.python.org/install/index.html" rel="nofollow"><code>distutils</code></a> allows you to specify a custom installation directory using</p> <pre><code> python setup.py install --home=/my/dir </code></pre> <p>However, neither of these may be practical if you need to have multiple versions running simultaneously with the same module names. In that case you're probably best off modifying <code>sys.path</code>.</p>
1
2009-02-02T01:13:51Z
[ "python" ]
How to modularize a Python application
501,945
<p>I've got a number of scripts that use common definitions. How do I split them in multiple files? Furthermore, the application can not be installed in any way in my scenario; it must be possible to have an arbitrary number of versions concurrently running and it must work without superuser rights. Solutions I've come up with are:</p> <ul> <li><b>Duplicate code</b> in every script. Messy, and probably the worst scheme.</li> <li><b>Put all scripts and common code in a single directory,</b> and use <code>from . import</code> to load them. The downside of this approach is that I'd like to put my libraries in other directory than the applications.</li> <li><b>Put common code in its own directory</b>, write a <code>__init__.py</code> that imports all submodules and finally use <code>from . import</code> to load them. Keeps code organized, but it's a little bit of overhead to maintain <code>__init__.py</code> and qualify names.</li> <li><b>Add the library directory to <code>sys.path</code> and <code>import</code>.</b> I tend to this, but I'm not sure whether fiddling with <code>sys.path</code> is nice code.</li> <li><b>Load using <code>execfile</code></b> (<code>exec</code> in Python 3). Combines the advantages of the previous two approaches: Only one line per module needed, and I can use a dedicated. On the other hand, this evades the python module concept and polutes the global namespace.</li> <li><b>Write and install a module using <code>distutils</code>.</b> This installs the library for all python scripts and needs superuser rights and impacts other applications and is hence not applicable in my case.</li> </ul> <p>What is the best method?</p>
5
2009-02-02T00:59:26Z
501,966
<p>I've used the third approach (add the directories to <code>sys.path</code>) for more than one project, and I think it's a valid approach.</p>
1
2009-02-02T01:17:31Z
[ "python" ]
How to modularize a Python application
501,945
<p>I've got a number of scripts that use common definitions. How do I split them in multiple files? Furthermore, the application can not be installed in any way in my scenario; it must be possible to have an arbitrary number of versions concurrently running and it must work without superuser rights. Solutions I've come up with are:</p> <ul> <li><b>Duplicate code</b> in every script. Messy, and probably the worst scheme.</li> <li><b>Put all scripts and common code in a single directory,</b> and use <code>from . import</code> to load them. The downside of this approach is that I'd like to put my libraries in other directory than the applications.</li> <li><b>Put common code in its own directory</b>, write a <code>__init__.py</code> that imports all submodules and finally use <code>from . import</code> to load them. Keeps code organized, but it's a little bit of overhead to maintain <code>__init__.py</code> and qualify names.</li> <li><b>Add the library directory to <code>sys.path</code> and <code>import</code>.</b> I tend to this, but I'm not sure whether fiddling with <code>sys.path</code> is nice code.</li> <li><b>Load using <code>execfile</code></b> (<code>exec</code> in Python 3). Combines the advantages of the previous two approaches: Only one line per module needed, and I can use a dedicated. On the other hand, this evades the python module concept and polutes the global namespace.</li> <li><b>Write and install a module using <code>distutils</code>.</b> This installs the library for all python scripts and needs superuser rights and impacts other applications and is hence not applicable in my case.</li> </ul> <p>What is the best method?</p>
5
2009-02-02T00:59:26Z
502,008
<p>If you have multiple environments which have various combinations of dependencies, a good solution is to use <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">virtualenv</a> to create sandboxed Python environments, each with their own set of installed packages. Each environment will function in the same way as a system-wide Python site-packages setup, but no superuser rights are required to create local environments.</p> <p>Google has <a href="http://www.google.com/search?client=safari&amp;rls=en-us&amp;q=virtualenv&amp;ie=UTF-8&amp;oe=UTF-8" rel="nofollow">plenty of info</a>, but <a href="http://wiki.pylonshq.com/display/pylonscookbook/Using+a+Virtualenv+Sandbox" rel="nofollow">this</a> looks like a pretty good starting point.</p>
3
2009-02-02T01:53:36Z
[ "python" ]
How to modularize a Python application
501,945
<p>I've got a number of scripts that use common definitions. How do I split them in multiple files? Furthermore, the application can not be installed in any way in my scenario; it must be possible to have an arbitrary number of versions concurrently running and it must work without superuser rights. Solutions I've come up with are:</p> <ul> <li><b>Duplicate code</b> in every script. Messy, and probably the worst scheme.</li> <li><b>Put all scripts and common code in a single directory,</b> and use <code>from . import</code> to load them. The downside of this approach is that I'd like to put my libraries in other directory than the applications.</li> <li><b>Put common code in its own directory</b>, write a <code>__init__.py</code> that imports all submodules and finally use <code>from . import</code> to load them. Keeps code organized, but it's a little bit of overhead to maintain <code>__init__.py</code> and qualify names.</li> <li><b>Add the library directory to <code>sys.path</code> and <code>import</code>.</b> I tend to this, but I'm not sure whether fiddling with <code>sys.path</code> is nice code.</li> <li><b>Load using <code>execfile</code></b> (<code>exec</code> in Python 3). Combines the advantages of the previous two approaches: Only one line per module needed, and I can use a dedicated. On the other hand, this evades the python module concept and polutes the global namespace.</li> <li><b>Write and install a module using <code>distutils</code>.</b> This installs the library for all python scripts and needs superuser rights and impacts other applications and is hence not applicable in my case.</li> </ul> <p>What is the best method?</p>
5
2009-02-02T00:59:26Z
502,014
<p>Adding to sys.path (usually using site.addsitedir) is quite common and not particularly frowned upon. Certainly you will want your common working shared stuff to be in modules somewhere convenient.</p> <p>If you are using Python 2.6+ there's already a user-level modules folder you can use without having to add to sys.path or PYTHONPATH. It's ~/.local/lib/python2.6/site-packages on Unix-likes - see <a href="http://www.python.org/dev/peps/pep-0370/" rel="nofollow">PEP 370</a> for more information.</p>
8
2009-02-02T02:00:33Z
[ "python" ]
Finding the workspace size (screen size less the taskbar) using GTK
502,282
<p>How do you create a main window that fills the entire desktop <strong>without covering (or being covered by) the task bar</strong> and <strong>without being maximized</strong>? I can find the entire screen size with and set the main window accordingly with this:</p> <pre><code>window = gtk.Window() screen = window.get_screen() window.resize(screen.get_width(), screen.get_height()) </code></pre> <p>but the bottom of the window is covered by the task bar.</p>
5
2009-02-02T05:38:09Z
508,251
<p>You are totally at the mercy of your window manager for this, and the key issue here is:</p> <blockquote> <p><strong>without being maximized</strong></p> </blockquote> <p>So we are left with a number of hacks, because basically maximization and resizing are two separate things, in order that you might be able to remember where it was when it is unmaximized.</p> <p>So before I show you this hideous hack, I urge you to consider using proper maximization and just be happy with it.</p> <p>So here goes:</p> <pre><code>import gtk # Even I am ashamed by this # Set up a one-time signal handler to detect size changes def _on_size_req(win, req): x, y, w, h = win.get_allocation() print x, y, w, h # just to prove to you its working win.disconnect(win.connection_id) win.unmaximize() win.window.move_resize(x, y, w, h) # Create the window, connect the signal, then maximise it w = gtk.Window() w.show_all() w.connection_id = w.connect('size-request', _on_size_req) # Maximizing will fire the signal handler just once, # unmaximize, and then resize to the previously set size for maximization. w.maximize() # run this monstrosity gtk.main() </code></pre>
9
2009-02-03T18:09:21Z
[ "python", "gtk", "pygtk" ]
Finding the workspace size (screen size less the taskbar) using GTK
502,282
<p>How do you create a main window that fills the entire desktop <strong>without covering (or being covered by) the task bar</strong> and <strong>without being maximized</strong>? I can find the entire screen size with and set the main window accordingly with this:</p> <pre><code>window = gtk.Window() screen = window.get_screen() window.resize(screen.get_width(), screen.get_height()) </code></pre> <p>but the bottom of the window is covered by the task bar.</p>
5
2009-02-02T05:38:09Z
6,521,588
<p>Do you mean making the window <em>fullscreen</em>?</p> <p>Gtk has functions for making windows fullscreen and back, see <a href="http://developer.gnome.org/gtk3/stable/GtkWindow.html#gtk-window-fullscreen" rel="nofollow"><code>gtk_window_fullscreen()</code></a> and <a href="http://developer.gnome.org/gtk3/stable/GtkWindow.html#gtk-window-unfullscreen" rel="nofollow"><code>gtk_window_unfullscreen()</code></a>.</p>
1
2011-06-29T13:41:20Z
[ "python", "gtk", "pygtk" ]
Running SimpleXMLRPCServer in separate thread and shutting down
502,610
<p>I have a class that I wish to test via SimpleXMLRPCServer in python. The way I have my unit test set up is that I create a new thread, and start SimpleXMLRPCServer in that. Then I run all the test, and finally shut down.</p> <p>This is my ServerThread:</p> <pre><code>class ServerThread(Thread): running = True def run(self): self.server = #Creates and starts SimpleXMLRPCServer while (self.running): self.server.handle_request() def stop(self): self.running = False self.server.server_close() </code></pre> <p>The problem is, that calling ServerThread.stop(), followed by Thread.stop() and Thread.join() will not cause the thread to stop properly if it's already waiting for a request in handle_request. And since there doesn't seem to be any interrupt or timeout mechanisms here that I can use, I am at a loss for how I can cleanly shut down the server thread.</p>
2
2009-02-02T08:59:40Z
502,956
<p>Two suggestions.</p> <p>Suggestion One is to use a separate process instead of a separate thread.</p> <ul> <li><p>Create a stand-alone XMLRPC server program.</p></li> <li><p>Start it with <code>subprocess.Popen()</code>. </p></li> <li><p>Kill it when the test is done. In standard OS's (not Windows) the kill works nicely. In Windows, however, there's no trivial kill function, but there are recipes for this.</p></li> </ul> <p>The other suggestion is to have a function in your XMLRPC server which causes server self-destruction. You define a function that calls <code>sys.exit()</code> or <code>os.abort()</code> or raises a similar exception that will stop the process.</p>
1
2009-02-02T11:54:29Z
[ "python", "multithreading", "simplexmlrpcserver" ]
Running SimpleXMLRPCServer in separate thread and shutting down
502,610
<p>I have a class that I wish to test via SimpleXMLRPCServer in python. The way I have my unit test set up is that I create a new thread, and start SimpleXMLRPCServer in that. Then I run all the test, and finally shut down.</p> <p>This is my ServerThread:</p> <pre><code>class ServerThread(Thread): running = True def run(self): self.server = #Creates and starts SimpleXMLRPCServer while (self.running): self.server.handle_request() def stop(self): self.running = False self.server.server_close() </code></pre> <p>The problem is, that calling ServerThread.stop(), followed by Thread.stop() and Thread.join() will not cause the thread to stop properly if it's already waiting for a request in handle_request. And since there doesn't seem to be any interrupt or timeout mechanisms here that I can use, I am at a loss for how I can cleanly shut down the server thread.</p>
2
2009-02-02T08:59:40Z
29,421,095
<p>I had the same problem and after hours of research i solved it by switching from using my own <strong>handle_request()</strong> loop to <strong>serve_forever()</strong> to start the server. </p> <p><strong>serve_forever()</strong> starts an internal loop like yours. This loop can be stopped by calling <strong>shutdown()</strong>. After stopping the loop it is possible to stop the server with <strong>server_close()</strong>. </p> <p>I don't know why this works and the <strong>handle_request()</strong> loop don't, but it does ;P</p> <p>Here is my code:</p> <pre><code>from threading import Thread from xmlrpc.server import SimpleXMLRPCServer from pyWebService.server.service.WebServiceRequestHandler import WebServiceRquestHandler class WebServiceServer(Thread): def __init__(self, ip, port): super(WebServiceServer, self).__init__() self.running = True self.server = SimpleXMLRPCServer((ip, port),requestHandler=WebServiceRquestHandler) self.server.register_introspection_functions() def register_function(self, function): self.server.register_function(function) def run(self): self.server.serve_forever() def stop_server(self): self.server.shutdown() self.server.server_close() print("starting server") webService = WebServiceServer("localhost", 8010) webService.start() print("stopping server") webService.stop_server() webService.join() print("server stopped") </code></pre>
1
2015-04-02T19:38:11Z
[ "python", "multithreading", "simplexmlrpcserver" ]
Converting date between DD/MM/YYYY and YYYY-MM-DD?
502,726
<p>Using a Python script, I need to read a CVS file where dates are formated as DD/MM/YYYY, and convert them to YYYY-MM-DD before saving this into a SQLite database.</p> <p>This almost works, but fails because I don't provide time:</p> <pre><code>from datetime import datetime lastconnection = datetime.strptime("21/12/2008", "%Y-%m-%d") #ValueError: time data did not match format: data=21/12/2008 fmt=%Y-%m-%d print lastconnection </code></pre> <p>I assume there's a method in the datetime object to perform this conversion very easily, but I can't find an example of how to do it. Thank you.</p>
12
2009-02-02T10:01:49Z
502,737
<p>you first would need to convert string into datetime tuple, and then convert that datetime tuple to string, it would go like this:</p> <pre><code>lastconnection = datetime.strptime("21/12/2008", "%d/%m/%Y").strftime('%Y-%m-%d') </code></pre>
8
2009-02-02T10:07:57Z
[ "python", "date" ]
Converting date between DD/MM/YYYY and YYYY-MM-DD?
502,726
<p>Using a Python script, I need to read a CVS file where dates are formated as DD/MM/YYYY, and convert them to YYYY-MM-DD before saving this into a SQLite database.</p> <p>This almost works, but fails because I don't provide time:</p> <pre><code>from datetime import datetime lastconnection = datetime.strptime("21/12/2008", "%Y-%m-%d") #ValueError: time data did not match format: data=21/12/2008 fmt=%Y-%m-%d print lastconnection </code></pre> <p>I assume there's a method in the datetime object to perform this conversion very easily, but I can't find an example of how to do it. Thank you.</p>
12
2009-02-02T10:01:49Z
502,738
<p>Your example code is wrong. This works:</p> <pre><code>import datetime datetime.datetime.strptime("21/12/2008", "%d/%m/%Y").strftime("%Y-%m-%d") </code></pre> <p>The call to strptime() parses the first argument according to the format specified in the second, so those two need to match. Then you can call strftime() to format the result into the desired final format.</p>
33
2009-02-02T10:09:22Z
[ "python", "date" ]
Converting date between DD/MM/YYYY and YYYY-MM-DD?
502,726
<p>Using a Python script, I need to read a CVS file where dates are formated as DD/MM/YYYY, and convert them to YYYY-MM-DD before saving this into a SQLite database.</p> <p>This almost works, but fails because I don't provide time:</p> <pre><code>from datetime import datetime lastconnection = datetime.strptime("21/12/2008", "%Y-%m-%d") #ValueError: time data did not match format: data=21/12/2008 fmt=%Y-%m-%d print lastconnection </code></pre> <p>I assume there's a method in the datetime object to perform this conversion very easily, but I can't find an example of how to do it. Thank you.</p>
12
2009-02-02T10:01:49Z
502,833
<p>Does anyone else else think it's a waste to convert these strings to date/time objects for what is, in the end, a simple text transformation? If you're certain the incoming dates will be valid, you can just use:</p> <pre><code>&gt;&gt;&gt; ddmmyyyy = "21/12/2008" &gt;&gt;&gt; yyyymmdd = ddmmyyyy[6:] + "-" + ddmmyyyy[3:5] + "-" + ddmmyyyy[:2] &gt;&gt;&gt; yyyymmdd '2008-12-21' </code></pre> <p>This will almost certainly be faster than the conversion to and from a date.</p>
1
2009-02-02T10:53:43Z
[ "python", "date" ]
Django: How to create a model dynamically just for testing
502,916
<p>I have a Django app that requires a <code>settings</code> attribute in the form of:</p> <pre><code>RELATED_MODELS = ('appname1.modelname1.attribute1', 'appname1.modelname2.attribute2', 'appname2.modelname3.attribute3', ...) </code></pre> <p>Then hooks their post_save signal to update some other fixed model depending on the <code>attributeN</code> defined.</p> <p>I would like to test this behaviour and tests should work even if this app is the only one in the project (except for its own dependencies, no other wrapper app need to be installed). How can I create and attach/register/activate mock models just for the test database? (or is it possible at all?)</p> <p>Solutions that allow me to use test fixtures would be great.</p>
41
2009-02-02T11:35:52Z
503,435
<p>You can put your tests in a <code>tests/</code> subdirectory of the app (rather than a <code>tests.py</code> file), and include a <code>tests/models.py</code> with the test-only models.</p> <p>Then provide a test-running script (<a href="https://github.com/carljm/django-model-utils/blob/master/runtests.py">example</a>) that includes your <code>tests/</code> "app" in <code>INSTALLED_APPS</code>. (This doesn't work when running app tests from a real project, which won't have the tests app in <code>INSTALLED_APPS</code>, but I rarely find it useful to run reusable app tests from a project, and Django 1.6+ doesn't by default.)</p> <p>(<strong>NOTE</strong>: The alternative dynamic method described below only works in Django 1.1+ if your test case subclasses <code>TransactionTestCase</code> - which slows down your tests significantly - and no longer works at all in Django 1.7+. It's left here only for historical interest; don't use it.)</p> <p>At the beginning of your tests (i.e. in a setUp method, or at the beginning of a set of doctests), you can dynamically add <code>"myapp.tests"</code> to the INSTALLED_APPS setting, and then do this:</p> <pre><code>from django.core.management import call_command from django.db.models import loading loading.cache.loaded = False call_command('syncdb', verbosity=0) </code></pre> <p>Then at the end of your tests, you should clean up by restoring the old version of INSTALLED_APPS and clearing the app cache again.</p> <p><a href="http://www.djangosnippets.org/snippets/1011/">This class</a> encapsulates the pattern so it doesn't clutter up your test code quite as much.</p>
39
2009-02-02T14:49:31Z
[ "python", "django", "unit-testing", "django-models", "mocking" ]
Django: How to create a model dynamically just for testing
502,916
<p>I have a Django app that requires a <code>settings</code> attribute in the form of:</p> <pre><code>RELATED_MODELS = ('appname1.modelname1.attribute1', 'appname1.modelname2.attribute2', 'appname2.modelname3.attribute3', ...) </code></pre> <p>Then hooks their post_save signal to update some other fixed model depending on the <code>attributeN</code> defined.</p> <p>I would like to test this behaviour and tests should work even if this app is the only one in the project (except for its own dependencies, no other wrapper app need to be installed). How can I create and attach/register/activate mock models just for the test database? (or is it possible at all?)</p> <p>Solutions that allow me to use test fixtures would be great.</p>
41
2009-02-02T11:35:52Z
1,827,272
<p>This solution works only for earlier versions of <code>django</code> (before <code>1.7</code>). You can check your version easily:</p> <pre><code>import django django.VERSION &lt; (1, 7) </code></pre> <p>Original response:</p> <p>It's quite strange but form me works very simple pattern:</p> <ol> <li>add tests.py to app which you are going to test,</li> <li>in this file just define testing models,</li> <li>below put your testing code (doctest or TestCase definition),</li> </ol> <p>Below I've put some code which defines Article model which is needed only for tests (it exists in someapp/tests.py and I can test it just with: <em>./manage.py test someapp</em> ):</p> <pre><code>class Article(models.Model): title = models.CharField(max_length=128) description = models.TextField() document = DocumentTextField(template=lambda i: i.description) def __unicode__(self): return self.title __test__ = {"doctest": """ #smuggling model for tests &gt;&gt;&gt; from .tests import Article #testing data &gt;&gt;&gt; by_two = Article.objects.create(title="divisible by two", description="two four six eight") &gt;&gt;&gt; by_three = Article.objects.create(title="divisible by three", description="three six nine") &gt;&gt;&gt; by_four = Article.objects.create(title="divisible by four", description="four four eight") &gt;&gt;&gt; Article.objects.all().search(document='four') [&lt;Article: divisible by two&gt;, &lt;Article: divisible by four&gt;] &gt;&gt;&gt; Article.objects.all().search(document='three') [&lt;Article: divisible by three&gt;] """} </code></pre> <p>Unit tests also working with such model definition.</p>
10
2009-12-01T16:24:59Z
[ "python", "django", "unit-testing", "django-models", "mocking" ]
Django: How to create a model dynamically just for testing
502,916
<p>I have a Django app that requires a <code>settings</code> attribute in the form of:</p> <pre><code>RELATED_MODELS = ('appname1.modelname1.attribute1', 'appname1.modelname2.attribute2', 'appname2.modelname3.attribute3', ...) </code></pre> <p>Then hooks their post_save signal to update some other fixed model depending on the <code>attributeN</code> defined.</p> <p>I would like to test this behaviour and tests should work even if this app is the only one in the project (except for its own dependencies, no other wrapper app need to be installed). How can I create and attach/register/activate mock models just for the test database? (or is it possible at all?)</p> <p>Solutions that allow me to use test fixtures would be great.</p>
41
2009-02-02T11:35:52Z
2,672,444
<p>@paluh's answer requires adding unwanted code to a non-test file and in my experience, @carl's solution does not work with django.test.TestCase which is needed to use fixtures. If you want to use django.test.TestCase, you need to make sure you call syncdb before the fixtures get loaded. This requires overriding the _pre_setup method (putting the code in the setUp method is not sufficient). I use my own version of TestCase that let's me add apps with test models. It is defined as follows:</p> <pre><code>from django.conf import settings from django.core.management import call_command from django.db.models import loading from django import test class TestCase(test.TestCase): apps = () def _pre_setup(self): # Add the models to the db. self._original_installed_apps = list(settings.INSTALLED_APPS) for app in self.apps: settings.INSTALLED_APPS.append(app) loading.cache.loaded = False call_command('syncdb', interactive=False, verbosity=0) # Call the original method that does the fixtures etc. super(TestCase, self)._pre_setup() def _post_teardown(self): # Call the original method. super(TestCase, self)._post_teardown() # Restore the settings. settings.INSTALLED_APPS = self._original_installed_apps loading.cache.loaded = False </code></pre>
17
2010-04-20T04:00:49Z
[ "python", "django", "unit-testing", "django-models", "mocking" ]
Django: How to create a model dynamically just for testing
502,916
<p>I have a Django app that requires a <code>settings</code> attribute in the form of:</p> <pre><code>RELATED_MODELS = ('appname1.modelname1.attribute1', 'appname1.modelname2.attribute2', 'appname2.modelname3.attribute3', ...) </code></pre> <p>Then hooks their post_save signal to update some other fixed model depending on the <code>attributeN</code> defined.</p> <p>I would like to test this behaviour and tests should work even if this app is the only one in the project (except for its own dependencies, no other wrapper app need to be installed). How can I create and attach/register/activate mock models just for the test database? (or is it possible at all?)</p> <p>Solutions that allow me to use test fixtures would be great.</p>
41
2009-02-02T11:35:52Z
8,719,352
<p>I chose a slightly different, albeit more coupled, approach to dynamically creating models just for testing. </p> <p>I keep all my tests in a <code>tests</code> subdirectory that lives in my <code>files</code> app. The <code>models.py</code> file in the <code>tests</code> subdirectory contains my test-only models. The coupled part comes in here, where I need to add the following to my <code>settings.py</code> file:</p> <pre><code># check if we are testing right now TESTING = 'test' in sys.argv if TESTING: # add test packages that have models INSTALLED_APPS += ['files.tests',] </code></pre> <p>I also set db_table in my test model, because otherwise Django would have created the table with the name <code>tests_&lt;model_name&gt;</code>, which may have caused a conflict with other test models in another app. Here's my my test model:</p> <pre><code>class Recipe(models.Model): '''Test-only model to test out thumbnail registration.''' dish_image = models.ImageField(upload_to='recipes/') class Meta: db_table = 'files_tests_recipe' </code></pre>
6
2012-01-03T22:10:32Z
[ "python", "django", "unit-testing", "django-models", "mocking" ]
Django: How to create a model dynamically just for testing
502,916
<p>I have a Django app that requires a <code>settings</code> attribute in the form of:</p> <pre><code>RELATED_MODELS = ('appname1.modelname1.attribute1', 'appname1.modelname2.attribute2', 'appname2.modelname3.attribute3', ...) </code></pre> <p>Then hooks their post_save signal to update some other fixed model depending on the <code>attributeN</code> defined.</p> <p>I would like to test this behaviour and tests should work even if this app is the only one in the project (except for its own dependencies, no other wrapper app need to be installed). How can I create and attach/register/activate mock models just for the test database? (or is it possible at all?)</p> <p>Solutions that allow me to use test fixtures would be great.</p>
41
2009-02-02T11:35:52Z
10,218,628
<p>Here's the pattern that I'm using to do this. </p> <p>I've written this method that I use on a subclassed version of TestCase. It goes as follows:</p> <pre><code>@classmethod def create_models_from_app(cls, app_name): """ Manually create Models (used only for testing) from the specified string app name. Models are loaded from the module "&lt;app_name&gt;.models" """ from django.db import connection, DatabaseError from django.db.models.loading import load_app app = load_app(app_name) from django.core.management import sql from django.core.management.color import no_style sql = sql.sql_create(app, no_style(), connection) cursor = connection.cursor() for statement in sql: try: cursor.execute(statement) except DatabaseError, excn: logger.debug(excn.message) pass </code></pre> <p>Then, I create a special test-specific models.py file in something like <code>myapp/tests/models.py</code> that's not included in INSTALLED_APPS. </p> <p>In my setUp method, I call create_models_from_app('myapp.tests') and it creates the proper tables.</p> <p>The only "gotcha" with this approach is that you don't really want to create the models ever time <code>setUp</code> runs, which is why I catch DatabaseError. I guess the call to this method could go at the top of the test file and that would work a little better. </p>
2
2012-04-18T21:55:11Z
[ "python", "django", "unit-testing", "django-models", "mocking" ]
Django: How to create a model dynamically just for testing
502,916
<p>I have a Django app that requires a <code>settings</code> attribute in the form of:</p> <pre><code>RELATED_MODELS = ('appname1.modelname1.attribute1', 'appname1.modelname2.attribute2', 'appname2.modelname3.attribute3', ...) </code></pre> <p>Then hooks their post_save signal to update some other fixed model depending on the <code>attributeN</code> defined.</p> <p>I would like to test this behaviour and tests should work even if this app is the only one in the project (except for its own dependencies, no other wrapper app need to be installed). How can I create and attach/register/activate mock models just for the test database? (or is it possible at all?)</p> <p>Solutions that allow me to use test fixtures would be great.</p>
41
2009-02-02T11:35:52Z
10,657,706
<p>Combining your answers, specially @slacy's, I did this:</p> <pre><code>class TestCase(test.TestCase): initiated = False @classmethod def setUpClass(cls, *args, **kwargs): if not TestCase.initiated: TestCase.create_models_from_app('myapp.tests') TestCase.initiated = True super(TestCase, cls).setUpClass(*args, **kwargs) @classmethod def create_models_from_app(cls, app_name): """ Manually create Models (used only for testing) from the specified string app name. Models are loaded from the module "&lt;app_name&gt;.models" """ from django.db import connection, DatabaseError from django.db.models.loading import load_app app = load_app(app_name) from django.core.management import sql from django.core.management.color import no_style sql = sql.sql_create(app, no_style(), connection) cursor = connection.cursor() for statement in sql: try: cursor.execute(statement) except DatabaseError, excn: logger.debug(excn.message) </code></pre> <p>With this, you don't try to create db tables more than once, and you don't need to change your INSTALLED_APPS.</p>
2
2012-05-18T18:13:06Z
[ "python", "django", "unit-testing", "django-models", "mocking" ]
Django: How to create a model dynamically just for testing
502,916
<p>I have a Django app that requires a <code>settings</code> attribute in the form of:</p> <pre><code>RELATED_MODELS = ('appname1.modelname1.attribute1', 'appname1.modelname2.attribute2', 'appname2.modelname3.attribute3', ...) </code></pre> <p>Then hooks their post_save signal to update some other fixed model depending on the <code>attributeN</code> defined.</p> <p>I would like to test this behaviour and tests should work even if this app is the only one in the project (except for its own dependencies, no other wrapper app need to be installed). How can I create and attach/register/activate mock models just for the test database? (or is it possible at all?)</p> <p>Solutions that allow me to use test fixtures would be great.</p>
41
2009-02-02T11:35:52Z
15,460,736
<p>Quoting from <a href="http://stackoverflow.com/a/6960879/2179211">a related answer</a>:</p> <blockquote> <p>If you want models defined for testing only then you should check out <a href="https://code.djangoproject.com/ticket/7835">Django ticket #7835</a> in particular <a href="https://code.djangoproject.com/ticket/7835#comment:24">comment #24</a> part of which is given below:</p> <blockquote> <p>Apparently you can simply define models directly in your tests.py. Syncdb never imports tests.py, so those models won't get synced to the normal db, but they will get synced to the test database, and can be used in tests.</p> </blockquote> </blockquote>
8
2013-03-17T12:34:18Z
[ "python", "django", "unit-testing", "django-models", "mocking" ]
Django: How to create a model dynamically just for testing
502,916
<p>I have a Django app that requires a <code>settings</code> attribute in the form of:</p> <pre><code>RELATED_MODELS = ('appname1.modelname1.attribute1', 'appname1.modelname2.attribute2', 'appname2.modelname3.attribute3', ...) </code></pre> <p>Then hooks their post_save signal to update some other fixed model depending on the <code>attributeN</code> defined.</p> <p>I would like to test this behaviour and tests should work even if this app is the only one in the project (except for its own dependencies, no other wrapper app need to be installed). How can I create and attach/register/activate mock models just for the test database? (or is it possible at all?)</p> <p>Solutions that allow me to use test fixtures would be great.</p>
41
2009-02-02T11:35:52Z
24,907,652
<p>If you are writing a reusable django-app, <strong>create a minimal test-dedicated app for it</strong>!</p> <pre><code>$ django-admin.py startproject test_myapp_project $ django-admin.py startapp test_myapp </code></pre> <p>add both <code>myapp</code> and <code>test_myapp</code> to the <code>INSTALLED_APPS</code>, create your models there and it's good to go!</p> <p>I have gone through all these answers as well as django ticket <a href="https://code.djangoproject.com/ticket/7835" rel="nofollow">7835</a>, and I finally went for a totally different approach. I wanted my app (somehow extending queryset.values() ) to be able to be tested in isolation; also, my package does include some models and I wanted a clean distinction between test models and package ones.</p> <p>That's when I realized it was easier to add a very small django project in the package! This also allows a much cleaner separation of code IMHO:</p> <p>In there you can cleanly and without any hack define your models, and you know they will be created when you run your tests from in there!</p> <p>If you are not writing an independent, reusable app you can still go this way: create a <code>test_myapp</code> app, and add it to your INSTALLED_APPS only in a separate <code>settings_test_myapp.py</code>!</p>
0
2014-07-23T10:10:49Z
[ "python", "django", "unit-testing", "django-models", "mocking" ]
Django: How to create a model dynamically just for testing
502,916
<p>I have a Django app that requires a <code>settings</code> attribute in the form of:</p> <pre><code>RELATED_MODELS = ('appname1.modelname1.attribute1', 'appname1.modelname2.attribute2', 'appname2.modelname3.attribute3', ...) </code></pre> <p>Then hooks their post_save signal to update some other fixed model depending on the <code>attributeN</code> defined.</p> <p>I would like to test this behaviour and tests should work even if this app is the only one in the project (except for its own dependencies, no other wrapper app need to be installed). How can I create and attach/register/activate mock models just for the test database? (or is it possible at all?)</p> <p>Solutions that allow me to use test fixtures would be great.</p>
41
2009-02-02T11:35:52Z
32,825,308
<p>I shared my <a href="https://github.com/erm0l0v/django-fake-model" rel="nofollow">solution</a> that I use in my projects. Maybe it helps someone.</p> <p><code>pip install django-fake-model</code></p> <p>Two simple steps to create fake model:</p> <p>1) Define model in any file (I usualy define model in test file near a test case)</p> <pre><code>from django_fake_model import models as f class MyFakeModel(f.FakeModel): name = models.CharField(max_length=100) </code></pre> <p>2) Add decorator <code>@MyFakeModel.fake_me</code> to your <em>TestCase</em> or to test function.</p> <pre><code>class MyTest(TestCase): @MyFakeModel.fake_me def test_create_model(self): MyFakeModel.objects.create(name='123') model = MyFakeModel.objects.get(name='123') self.assertEqual(model.name, '123') </code></pre> <p>This decorator creates table in your database before each test and remove the table after test.</p> <p>Also you may <em>create</em>/<em>delete</em> table manually: <code>MyFakeModel.create_table()</code> / <code>MyFakeModel.delete_table()</code></p>
2
2015-09-28T14:17:53Z
[ "python", "django", "unit-testing", "django-models", "mocking" ]
Django: How to create a model dynamically just for testing
502,916
<p>I have a Django app that requires a <code>settings</code> attribute in the form of:</p> <pre><code>RELATED_MODELS = ('appname1.modelname1.attribute1', 'appname1.modelname2.attribute2', 'appname2.modelname3.attribute3', ...) </code></pre> <p>Then hooks their post_save signal to update some other fixed model depending on the <code>attributeN</code> defined.</p> <p>I would like to test this behaviour and tests should work even if this app is the only one in the project (except for its own dependencies, no other wrapper app need to be installed). How can I create and attach/register/activate mock models just for the test database? (or is it possible at all?)</p> <p>Solutions that allow me to use test fixtures would be great.</p>
41
2009-02-02T11:35:52Z
34,900,947
<p>I've figured out a way for test-only models for django 1.7+.</p> <p>The basic idea is, make your <code>tests</code> an app, and add your <code>tests</code> to <code>INSTALLED_APPS</code>.</p> <p>Here's an example:</p> <pre><code>$ ls common __init__.py admin.py apps.py fixtures models.py pagination.py tests validators.py views.py $ ls common/tests __init__.py apps.py models.py serializers.py test_filter.py test_pagination.py test_validators.py views.py </code></pre> <p>And I have different <code>settings</code> for different purposes(ref: <a href="https://code.djangoproject.com/wiki/SplitSettings#Accessingandmodifyingexistingsettings" rel="nofollow">splitting up the settings file</a>), namely:</p> <ul> <li><code>settings/default.py</code>: base settings file</li> <li><code>settings/production.py</code>: for production</li> <li><code>settings/development.py</code>: for development</li> <li><code>settings/testing.py</code>: for testing.</li> </ul> <p>And in <code>settings/testing.py</code>, you can modify <code>INSTALLED_APPS</code>:</p> <p><code>settings/testing.py</code>:</p> <pre><code>from default import * DEBUG = True INSTALLED_APPS += ['common', 'common.tests'] </code></pre> <p>And make sure that you have set a proper label for your tests app, namely, </p> <p><code>common/tests/apps.py</code></p> <pre><code>from django.apps import AppConfig class CommonTestsConfig(AppConfig): name = 'common.tests' label = 'common_tests' </code></pre> <p><code>common/tests/__init__.py</code>, set up proper <code>AppConfig</code>(ref: <a href="https://docs.djangoproject.com/en/1.9/ref/applications/" rel="nofollow">Django Applications</a>).</p> <pre><code>default_app_config = 'common.tests.apps.CommonTestsConfig' </code></pre> <p>Then, generate db migration by</p> <pre><code>python manage.py makemigrations --settings=&lt;your_project_name&gt;.settings.testing tests </code></pre> <p>Finally, you can run your test with param <code>--settings=&lt;your_project_name&gt;.settings.testing</code>. </p> <p>If you use py.test, you can even drop a <code>pytest.ini</code> file along with django's <code>manage.py</code>.</p> <p><code>py.test</code></p> <pre><code>[pytest] DJANGO_SETTINGS_MODULE=kungfu.settings.testing </code></pre>
0
2016-01-20T13:08:48Z
[ "python", "django", "unit-testing", "django-models", "mocking" ]
How to parse nagios status.dat file?
503,148
<p>I'd like to parse status.dat file for nagios3 and output as xml with a python script. The xml part is the easy one but how do I go about parsing the file? Use multi line regex? It's possible the file will be large as many hosts and services are monitored, will loading the whole file in memory be wise?<br /> I only need to extract services that have critical state and host they belong to.</p> <p>Any help and pointing in the right direction will be highly appreciated.</p> <p><strong>LE</strong> Here's how the file looks:</p> <pre><code>######################################## # NAGIOS STATUS FILE # # THIS FILE IS AUTOMATICALLY GENERATED # BY NAGIOS. DO NOT MODIFY THIS FILE! ######################################## info { created=1233491098 version=2.11 } program { modified_host_attributes=0 modified_service_attributes=0 nagios_pid=15015 daemon_mode=1 program_start=1233490393 last_command_check=0 last_log_rotation=0 enable_notifications=1 active_service_checks_enabled=1 passive_service_checks_enabled=1 active_host_checks_enabled=1 passive_host_checks_enabled=1 enable_event_handlers=1 obsess_over_services=0 obsess_over_hosts=0 check_service_freshness=1 check_host_freshness=0 enable_flap_detection=0 enable_failure_prediction=1 process_performance_data=0 global_host_event_handler= global_service_event_handler= total_external_command_buffer_slots=4096 used_external_command_buffer_slots=0 high_external_command_buffer_slots=0 total_check_result_buffer_slots=4096 used_check_result_buffer_slots=0 high_check_result_buffer_slots=2 } host { host_name=localhost modified_attributes=0 check_command=check-host-alive event_handler= has_been_checked=1 should_be_scheduled=0 check_execution_time=0.019 check_latency=0.000 check_type=0 current_state=0 last_hard_state=0 plugin_output=PING OK - Packet loss = 0%, RTA = 3.57 ms performance_data= last_check=1233490883 next_check=0 current_attempt=1 max_attempts=10 state_type=1 last_state_change=1233489475 last_hard_state_change=1233489475 last_time_up=1233490883 last_time_down=0 last_time_unreachable=0 last_notification=0 next_notification=0 no_more_notifications=0 current_notification_number=0 notifications_enabled=1 problem_has_been_acknowledged=0 acknowledgement_type=0 active_checks_enabled=1 passive_checks_enabled=1 event_handler_enabled=1 flap_detection_enabled=1 failure_prediction_enabled=1 process_performance_data=1 obsess_over_host=1 last_update=1233491098 is_flapping=0 percent_state_change=0.00 scheduled_downtime_depth=0 } service { host_name=gateway service_description=PING modified_attributes=0 check_command=check_ping!100.0,20%!500.0,60% event_handler= has_been_checked=1 should_be_scheduled=1 check_execution_time=4.017 check_latency=0.210 check_type=0 current_state=0 last_hard_state=0 current_attempt=1 max_attempts=4 state_type=1 last_state_change=1233489432 last_hard_state_change=1233489432 last_time_ok=1233491078 last_time_warning=0 last_time_unknown=0 last_time_critical=0 plugin_output=PING OK - Packet loss = 0%, RTA = 2.98 ms performance_data= last_check=1233491078 next_check=1233491378 current_notification_number=0 last_notification=0 next_notification=0 no_more_notifications=0 notifications_enabled=1 active_checks_enabled=1 passive_checks_enabled=1 event_handler_enabled=1 problem_has_been_acknowledged=0 acknowledgement_type=0 flap_detection_enabled=1 failure_prediction_enabled=1 process_performance_data=1 obsess_over_service=1 last_update=1233491098 is_flapping=0 percent_state_change=0.00 scheduled_downtime_depth=0 } </code></pre> <p>It can have any number of hosts and a host can have any number of services.</p>
4
2009-02-02T13:11:09Z
503,532
<p>Don't know nagios and its config file, but the structure seems pretty simple:</p> <pre><code># comment identifier { attribute= attribute=value } </code></pre> <p>which can simply be translated to</p> <pre><code>&lt;identifier&gt; &lt;attribute name="attribute-name"&gt;attribute-value&lt;/attribute&gt; &lt;/identifier&gt; </code></pre> <p>all contained inside a root-level &lt;nagios> tag.</p> <p>I don't see line breaks in the values. Does nagios have multi-line values?</p> <p>You need to take care of equal signs within attribute values, so set your regex to non-greedy.</p>
2
2009-02-02T15:12:37Z
[ "python", "parsing", "nagios" ]
How to parse nagios status.dat file?
503,148
<p>I'd like to parse status.dat file for nagios3 and output as xml with a python script. The xml part is the easy one but how do I go about parsing the file? Use multi line regex? It's possible the file will be large as many hosts and services are monitored, will loading the whole file in memory be wise?<br /> I only need to extract services that have critical state and host they belong to.</p> <p>Any help and pointing in the right direction will be highly appreciated.</p> <p><strong>LE</strong> Here's how the file looks:</p> <pre><code>######################################## # NAGIOS STATUS FILE # # THIS FILE IS AUTOMATICALLY GENERATED # BY NAGIOS. DO NOT MODIFY THIS FILE! ######################################## info { created=1233491098 version=2.11 } program { modified_host_attributes=0 modified_service_attributes=0 nagios_pid=15015 daemon_mode=1 program_start=1233490393 last_command_check=0 last_log_rotation=0 enable_notifications=1 active_service_checks_enabled=1 passive_service_checks_enabled=1 active_host_checks_enabled=1 passive_host_checks_enabled=1 enable_event_handlers=1 obsess_over_services=0 obsess_over_hosts=0 check_service_freshness=1 check_host_freshness=0 enable_flap_detection=0 enable_failure_prediction=1 process_performance_data=0 global_host_event_handler= global_service_event_handler= total_external_command_buffer_slots=4096 used_external_command_buffer_slots=0 high_external_command_buffer_slots=0 total_check_result_buffer_slots=4096 used_check_result_buffer_slots=0 high_check_result_buffer_slots=2 } host { host_name=localhost modified_attributes=0 check_command=check-host-alive event_handler= has_been_checked=1 should_be_scheduled=0 check_execution_time=0.019 check_latency=0.000 check_type=0 current_state=0 last_hard_state=0 plugin_output=PING OK - Packet loss = 0%, RTA = 3.57 ms performance_data= last_check=1233490883 next_check=0 current_attempt=1 max_attempts=10 state_type=1 last_state_change=1233489475 last_hard_state_change=1233489475 last_time_up=1233490883 last_time_down=0 last_time_unreachable=0 last_notification=0 next_notification=0 no_more_notifications=0 current_notification_number=0 notifications_enabled=1 problem_has_been_acknowledged=0 acknowledgement_type=0 active_checks_enabled=1 passive_checks_enabled=1 event_handler_enabled=1 flap_detection_enabled=1 failure_prediction_enabled=1 process_performance_data=1 obsess_over_host=1 last_update=1233491098 is_flapping=0 percent_state_change=0.00 scheduled_downtime_depth=0 } service { host_name=gateway service_description=PING modified_attributes=0 check_command=check_ping!100.0,20%!500.0,60% event_handler= has_been_checked=1 should_be_scheduled=1 check_execution_time=4.017 check_latency=0.210 check_type=0 current_state=0 last_hard_state=0 current_attempt=1 max_attempts=4 state_type=1 last_state_change=1233489432 last_hard_state_change=1233489432 last_time_ok=1233491078 last_time_warning=0 last_time_unknown=0 last_time_critical=0 plugin_output=PING OK - Packet loss = 0%, RTA = 2.98 ms performance_data= last_check=1233491078 next_check=1233491378 current_notification_number=0 last_notification=0 next_notification=0 no_more_notifications=0 notifications_enabled=1 active_checks_enabled=1 passive_checks_enabled=1 event_handler_enabled=1 problem_has_been_acknowledged=0 acknowledgement_type=0 flap_detection_enabled=1 failure_prediction_enabled=1 process_performance_data=1 obsess_over_service=1 last_update=1233491098 is_flapping=0 percent_state_change=0.00 scheduled_downtime_depth=0 } </code></pre> <p>It can have any number of hosts and a host can have any number of services.</p>
4
2009-02-02T13:11:09Z
503,862
<p>You can do something like this:</p> <pre><code>def parseConf(filename): conf = [] with open(filename, 'r') as f: for i in f.readlines(): if i[0] == '#': continue matchID = re.search(r"([\w]+) {", i) matchAttr = re.search(r"[ ]*([\w]+)=([\w\d]*)", i) matchEndID = re.search(r"[ ]*}", i) if matchID: identifier = matchID.group(1) cur = [identifier, {}] elif matchAttr: attribute = matchAttr.group(1) value = matchAttr.group(2) cur[1][attribute] = value elif matchEndID: conf.append(cur) return conf def conf2xml(filename): conf = parseConf(filename) xml = '' for ID in conf: xml += '&lt;%s&gt;\n' % ID[0] for attr in ID[1]: xml += '\t&lt;attribute name="%s"&gt;%s&lt;/attribute&gt;\n' % \ (attr, ID[1][attr]) xml += '&lt;/%s&gt;\n' % ID[0] return xml </code></pre> <p>Then try to do:</p> <pre><code>print conf2xml('conf.dat') </code></pre>
2
2009-02-02T16:45:17Z
[ "python", "parsing", "nagios" ]
How to parse nagios status.dat file?
503,148
<p>I'd like to parse status.dat file for nagios3 and output as xml with a python script. The xml part is the easy one but how do I go about parsing the file? Use multi line regex? It's possible the file will be large as many hosts and services are monitored, will loading the whole file in memory be wise?<br /> I only need to extract services that have critical state and host they belong to.</p> <p>Any help and pointing in the right direction will be highly appreciated.</p> <p><strong>LE</strong> Here's how the file looks:</p> <pre><code>######################################## # NAGIOS STATUS FILE # # THIS FILE IS AUTOMATICALLY GENERATED # BY NAGIOS. DO NOT MODIFY THIS FILE! ######################################## info { created=1233491098 version=2.11 } program { modified_host_attributes=0 modified_service_attributes=0 nagios_pid=15015 daemon_mode=1 program_start=1233490393 last_command_check=0 last_log_rotation=0 enable_notifications=1 active_service_checks_enabled=1 passive_service_checks_enabled=1 active_host_checks_enabled=1 passive_host_checks_enabled=1 enable_event_handlers=1 obsess_over_services=0 obsess_over_hosts=0 check_service_freshness=1 check_host_freshness=0 enable_flap_detection=0 enable_failure_prediction=1 process_performance_data=0 global_host_event_handler= global_service_event_handler= total_external_command_buffer_slots=4096 used_external_command_buffer_slots=0 high_external_command_buffer_slots=0 total_check_result_buffer_slots=4096 used_check_result_buffer_slots=0 high_check_result_buffer_slots=2 } host { host_name=localhost modified_attributes=0 check_command=check-host-alive event_handler= has_been_checked=1 should_be_scheduled=0 check_execution_time=0.019 check_latency=0.000 check_type=0 current_state=0 last_hard_state=0 plugin_output=PING OK - Packet loss = 0%, RTA = 3.57 ms performance_data= last_check=1233490883 next_check=0 current_attempt=1 max_attempts=10 state_type=1 last_state_change=1233489475 last_hard_state_change=1233489475 last_time_up=1233490883 last_time_down=0 last_time_unreachable=0 last_notification=0 next_notification=0 no_more_notifications=0 current_notification_number=0 notifications_enabled=1 problem_has_been_acknowledged=0 acknowledgement_type=0 active_checks_enabled=1 passive_checks_enabled=1 event_handler_enabled=1 flap_detection_enabled=1 failure_prediction_enabled=1 process_performance_data=1 obsess_over_host=1 last_update=1233491098 is_flapping=0 percent_state_change=0.00 scheduled_downtime_depth=0 } service { host_name=gateway service_description=PING modified_attributes=0 check_command=check_ping!100.0,20%!500.0,60% event_handler= has_been_checked=1 should_be_scheduled=1 check_execution_time=4.017 check_latency=0.210 check_type=0 current_state=0 last_hard_state=0 current_attempt=1 max_attempts=4 state_type=1 last_state_change=1233489432 last_hard_state_change=1233489432 last_time_ok=1233491078 last_time_warning=0 last_time_unknown=0 last_time_critical=0 plugin_output=PING OK - Packet loss = 0%, RTA = 2.98 ms performance_data= last_check=1233491078 next_check=1233491378 current_notification_number=0 last_notification=0 next_notification=0 no_more_notifications=0 notifications_enabled=1 active_checks_enabled=1 passive_checks_enabled=1 event_handler_enabled=1 problem_has_been_acknowledged=0 acknowledgement_type=0 flap_detection_enabled=1 failure_prediction_enabled=1 process_performance_data=1 obsess_over_service=1 last_update=1233491098 is_flapping=0 percent_state_change=0.00 scheduled_downtime_depth=0 } </code></pre> <p>It can have any number of hosts and a host can have any number of services.</p>
4
2009-02-02T13:11:09Z
576,497
<p>Nagiosity does exactly what you want:</p> <p><a href="http://code.google.com/p/nagiosity/">http://code.google.com/p/nagiosity/</a></p>
5
2009-02-23T04:11:04Z
[ "python", "parsing", "nagios" ]
How to parse nagios status.dat file?
503,148
<p>I'd like to parse status.dat file for nagios3 and output as xml with a python script. The xml part is the easy one but how do I go about parsing the file? Use multi line regex? It's possible the file will be large as many hosts and services are monitored, will loading the whole file in memory be wise?<br /> I only need to extract services that have critical state and host they belong to.</p> <p>Any help and pointing in the right direction will be highly appreciated.</p> <p><strong>LE</strong> Here's how the file looks:</p> <pre><code>######################################## # NAGIOS STATUS FILE # # THIS FILE IS AUTOMATICALLY GENERATED # BY NAGIOS. DO NOT MODIFY THIS FILE! ######################################## info { created=1233491098 version=2.11 } program { modified_host_attributes=0 modified_service_attributes=0 nagios_pid=15015 daemon_mode=1 program_start=1233490393 last_command_check=0 last_log_rotation=0 enable_notifications=1 active_service_checks_enabled=1 passive_service_checks_enabled=1 active_host_checks_enabled=1 passive_host_checks_enabled=1 enable_event_handlers=1 obsess_over_services=0 obsess_over_hosts=0 check_service_freshness=1 check_host_freshness=0 enable_flap_detection=0 enable_failure_prediction=1 process_performance_data=0 global_host_event_handler= global_service_event_handler= total_external_command_buffer_slots=4096 used_external_command_buffer_slots=0 high_external_command_buffer_slots=0 total_check_result_buffer_slots=4096 used_check_result_buffer_slots=0 high_check_result_buffer_slots=2 } host { host_name=localhost modified_attributes=0 check_command=check-host-alive event_handler= has_been_checked=1 should_be_scheduled=0 check_execution_time=0.019 check_latency=0.000 check_type=0 current_state=0 last_hard_state=0 plugin_output=PING OK - Packet loss = 0%, RTA = 3.57 ms performance_data= last_check=1233490883 next_check=0 current_attempt=1 max_attempts=10 state_type=1 last_state_change=1233489475 last_hard_state_change=1233489475 last_time_up=1233490883 last_time_down=0 last_time_unreachable=0 last_notification=0 next_notification=0 no_more_notifications=0 current_notification_number=0 notifications_enabled=1 problem_has_been_acknowledged=0 acknowledgement_type=0 active_checks_enabled=1 passive_checks_enabled=1 event_handler_enabled=1 flap_detection_enabled=1 failure_prediction_enabled=1 process_performance_data=1 obsess_over_host=1 last_update=1233491098 is_flapping=0 percent_state_change=0.00 scheduled_downtime_depth=0 } service { host_name=gateway service_description=PING modified_attributes=0 check_command=check_ping!100.0,20%!500.0,60% event_handler= has_been_checked=1 should_be_scheduled=1 check_execution_time=4.017 check_latency=0.210 check_type=0 current_state=0 last_hard_state=0 current_attempt=1 max_attempts=4 state_type=1 last_state_change=1233489432 last_hard_state_change=1233489432 last_time_ok=1233491078 last_time_warning=0 last_time_unknown=0 last_time_critical=0 plugin_output=PING OK - Packet loss = 0%, RTA = 2.98 ms performance_data= last_check=1233491078 next_check=1233491378 current_notification_number=0 last_notification=0 next_notification=0 no_more_notifications=0 notifications_enabled=1 active_checks_enabled=1 passive_checks_enabled=1 event_handler_enabled=1 problem_has_been_acknowledged=0 acknowledgement_type=0 flap_detection_enabled=1 failure_prediction_enabled=1 process_performance_data=1 obsess_over_service=1 last_update=1233491098 is_flapping=0 percent_state_change=0.00 scheduled_downtime_depth=0 } </code></pre> <p>It can have any number of hosts and a host can have any number of services.</p>
4
2009-02-02T13:11:09Z
2,570,062
<p>Pfft, get yerself mk_livestatus. <a href="http://mathias-kettner.de/checkmk_livestatus.html" rel="nofollow">http://mathias-kettner.de/checkmk_livestatus.html</a></p>
9
2010-04-03T02:46:05Z
[ "python", "parsing", "nagios" ]
How to parse nagios status.dat file?
503,148
<p>I'd like to parse status.dat file for nagios3 and output as xml with a python script. The xml part is the easy one but how do I go about parsing the file? Use multi line regex? It's possible the file will be large as many hosts and services are monitored, will loading the whole file in memory be wise?<br /> I only need to extract services that have critical state and host they belong to.</p> <p>Any help and pointing in the right direction will be highly appreciated.</p> <p><strong>LE</strong> Here's how the file looks:</p> <pre><code>######################################## # NAGIOS STATUS FILE # # THIS FILE IS AUTOMATICALLY GENERATED # BY NAGIOS. DO NOT MODIFY THIS FILE! ######################################## info { created=1233491098 version=2.11 } program { modified_host_attributes=0 modified_service_attributes=0 nagios_pid=15015 daemon_mode=1 program_start=1233490393 last_command_check=0 last_log_rotation=0 enable_notifications=1 active_service_checks_enabled=1 passive_service_checks_enabled=1 active_host_checks_enabled=1 passive_host_checks_enabled=1 enable_event_handlers=1 obsess_over_services=0 obsess_over_hosts=0 check_service_freshness=1 check_host_freshness=0 enable_flap_detection=0 enable_failure_prediction=1 process_performance_data=0 global_host_event_handler= global_service_event_handler= total_external_command_buffer_slots=4096 used_external_command_buffer_slots=0 high_external_command_buffer_slots=0 total_check_result_buffer_slots=4096 used_check_result_buffer_slots=0 high_check_result_buffer_slots=2 } host { host_name=localhost modified_attributes=0 check_command=check-host-alive event_handler= has_been_checked=1 should_be_scheduled=0 check_execution_time=0.019 check_latency=0.000 check_type=0 current_state=0 last_hard_state=0 plugin_output=PING OK - Packet loss = 0%, RTA = 3.57 ms performance_data= last_check=1233490883 next_check=0 current_attempt=1 max_attempts=10 state_type=1 last_state_change=1233489475 last_hard_state_change=1233489475 last_time_up=1233490883 last_time_down=0 last_time_unreachable=0 last_notification=0 next_notification=0 no_more_notifications=0 current_notification_number=0 notifications_enabled=1 problem_has_been_acknowledged=0 acknowledgement_type=0 active_checks_enabled=1 passive_checks_enabled=1 event_handler_enabled=1 flap_detection_enabled=1 failure_prediction_enabled=1 process_performance_data=1 obsess_over_host=1 last_update=1233491098 is_flapping=0 percent_state_change=0.00 scheduled_downtime_depth=0 } service { host_name=gateway service_description=PING modified_attributes=0 check_command=check_ping!100.0,20%!500.0,60% event_handler= has_been_checked=1 should_be_scheduled=1 check_execution_time=4.017 check_latency=0.210 check_type=0 current_state=0 last_hard_state=0 current_attempt=1 max_attempts=4 state_type=1 last_state_change=1233489432 last_hard_state_change=1233489432 last_time_ok=1233491078 last_time_warning=0 last_time_unknown=0 last_time_critical=0 plugin_output=PING OK - Packet loss = 0%, RTA = 2.98 ms performance_data= last_check=1233491078 next_check=1233491378 current_notification_number=0 last_notification=0 next_notification=0 no_more_notifications=0 notifications_enabled=1 active_checks_enabled=1 passive_checks_enabled=1 event_handler_enabled=1 problem_has_been_acknowledged=0 acknowledgement_type=0 flap_detection_enabled=1 failure_prediction_enabled=1 process_performance_data=1 obsess_over_service=1 last_update=1233491098 is_flapping=0 percent_state_change=0.00 scheduled_downtime_depth=0 } </code></pre> <p>It can have any number of hosts and a host can have any number of services.</p>
4
2009-02-02T13:11:09Z
2,977,812
<p>If you slightly tweak Andrea's solution you can use that code to parse both the status.dat as well as the objects.cache</p> <pre><code>def parseConf(source): conf = [] for line in source.splitlines(): line=line.strip() matchID = re.match(r"(?:\s*define)?\s*(\w+)\s+{", line) matchAttr = re.match(r"\s*(\w+)(?:=|\s+)(.*)", line) matchEndID = re.match(r"\s*}", line) if len(line) == 0 or line[0]=='#': pass elif matchID: identifier = matchID.group(1) cur = [identifier, {}] elif matchAttr: attribute = matchAttr.group(1) value = matchAttr.group(2).strip() cur[1][attribute] = value elif matchEndID and cur: conf.append(cur) del cur return conf </code></pre> <p>It is a little puzzling why nagios chose to use two different formats for these files, but once you've parsed them both into some usable python objects you can do quite a bit of magic through the external command file.</p> <p>If anybody has a solution for getting this into a a real xml dom that'd be awesome.</p>
2
2010-06-04T21:08:35Z
[ "python", "parsing", "nagios" ]
How to parse nagios status.dat file?
503,148
<p>I'd like to parse status.dat file for nagios3 and output as xml with a python script. The xml part is the easy one but how do I go about parsing the file? Use multi line regex? It's possible the file will be large as many hosts and services are monitored, will loading the whole file in memory be wise?<br /> I only need to extract services that have critical state and host they belong to.</p> <p>Any help and pointing in the right direction will be highly appreciated.</p> <p><strong>LE</strong> Here's how the file looks:</p> <pre><code>######################################## # NAGIOS STATUS FILE # # THIS FILE IS AUTOMATICALLY GENERATED # BY NAGIOS. DO NOT MODIFY THIS FILE! ######################################## info { created=1233491098 version=2.11 } program { modified_host_attributes=0 modified_service_attributes=0 nagios_pid=15015 daemon_mode=1 program_start=1233490393 last_command_check=0 last_log_rotation=0 enable_notifications=1 active_service_checks_enabled=1 passive_service_checks_enabled=1 active_host_checks_enabled=1 passive_host_checks_enabled=1 enable_event_handlers=1 obsess_over_services=0 obsess_over_hosts=0 check_service_freshness=1 check_host_freshness=0 enable_flap_detection=0 enable_failure_prediction=1 process_performance_data=0 global_host_event_handler= global_service_event_handler= total_external_command_buffer_slots=4096 used_external_command_buffer_slots=0 high_external_command_buffer_slots=0 total_check_result_buffer_slots=4096 used_check_result_buffer_slots=0 high_check_result_buffer_slots=2 } host { host_name=localhost modified_attributes=0 check_command=check-host-alive event_handler= has_been_checked=1 should_be_scheduled=0 check_execution_time=0.019 check_latency=0.000 check_type=0 current_state=0 last_hard_state=0 plugin_output=PING OK - Packet loss = 0%, RTA = 3.57 ms performance_data= last_check=1233490883 next_check=0 current_attempt=1 max_attempts=10 state_type=1 last_state_change=1233489475 last_hard_state_change=1233489475 last_time_up=1233490883 last_time_down=0 last_time_unreachable=0 last_notification=0 next_notification=0 no_more_notifications=0 current_notification_number=0 notifications_enabled=1 problem_has_been_acknowledged=0 acknowledgement_type=0 active_checks_enabled=1 passive_checks_enabled=1 event_handler_enabled=1 flap_detection_enabled=1 failure_prediction_enabled=1 process_performance_data=1 obsess_over_host=1 last_update=1233491098 is_flapping=0 percent_state_change=0.00 scheduled_downtime_depth=0 } service { host_name=gateway service_description=PING modified_attributes=0 check_command=check_ping!100.0,20%!500.0,60% event_handler= has_been_checked=1 should_be_scheduled=1 check_execution_time=4.017 check_latency=0.210 check_type=0 current_state=0 last_hard_state=0 current_attempt=1 max_attempts=4 state_type=1 last_state_change=1233489432 last_hard_state_change=1233489432 last_time_ok=1233491078 last_time_warning=0 last_time_unknown=0 last_time_critical=0 plugin_output=PING OK - Packet loss = 0%, RTA = 2.98 ms performance_data= last_check=1233491078 next_check=1233491378 current_notification_number=0 last_notification=0 next_notification=0 no_more_notifications=0 notifications_enabled=1 active_checks_enabled=1 passive_checks_enabled=1 event_handler_enabled=1 problem_has_been_acknowledged=0 acknowledgement_type=0 flap_detection_enabled=1 failure_prediction_enabled=1 process_performance_data=1 obsess_over_service=1 last_update=1233491098 is_flapping=0 percent_state_change=0.00 scheduled_downtime_depth=0 } </code></pre> <p>It can have any number of hosts and a host can have any number of services.</p>
4
2009-02-02T13:11:09Z
9,318,153
<p>For the last several months I've written and released a tool that that parses the Nagios status.dat and objects.cache and builds a model that allows for some really useful manipulation of Nagios data. We use it to drive an internal operations dashboard that is a simplified 'mini' Nagios. Its under continual development and I've neglected testing and documentation but the code isn't too crazy and I feel fairly easy to follow.</p> <p>Let me know what you think... <a href="https://github.com/zebpalmer/NagParser" rel="nofollow">https://github.com/zebpalmer/NagParser</a></p>
2
2012-02-16T19:55:52Z
[ "python", "parsing", "nagios" ]
How to parse nagios status.dat file?
503,148
<p>I'd like to parse status.dat file for nagios3 and output as xml with a python script. The xml part is the easy one but how do I go about parsing the file? Use multi line regex? It's possible the file will be large as many hosts and services are monitored, will loading the whole file in memory be wise?<br /> I only need to extract services that have critical state and host they belong to.</p> <p>Any help and pointing in the right direction will be highly appreciated.</p> <p><strong>LE</strong> Here's how the file looks:</p> <pre><code>######################################## # NAGIOS STATUS FILE # # THIS FILE IS AUTOMATICALLY GENERATED # BY NAGIOS. DO NOT MODIFY THIS FILE! ######################################## info { created=1233491098 version=2.11 } program { modified_host_attributes=0 modified_service_attributes=0 nagios_pid=15015 daemon_mode=1 program_start=1233490393 last_command_check=0 last_log_rotation=0 enable_notifications=1 active_service_checks_enabled=1 passive_service_checks_enabled=1 active_host_checks_enabled=1 passive_host_checks_enabled=1 enable_event_handlers=1 obsess_over_services=0 obsess_over_hosts=0 check_service_freshness=1 check_host_freshness=0 enable_flap_detection=0 enable_failure_prediction=1 process_performance_data=0 global_host_event_handler= global_service_event_handler= total_external_command_buffer_slots=4096 used_external_command_buffer_slots=0 high_external_command_buffer_slots=0 total_check_result_buffer_slots=4096 used_check_result_buffer_slots=0 high_check_result_buffer_slots=2 } host { host_name=localhost modified_attributes=0 check_command=check-host-alive event_handler= has_been_checked=1 should_be_scheduled=0 check_execution_time=0.019 check_latency=0.000 check_type=0 current_state=0 last_hard_state=0 plugin_output=PING OK - Packet loss = 0%, RTA = 3.57 ms performance_data= last_check=1233490883 next_check=0 current_attempt=1 max_attempts=10 state_type=1 last_state_change=1233489475 last_hard_state_change=1233489475 last_time_up=1233490883 last_time_down=0 last_time_unreachable=0 last_notification=0 next_notification=0 no_more_notifications=0 current_notification_number=0 notifications_enabled=1 problem_has_been_acknowledged=0 acknowledgement_type=0 active_checks_enabled=1 passive_checks_enabled=1 event_handler_enabled=1 flap_detection_enabled=1 failure_prediction_enabled=1 process_performance_data=1 obsess_over_host=1 last_update=1233491098 is_flapping=0 percent_state_change=0.00 scheduled_downtime_depth=0 } service { host_name=gateway service_description=PING modified_attributes=0 check_command=check_ping!100.0,20%!500.0,60% event_handler= has_been_checked=1 should_be_scheduled=1 check_execution_time=4.017 check_latency=0.210 check_type=0 current_state=0 last_hard_state=0 current_attempt=1 max_attempts=4 state_type=1 last_state_change=1233489432 last_hard_state_change=1233489432 last_time_ok=1233491078 last_time_warning=0 last_time_unknown=0 last_time_critical=0 plugin_output=PING OK - Packet loss = 0%, RTA = 2.98 ms performance_data= last_check=1233491078 next_check=1233491378 current_notification_number=0 last_notification=0 next_notification=0 no_more_notifications=0 notifications_enabled=1 active_checks_enabled=1 passive_checks_enabled=1 event_handler_enabled=1 problem_has_been_acknowledged=0 acknowledgement_type=0 flap_detection_enabled=1 failure_prediction_enabled=1 process_performance_data=1 obsess_over_service=1 last_update=1233491098 is_flapping=0 percent_state_change=0.00 scheduled_downtime_depth=0 } </code></pre> <p>It can have any number of hosts and a host can have any number of services.</p>
4
2009-02-02T13:11:09Z
35,311,918
<p>Having shamelessly stolen from the above examples, Here's a version build for Python 2.4 that returns a dict containing arrays of nagios sections.</p> <pre><code>def parseConf(source): conf = {} patID=re.compile(r"(?:\s*define)?\s*(\w+)\s+{") patAttr=re.compile(r"\s*(\w+)(?:=|\s+)(.*)") patEndID=re.compile(r"\s*}") for line in source.splitlines(): line=line.strip() matchID = patID.match(line) matchAttr = patAttr.match(line) matchEndID = patEndID.match( line) if len(line) == 0 or line[0]=='#': pass elif matchID: identifier = matchID.group(1) cur = [identifier, {}] elif matchAttr: attribute = matchAttr.group(1) value = matchAttr.group(2).strip() cur[1][attribute] = value elif matchEndID and cur: conf.setdefault(cur[0],[]).append(cur[1]) del cur return conf </code></pre> <p>To get all Names your Host which have contactgroups beginning with 'devops':</p> <pre><code>nagcfg=parseConf(stringcontaingcompleteconfig) hostlist=[host['host_name'] for host in nagcfg['host'] if host['contact_groups'].startswith('devops')] </code></pre>
1
2016-02-10T09:57:58Z
[ "python", "parsing", "nagios" ]
Query distinct list of choices for Django form with App Engine Datastore
503,295
<p>I've been trying to figure this out for hours across a couple of days, and can not get it to work. I've been everywhere. I'll continue trying to figure it out, but was hoping for a quicker solution. I'm using App Engine datastore + Django.</p> <p>Using a query in a view and custom forms, I was able to get a list to the form but then I was not able to post. I have been trying to figure out how to dynamically add the choices as part of the Django form... I've tried various ways with no success. Help!</p> <p>Below are the two models. I'd like to get a distinct list of address_id to show in the location field in InfoForm. This fields could (and maybe should) be named the same, but I thought it'd be easier if they were named different.</p> <pre><code>class Info(db.Model): user = db.UserProperty() location = db.StringProperty() info = db.StringProperty() created = db.DateTimeProperty(auto_now_add=True) modified = db.DateTimeProperty(auto_now=True) class Locations(db.Model): user = db.UserProperty() address_id = db.StringProperty() address = db.StringProperty() class InfoForm(djangoforms.ModelForm): info = forms.ChoiceField(choices=INFO_CHOICES) location = forms.ChoiceField() class Meta: model = Info exclude = ['user','created','modified'] </code></pre>
1
2009-02-02T14:02:55Z
504,227
<p>I'm not familiar with App Engine Datastore, but I'm guessing you probably want to do something along these lines:</p> <pre><code>class InfoForm(djangoforms.ModelForm): def __init__(self, *args, **kwargs): super(InfoForm, self).__init__(*args, **kwargs) choices = [(r.id, r.info) for r in Info.objects.filter(...)] self.fields['info'] = ChoiceField(choices=choices) </code></pre> <p>By assigning <code>info</code> dynamically, you would then exclude this line from your <code>InfoForm</code> class:</p> <pre><code> info = forms.ChoiceField(choices=INFO_CHOICES) </code></pre>
1
2009-02-02T18:15:45Z
[ "python", "django", "google-app-engine" ]
django facebook connect missing libs?
503,462
<p>I'm trying to integrate some photo related functionality with my site and facebook. I checked out facebook connect and it seems like the way to go for this (since I don't want to make an app, just have users authenticate and then grab some content from facebook to integrate into our site)</p> <p>First of all, if you think there is a better way to do this (infinite session maybe?) let me know.</p> <p>Otherwise here is the problem I'm having... I downloaded <a href="http://code.google.com/p/django-fbconnect/" rel="nofollow">django-fbconnect</a> and installed it as an app (as per the readme.txt included in the svn) but python is complaining about a missing signals.py</p> <pre><code>Error: No module named signals </code></pre> <p>which I assume should be fbconnect/signals.py because of this line of code:</p> <pre><code>from fbconnect.signals import facebook_update </code></pre> <p>Anyway does anyone have experience with django-fbconnect? or any advice on getting the developer to update google code?</p> <p>Thanks</p> <p><strong>edit</strong>: Found this: "<a href="http://nyquistrate.com/django/facebook-connect/" rel="nofollow">Integrating Facebook Connect with Django in 15 minutes</a>" which uses middleware instead of the django-fbconnect app. I prefer the app because it's lighter and the code is clearer. Also, it sticks to the 'everything is an app' culture of django. but I guess I'll look into this other possibility</p> <p><strong>edit 2</strong>: I contacted the original author of django-fbconnect, and he graciously updated the project with the missing file (he also answered on this post)</p>
0
2009-02-02T14:57:05Z
512,919
<p>the solution proposeed by van gale (removing the lines which reference the signals.py file) work well enough. I think I may end up needing to write my own signals.py eventually... I keep you updated.</p> <p>Anyway here's is the answer:</p> <p><b><s>Remove the functionality and all uses of it, provided by the signals.py</s></b></p> <p><s>it's kind of crappy, but oh well</s></p> <p>The missing file has been added to the google code project! :)</p>
0
2009-02-04T19:28:55Z
[ "python", "django", "facebook", "integration", "fbconnect" ]
django facebook connect missing libs?
503,462
<p>I'm trying to integrate some photo related functionality with my site and facebook. I checked out facebook connect and it seems like the way to go for this (since I don't want to make an app, just have users authenticate and then grab some content from facebook to integrate into our site)</p> <p>First of all, if you think there is a better way to do this (infinite session maybe?) let me know.</p> <p>Otherwise here is the problem I'm having... I downloaded <a href="http://code.google.com/p/django-fbconnect/" rel="nofollow">django-fbconnect</a> and installed it as an app (as per the readme.txt included in the svn) but python is complaining about a missing signals.py</p> <pre><code>Error: No module named signals </code></pre> <p>which I assume should be fbconnect/signals.py because of this line of code:</p> <pre><code>from fbconnect.signals import facebook_update </code></pre> <p>Anyway does anyone have experience with django-fbconnect? or any advice on getting the developer to update google code?</p> <p>Thanks</p> <p><strong>edit</strong>: Found this: "<a href="http://nyquistrate.com/django/facebook-connect/" rel="nofollow">Integrating Facebook Connect with Django in 15 minutes</a>" which uses middleware instead of the django-fbconnect app. I prefer the app because it's lighter and the code is clearer. Also, it sticks to the 'everything is an app' culture of django. but I guess I'll look into this other possibility</p> <p><strong>edit 2</strong>: I contacted the original author of django-fbconnect, and he graciously updated the project with the missing file (he also answered on this post)</p>
0
2009-02-02T14:57:05Z
519,805
<p>I've just added the missing file folks. Sorry for the inconveniences. :/</p>
2
2009-02-06T10:31:00Z
[ "python", "django", "facebook", "integration", "fbconnect" ]
Why is IronPython faster than the Official Python Interpreter
504,716
<p>According to this: </p> <p><a href="http://www.codeplex.com/IronPython/Wiki/View.aspx?title=IP20VsCPy25Perf&amp;referringTitle=IronPython%20Performance">http://www.codeplex.com/IronPython/Wiki/View.aspx?title=IP20VsCPy25Perf&amp;referringTitle=IronPython%20Performance</a></p> <p>IronPython (Python for .Net) is faster than regular Python (cPython) on the same machine. Why is this? I would think compiled C code would always be faster than the equivalent CLI bytecode.</p>
8
2009-02-02T20:21:28Z
504,725
<p>Python code doesn't get compiled to C, Python itself is written in C and interprets Python bytecode. CIL gets compiled to machine code, which is why you see better performance when using IronPython.</p>
37
2009-02-02T20:23:27Z
[ "python", "performance", "ironpython" ]
Why is IronPython faster than the Official Python Interpreter
504,716
<p>According to this: </p> <p><a href="http://www.codeplex.com/IronPython/Wiki/View.aspx?title=IP20VsCPy25Perf&amp;referringTitle=IronPython%20Performance">http://www.codeplex.com/IronPython/Wiki/View.aspx?title=IP20VsCPy25Perf&amp;referringTitle=IronPython%20Performance</a></p> <p>IronPython (Python for .Net) is faster than regular Python (cPython) on the same machine. Why is this? I would think compiled C code would always be faster than the equivalent CLI bytecode.</p>
8
2009-02-02T20:21:28Z
504,740
<p>Could it be explained by this notation on the page you linked to:</p> <blockquote> <p>Due to site caching in the Dynamic Language Runtime, IronPython performs better with more PyStone passes than the default value</p> </blockquote>
3
2009-02-02T20:26:06Z
[ "python", "performance", "ironpython" ]
Why is IronPython faster than the Official Python Interpreter
504,716
<p>According to this: </p> <p><a href="http://www.codeplex.com/IronPython/Wiki/View.aspx?title=IP20VsCPy25Perf&amp;referringTitle=IronPython%20Performance">http://www.codeplex.com/IronPython/Wiki/View.aspx?title=IP20VsCPy25Perf&amp;referringTitle=IronPython%20Performance</a></p> <p>IronPython (Python for .Net) is faster than regular Python (cPython) on the same machine. Why is this? I would think compiled C code would always be faster than the equivalent CLI bytecode.</p>
8
2009-02-02T20:21:28Z
506,956
<p>You're right, C is a lot faster. That's why in those results CPython is twice as fast when it comes to dictionaries, which are almost pure C. On the other hand, Python code is not compiled, it's interpreted. Function calls in CPython are terribly slow. But on the other hand: </p> <pre><code>TryRaiseExcept: +4478.9% </code></pre> <p>Now, there's where IronPython get is horribly wrong.</p> <p>And then, there is this PyPy project, with one of the objectives being Just-In-Time compiler. There is even subset of Python, called RPython (Reduced Python) which can be statically compiled. Which of course is a <strong>lot</strong> faster.</p>
8
2009-02-03T12:49:08Z
[ "python", "performance", "ironpython" ]
Why is IronPython faster than the Official Python Interpreter
504,716
<p>According to this: </p> <p><a href="http://www.codeplex.com/IronPython/Wiki/View.aspx?title=IP20VsCPy25Perf&amp;referringTitle=IronPython%20Performance">http://www.codeplex.com/IronPython/Wiki/View.aspx?title=IP20VsCPy25Perf&amp;referringTitle=IronPython%20Performance</a></p> <p>IronPython (Python for .Net) is faster than regular Python (cPython) on the same machine. Why is this? I would think compiled C code would always be faster than the equivalent CLI bytecode.</p>
8
2009-02-02T20:21:28Z
620,976
<p>I'm not sure exactly how you're drawing the conclusion that IronPython is faster than CPython. The link that you post seems to indicate that they're good at different things (like exceptions as has been pointed out).</p>
5
2009-03-07T00:21:05Z
[ "python", "performance", "ironpython" ]
Why is IronPython faster than the Official Python Interpreter
504,716
<p>According to this: </p> <p><a href="http://www.codeplex.com/IronPython/Wiki/View.aspx?title=IP20VsCPy25Perf&amp;referringTitle=IronPython%20Performance">http://www.codeplex.com/IronPython/Wiki/View.aspx?title=IP20VsCPy25Perf&amp;referringTitle=IronPython%20Performance</a></p> <p>IronPython (Python for .Net) is faster than regular Python (cPython) on the same machine. Why is this? I would think compiled C code would always be faster than the equivalent CLI bytecode.</p>
8
2009-02-02T20:21:28Z
830,892
<p>Wandering off your question "Why?", to "Oh, really?" The "good at different things" (Jason Baker) is right on. For example, cpython beats IronPython hands down start up time. </p> <pre><code>c:\Python26\python.exe Hello.py c:\IronPython\ipy.exe Hello.py </code></pre> <p>Cpython executes a basic hello world nearly instantly(&lt;100ms), where IronPython has an startup overhead of 4 or 5 seconds. This annoys me, but not enough to keep me from using IronPython. </p>
5
2009-05-06T17:59:51Z
[ "python", "performance", "ironpython" ]
Py2exe for Python 3.0
505,230
<p>I am looking for a Python3.0 version of "py2exe". I tried running 2to3 on the source for py2exe but the code remained broken.</p> <p>Any ideas?</p>
28
2009-02-02T22:28:40Z
506,005
<p>The <code>py2exe</code> and <code>2to3</code> programs serve completely different purposes, so I'm not sure what your ultimate goal is.</p> <p>If you want to build an executable from a working Python program, use the version of <code>py2exe</code> that is suitable for whichever Python you are using (version 2 or version 3).</p> <p>If you want to convert an existing Python 2 program to Python 3, use <code>2to3</code> plus any additional editing as necessary. The Python 3 documentation describes <a href="http://docs.python.org/3.0/whatsnew/3.0.html#porting-to-python-3-0" rel="nofollow">the conversion process in more detail</a>.</p> <p><strong>Update</strong>: I now understand that you might have been trying to run <code>2to3</code> against <code>py2exe</code> itself to try to make a Python 3 compatible version. Unfortunately, this is definitely beyond the capabilities of <code>2to3</code>. You will probably have to wait for the <a href="http://www.py2exe.org/" rel="nofollow">py2exe project</a> to release a Python 3 compatible version.</p>
7
2009-02-03T04:24:49Z
[ "python", "python-3.x", "py2exe" ]
Py2exe for Python 3.0
505,230
<p>I am looking for a Python3.0 version of "py2exe". I tried running 2to3 on the source for py2exe but the code remained broken.</p> <p>Any ideas?</p>
28
2009-02-02T22:28:40Z
633,648
<h3>Update 2014-05-15</h3> <p>py2exe for Python 3.x is now released! <a href="https://pypi.python.org/pypi/py2exe">Get it on PyPI</a>.</p> <h3>Old information</h3> <p>Have a look at the py2exe SourceForge project SVN repository at:</p> <p><a href="http://py2exe.svn.sourceforge.net/">http://py2exe.svn.sourceforge.net/</a></p> <p>The last I looked at it, it said the last update was August 2009. But keep an eye on that to see if there's any Python 3 work in-progress.</p> <p>I've also submitted two feature requests on the py2exe tracker. So far, no feedback on them:</p> <ul> <li><a href="http://sourceforge.net/tracker/?func=detail&amp;aid=3011276&amp;group_id=15583&amp;atid=365583">Support Python 3.x</a></li> <li><a href="http://sourceforge.net/tracker/?func=detail&amp;aid=3031912&amp;group_id=15583&amp;atid=365583">Project roadmap</a></li> </ul>
27
2009-03-11T07:33:42Z
[ "python", "python-3.x", "py2exe" ]
Py2exe for Python 3.0
505,230
<p>I am looking for a Python3.0 version of "py2exe". I tried running 2to3 on the source for py2exe but the code remained broken.</p> <p>Any ideas?</p>
28
2009-02-02T22:28:40Z
1,263,200
<p>Did you check out <a href="http://cx-freeze.sourceforge.net/">cx_Freeze</a>? It seems to create standalone executables from your Python scripts, including support for Python 3.0 and 3.1</p>
27
2009-08-11T22:00:16Z
[ "python", "python-3.x", "py2exe" ]
Py2exe for Python 3.0
505,230
<p>I am looking for a Python3.0 version of "py2exe". I tried running 2to3 on the source for py2exe but the code remained broken.</p> <p>Any ideas?</p>
28
2009-02-02T22:28:40Z
23,638,686
<h1>py2exe for Python3 is out!</h1> <p>Here is the original bug report:<br> <a href="http://sourceforge.net/projects/py2exe/">http://sourceforge.net/projects/py2exe/</a></p> <p>Here is the comment mentioning the release:<br> <a href="http://sourceforge.net/projects/py2exe/">http://sourceforge.net/projects/py2exe/</a></p> <p>Here is the package on pypi:<br> <a href="https://pypi.python.org/pypi/py2exe/0.9.2.0">https://pypi.python.org/pypi/py2exe/0.9.2.0</a></p> <p><strong>Note that py2exe for Python 3 only supports Python 3.3 and above!</strong></p> <p><strong>A huge thank you to the py2exe development team!</strong></p>
8
2014-05-13T18:15:48Z
[ "python", "python-3.x", "py2exe" ]
Py2exe for Python 3.0
505,230
<p>I am looking for a Python3.0 version of "py2exe". I tried running 2to3 on the source for py2exe but the code remained broken.</p> <p>Any ideas?</p>
28
2009-02-02T22:28:40Z
35,556,519
<p>If you have easy setup installed, type <code>pip install py2exe</code> in a shell to install.</p>
0
2016-02-22T14:44:21Z
[ "python", "python-3.x", "py2exe" ]
Closures in Python
505,559
<p>I've been trying to learn Python, and while I'm enthusiastic about using closures in Python, I've been having trouble getting some code to work properly:</p> <pre><code>def memoize(fn): def get(key): return (False,) def vset(key, value): global get oldget = get def newget(ky): if key==ky: return (True, value) return oldget(ky) get = newget def mfun(*args): cache = get(args) if (cache[0]): return cache[1] val = apply(fn, args) vset(args, val) return val return mfun def fib(x): if x&lt;2: return x return fib(x-1)+fib(x-2) def fibm(x): if x&lt;2: return x return fibm(x-1)+fibm(x-2) fibm = memoize(fibm) </code></pre> <p>Basically, what this is supposed to do is use closures to maintain the memoized state of the function. I realize there are probably many faster, easier to read, and in general more 'Pythonic' ways to implement this; however, my goal is to understand exactly how closures work in Python, and how they differ from Lisp, so I'm not interested in alternative solutions, just why my code doesn't work and what I can do (if anything) to fix it.</p> <p>The problem I'm running into is when I try to use <code>fibm</code> - Python insists that <code>get</code> isn't defined:</p> <pre><code>Python 2.6.1 (r261:67515, Feb 1 2009, 11:39:55) [GCC 4.0.1 (Apple Inc. build 5488)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import memoize &gt;&gt;&gt; memoize.fibm(35) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "memoize.py", line 14, in mfun cache = get(args) NameError: global name 'get' is not defined &gt;&gt;&gt; </code></pre> <p>Seeing as I'm new to Python, I don't know if I've done something wrong, or if this is just a limitation of the language. I'm hoping it's the former. :-)</p>
6
2009-02-03T00:13:06Z
505,594
<p>You want to put <code>global get</code> at the beginning of <em>every</em> function (except <code>get</code> itself).</p> <p>the <code>def get</code> is an assignment to the name <code>get</code>, so you want get to be declared global before that.</p> <p>Putting <code>global get</code> in mfun and vset makes them work. I can't point to the scoping rules that makes this necessary, but it works ;-)</p> <p>Your conses are quite lispy too... :)</p>
0
2009-02-03T00:24:59Z
[ "python", "closures", "lexical-scope" ]
Closures in Python
505,559
<p>I've been trying to learn Python, and while I'm enthusiastic about using closures in Python, I've been having trouble getting some code to work properly:</p> <pre><code>def memoize(fn): def get(key): return (False,) def vset(key, value): global get oldget = get def newget(ky): if key==ky: return (True, value) return oldget(ky) get = newget def mfun(*args): cache = get(args) if (cache[0]): return cache[1] val = apply(fn, args) vset(args, val) return val return mfun def fib(x): if x&lt;2: return x return fib(x-1)+fib(x-2) def fibm(x): if x&lt;2: return x return fibm(x-1)+fibm(x-2) fibm = memoize(fibm) </code></pre> <p>Basically, what this is supposed to do is use closures to maintain the memoized state of the function. I realize there are probably many faster, easier to read, and in general more 'Pythonic' ways to implement this; however, my goal is to understand exactly how closures work in Python, and how they differ from Lisp, so I'm not interested in alternative solutions, just why my code doesn't work and what I can do (if anything) to fix it.</p> <p>The problem I'm running into is when I try to use <code>fibm</code> - Python insists that <code>get</code> isn't defined:</p> <pre><code>Python 2.6.1 (r261:67515, Feb 1 2009, 11:39:55) [GCC 4.0.1 (Apple Inc. build 5488)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import memoize &gt;&gt;&gt; memoize.fibm(35) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "memoize.py", line 14, in mfun cache = get(args) NameError: global name 'get' is not defined &gt;&gt;&gt; </code></pre> <p>Seeing as I'm new to Python, I don't know if I've done something wrong, or if this is just a limitation of the language. I'm hoping it's the former. :-)</p>
6
2009-02-03T00:13:06Z
505,596
<p>The problem is in your scoping, not in your closures. If you're up for some heavy reading, then you can try <a href="http://www.python.org/dev/peps/pep-3104/">http://www.python.org/dev/peps/pep-3104/</a>.</p> <p>If that's not the case, here's the simple explanation:</p> <p>The problem is in the statement <code>global get</code> . <code>global</code> refers to the outermost scope, and since there isn't any global function <code>get</code>, it throws.</p> <p>What you need, is an access specifier for variables in the enclosing scope, and not the global scope.</p> <p>In python 3.0, as I've tested, the <code>nonlocal</code> keyword is exactly what you need, in the place of <code>global</code>.</p> <pre><code>nonlocal get ... </code></pre> <p>In python 2.x, I just removed the <code>global get</code> and the <code>oldget</code> references and it works properly.</p>
7
2009-02-03T00:26:25Z
[ "python", "closures", "lexical-scope" ]
Closures in Python
505,559
<p>I've been trying to learn Python, and while I'm enthusiastic about using closures in Python, I've been having trouble getting some code to work properly:</p> <pre><code>def memoize(fn): def get(key): return (False,) def vset(key, value): global get oldget = get def newget(ky): if key==ky: return (True, value) return oldget(ky) get = newget def mfun(*args): cache = get(args) if (cache[0]): return cache[1] val = apply(fn, args) vset(args, val) return val return mfun def fib(x): if x&lt;2: return x return fib(x-1)+fib(x-2) def fibm(x): if x&lt;2: return x return fibm(x-1)+fibm(x-2) fibm = memoize(fibm) </code></pre> <p>Basically, what this is supposed to do is use closures to maintain the memoized state of the function. I realize there are probably many faster, easier to read, and in general more 'Pythonic' ways to implement this; however, my goal is to understand exactly how closures work in Python, and how they differ from Lisp, so I'm not interested in alternative solutions, just why my code doesn't work and what I can do (if anything) to fix it.</p> <p>The problem I'm running into is when I try to use <code>fibm</code> - Python insists that <code>get</code> isn't defined:</p> <pre><code>Python 2.6.1 (r261:67515, Feb 1 2009, 11:39:55) [GCC 4.0.1 (Apple Inc. build 5488)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import memoize &gt;&gt;&gt; memoize.fibm(35) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "memoize.py", line 14, in mfun cache = get(args) NameError: global name 'get' is not defined &gt;&gt;&gt; </code></pre> <p>Seeing as I'm new to Python, I don't know if I've done something wrong, or if this is just a limitation of the language. I'm hoping it's the former. :-)</p>
6
2009-02-03T00:13:06Z
505,598
<p>Probably because you want the <em>global</em> get while it isn't a global? By the way, apply is deprecated, use fn(*args) instead.</p> <pre><code>def memoize(fn): def get(key): return (False,) def vset(key, value): def newget(ky): if key==ky: return (True, value) return get(ky) get = newget def mfun(*args): cache = get(args) if (cache[0]): return cache[1] val = fn(*args) vset(args, val) return val return mfun def fib(x): if x&lt;2: return x return fib(x-1)+fib(x-2) def fibm(x): if x&lt;2: return x return fibm(x-1)+fibm(x-2) fibm = memoize(fibm) </code></pre>
0
2009-02-03T00:27:20Z
[ "python", "closures", "lexical-scope" ]
Closures in Python
505,559
<p>I've been trying to learn Python, and while I'm enthusiastic about using closures in Python, I've been having trouble getting some code to work properly:</p> <pre><code>def memoize(fn): def get(key): return (False,) def vset(key, value): global get oldget = get def newget(ky): if key==ky: return (True, value) return oldget(ky) get = newget def mfun(*args): cache = get(args) if (cache[0]): return cache[1] val = apply(fn, args) vset(args, val) return val return mfun def fib(x): if x&lt;2: return x return fib(x-1)+fib(x-2) def fibm(x): if x&lt;2: return x return fibm(x-1)+fibm(x-2) fibm = memoize(fibm) </code></pre> <p>Basically, what this is supposed to do is use closures to maintain the memoized state of the function. I realize there are probably many faster, easier to read, and in general more 'Pythonic' ways to implement this; however, my goal is to understand exactly how closures work in Python, and how they differ from Lisp, so I'm not interested in alternative solutions, just why my code doesn't work and what I can do (if anything) to fix it.</p> <p>The problem I'm running into is when I try to use <code>fibm</code> - Python insists that <code>get</code> isn't defined:</p> <pre><code>Python 2.6.1 (r261:67515, Feb 1 2009, 11:39:55) [GCC 4.0.1 (Apple Inc. build 5488)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import memoize &gt;&gt;&gt; memoize.fibm(35) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "memoize.py", line 14, in mfun cache = get(args) NameError: global name 'get' is not defined &gt;&gt;&gt; </code></pre> <p>Seeing as I'm new to Python, I don't know if I've done something wrong, or if this is just a limitation of the language. I'm hoping it's the former. :-)</p>
6
2009-02-03T00:13:06Z
505,663
<pre><code>def memoize(fn): get = [lambda key: (False, None)] def vset(args): value = fn(*args) oldget = get[0] def newget(key): if args == key: return (True, value) return oldget(key) get[0] = newget return value def mfun(*args): found, value = get[0](args) if found: return value return vset(args) return mfun CALLS = 0 def fib(x): global CALLS CALLS += 1 if x&lt;2: return x return fib(x-1)+fib(x-2) @memoize def fibm(x): global CALLS CALLS += 1 if x&lt;2: return x return fibm(x-1)+fibm(x-2) CALLS = 0 print "fib(35) is", fib(35), "and took", CALLS, "calls" CALLS = 0 print "fibm(35) is", fibm(35), "and took", CALLS, "calls" </code></pre> <p>Output is:</p> <pre><code>fib(35) is 9227465 and took 29860703 calls fibm(35) is 9227465 and took 36 calls </code></pre> <p>Similar to other answers, however this one works. :)</p> <p>The important change from the code in the question is assigning to a non-global non-local (get); however, I also made some improvements while trying to maintain your <code>*</code>cough<code>*</code><em>broken</em><code>*</code>cough<code>*</code> closure use. Usually the cache is a dict instead of a linked list of closures.</p>
7
2009-02-03T00:57:24Z
[ "python", "closures", "lexical-scope" ]
Closures in Python
505,559
<p>I've been trying to learn Python, and while I'm enthusiastic about using closures in Python, I've been having trouble getting some code to work properly:</p> <pre><code>def memoize(fn): def get(key): return (False,) def vset(key, value): global get oldget = get def newget(ky): if key==ky: return (True, value) return oldget(ky) get = newget def mfun(*args): cache = get(args) if (cache[0]): return cache[1] val = apply(fn, args) vset(args, val) return val return mfun def fib(x): if x&lt;2: return x return fib(x-1)+fib(x-2) def fibm(x): if x&lt;2: return x return fibm(x-1)+fibm(x-2) fibm = memoize(fibm) </code></pre> <p>Basically, what this is supposed to do is use closures to maintain the memoized state of the function. I realize there are probably many faster, easier to read, and in general more 'Pythonic' ways to implement this; however, my goal is to understand exactly how closures work in Python, and how they differ from Lisp, so I'm not interested in alternative solutions, just why my code doesn't work and what I can do (if anything) to fix it.</p> <p>The problem I'm running into is when I try to use <code>fibm</code> - Python insists that <code>get</code> isn't defined:</p> <pre><code>Python 2.6.1 (r261:67515, Feb 1 2009, 11:39:55) [GCC 4.0.1 (Apple Inc. build 5488)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import memoize &gt;&gt;&gt; memoize.fibm(35) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "memoize.py", line 14, in mfun cache = get(args) NameError: global name 'get' is not defined &gt;&gt;&gt; </code></pre> <p>Seeing as I'm new to Python, I don't know if I've done something wrong, or if this is just a limitation of the language. I'm hoping it's the former. :-)</p>
6
2009-02-03T00:13:06Z
505,669
<p><code>Get</code> is not global, but local to the surrounding function, that's why the <code>global</code> declaration fails.</p> <p>If you remove the <code>global</code>, it still fails, because you can't assign to the captured variable name. To work around that, you can use an object as the variable captured by your closures and than just change properties of that object:</p> <pre><code>class Memo(object): pass def memoize(fn): def defaultget(key): return (False,) memo = Memo() memo.get = defaultget def vset(key, value): oldget = memo.get def newget(ky): if key==ky: return (True, value) return oldget(ky) memo.get = newget def mfun(*args): cache = memo.get(args) if cache[0]: return cache[1] val = apply(fn, args) vset(args, val) return val return mfun </code></pre> <p>This way you don't need to assign to the captured variable names but still get what you wanted.</p>
1
2009-02-03T00:58:45Z
[ "python", "closures", "lexical-scope" ]
Closures in Python
505,559
<p>I've been trying to learn Python, and while I'm enthusiastic about using closures in Python, I've been having trouble getting some code to work properly:</p> <pre><code>def memoize(fn): def get(key): return (False,) def vset(key, value): global get oldget = get def newget(ky): if key==ky: return (True, value) return oldget(ky) get = newget def mfun(*args): cache = get(args) if (cache[0]): return cache[1] val = apply(fn, args) vset(args, val) return val return mfun def fib(x): if x&lt;2: return x return fib(x-1)+fib(x-2) def fibm(x): if x&lt;2: return x return fibm(x-1)+fibm(x-2) fibm = memoize(fibm) </code></pre> <p>Basically, what this is supposed to do is use closures to maintain the memoized state of the function. I realize there are probably many faster, easier to read, and in general more 'Pythonic' ways to implement this; however, my goal is to understand exactly how closures work in Python, and how they differ from Lisp, so I'm not interested in alternative solutions, just why my code doesn't work and what I can do (if anything) to fix it.</p> <p>The problem I'm running into is when I try to use <code>fibm</code> - Python insists that <code>get</code> isn't defined:</p> <pre><code>Python 2.6.1 (r261:67515, Feb 1 2009, 11:39:55) [GCC 4.0.1 (Apple Inc. build 5488)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import memoize &gt;&gt;&gt; memoize.fibm(35) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "memoize.py", line 14, in mfun cache = get(args) NameError: global name 'get' is not defined &gt;&gt;&gt; </code></pre> <p>Seeing as I'm new to Python, I don't know if I've done something wrong, or if this is just a limitation of the language. I'm hoping it's the former. :-)</p>
6
2009-02-03T00:13:06Z
1,380,012
<p>I think the best way would be:</p> <pre><code>class Memoized(object): def __init__(self,func): self.cache = {} self.func = func def __call__(self,*args): if args in self.cache: return cache[args] else: self.cache[args] = self.func(*args) return self.cache[args] </code></pre>
0
2009-09-04T15:39:47Z
[ "python", "closures", "lexical-scope" ]
How to chain views in Django?
505,703
<p>I'm implementing <a href="http://www.b-list.org/about/" rel="nofollow">James Bennett</a>'s excellent <a href="http://code.google.com/p/django-contact-form/" rel="nofollow">django-contact-form</a> but have hit a snag. My contact page not only contains the form, but also additional flat page information. </p> <p>Without rewriting the existing view the contact form uses, I'd like to be able to wrap, or chain, the views. This way I could inject some additional information via the context so that both the form and the flat page data could be rendered within the same template.</p> <p>I've heard it mentioned that this is possible, but I can't seem to figure out how to make it work. I've created my own wrapper view, called the contact form view, and attempted to inspect the HttpResponse object for an attribute I can append to, but I can't seem to figure out which, if any, it is.</p> <p><strong>EDIT:</strong> James commented that the latest code can new be found <a href="http://bitbucket.org/ubernostrum/django-contact-form/overview/" rel="nofollow">here</a> at BitBucket.</p>
4
2009-02-03T01:13:26Z
505,712
<p>There's a context processor that may do what you want.</p> <p><a href="http://docs.djangoproject.com/en/dev/ref/templates/api/" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/templates/api/</a></p> <p>You can probably add your various pieces of "flat page information" to the context.</p>
2
2009-02-03T01:18:19Z
[ "python", "django", "extension-methods", "django-views", "wrapping" ]
How to chain views in Django?
505,703
<p>I'm implementing <a href="http://www.b-list.org/about/" rel="nofollow">James Bennett</a>'s excellent <a href="http://code.google.com/p/django-contact-form/" rel="nofollow">django-contact-form</a> but have hit a snag. My contact page not only contains the form, but also additional flat page information. </p> <p>Without rewriting the existing view the contact form uses, I'd like to be able to wrap, or chain, the views. This way I could inject some additional information via the context so that both the form and the flat page data could be rendered within the same template.</p> <p>I've heard it mentioned that this is possible, but I can't seem to figure out how to make it work. I've created my own wrapper view, called the contact form view, and attempted to inspect the HttpResponse object for an attribute I can append to, but I can't seem to figure out which, if any, it is.</p> <p><strong>EDIT:</strong> James commented that the latest code can new be found <a href="http://bitbucket.org/ubernostrum/django-contact-form/overview/" rel="nofollow">here</a> at BitBucket.</p>
4
2009-02-03T01:13:26Z
505,930
<p>Context processors are what you're thinking of. And render_to_response is irrelevant. The required piece of information is if the view uses RequestContext or not, as that is what activates context processors.</p> <p>Other than those, there is no way to "chain" views to add to context - you can wrap one view in another and alter the data going into it, but you <em>cannot</em> add to context that way.</p>
1
2009-02-03T03:30:11Z
[ "python", "django", "extension-methods", "django-views", "wrapping" ]
How to chain views in Django?
505,703
<p>I'm implementing <a href="http://www.b-list.org/about/" rel="nofollow">James Bennett</a>'s excellent <a href="http://code.google.com/p/django-contact-form/" rel="nofollow">django-contact-form</a> but have hit a snag. My contact page not only contains the form, but also additional flat page information. </p> <p>Without rewriting the existing view the contact form uses, I'd like to be able to wrap, or chain, the views. This way I could inject some additional information via the context so that both the form and the flat page data could be rendered within the same template.</p> <p>I've heard it mentioned that this is possible, but I can't seem to figure out how to make it work. I've created my own wrapper view, called the contact form view, and attempted to inspect the HttpResponse object for an attribute I can append to, but I can't seem to figure out which, if any, it is.</p> <p><strong>EDIT:</strong> James commented that the latest code can new be found <a href="http://bitbucket.org/ubernostrum/django-contact-form/overview/" rel="nofollow">here</a> at BitBucket.</p>
4
2009-02-03T01:13:26Z
510,371
<ol> <li>Write a wrapper which uses the URL to look up the appropriate flat page object.</li> <li>From your wrapper, call (and return the response from) the contact form view, passing the flat page in the <code>extra_context</code> argument (which is there for, among other things, precisely this sort of use case).</li> <li>There is no third step.</li> </ol>
2
2009-02-04T07:14:23Z
[ "python", "django", "extension-methods", "django-views", "wrapping" ]
Extracting data from MS Word
505,925
<p>I am looking for a way to extract / scrape data from Word files into a database. Our corporate procedures have Minutes of Meetings with clients documented in MS Word files, mostly due to history and inertia.</p> <p>I want to be able to pull the action items from these meeting minutes into a database so that we can access them from a web-interface, turn them into tasks and update them as they are completed.</p> <p>Which is the best way to do this:</p> <ol> <li>VBA macro from inside Word to create CSV and then upload to the DB?</li> <li>VBA macro in Word with connection to DB (how does one connect to MySQL from VBA?)</li> <li>Python script via win32com then upload to DB?</li> </ol> <p>The last one is attractive to me as the web-interface is being built with Django, but I've never used win32com or tried scripting Word from python.</p> <p><strong>EDIT:</strong> I've started extracting the text with VBA because it makes it a little easier to deal with the Word Object Model. I am having a problem though - all the text is in Tables, and when I pull the strings out of the CELLS I want, I get a strange little box character at the end of each string. My code looks like:</p> <pre><code>sFile = "D:\temp\output.txt" fnum = FreeFile Open sFile For Output As #fnum num_rows = Application.ActiveDocument.Tables(2).Rows.Count For n = 1 To num_rows Descr = Application.ActiveDocument.Tables(2).Cell(n, 2).Range.Text Assign = Application.ActiveDocument.Tables(2).Cell(n, 3).Range.Text Target = Application.ActiveDocument.Tables(2).Cell(n, 4).Range.Text If Target = "" Then ExportText = "" Else ExportText = Descr &amp; Chr(44) &amp; Assign &amp; Chr(44) &amp; _ Target &amp; Chr(13) &amp; Chr(10) Print #fnum, ExportText End If Next n Close #fnum </code></pre> <p>What's up with the little control character box? Is some kind of character code coming across from Word?</p>
5
2009-02-03T03:27:53Z
505,948
<p>I'd say look at the related questions on the right --> The <a href="http://stackoverflow.com/questions/125222/extracting-text-from-ms-word-files-in-python">top one</a> seems to have some good ideas for going the python route.</p>
0
2009-02-03T03:36:56Z
[ "python", "vba", "ms-word", "word-vba", "pywin32" ]
Extracting data from MS Word
505,925
<p>I am looking for a way to extract / scrape data from Word files into a database. Our corporate procedures have Minutes of Meetings with clients documented in MS Word files, mostly due to history and inertia.</p> <p>I want to be able to pull the action items from these meeting minutes into a database so that we can access them from a web-interface, turn them into tasks and update them as they are completed.</p> <p>Which is the best way to do this:</p> <ol> <li>VBA macro from inside Word to create CSV and then upload to the DB?</li> <li>VBA macro in Word with connection to DB (how does one connect to MySQL from VBA?)</li> <li>Python script via win32com then upload to DB?</li> </ol> <p>The last one is attractive to me as the web-interface is being built with Django, but I've never used win32com or tried scripting Word from python.</p> <p><strong>EDIT:</strong> I've started extracting the text with VBA because it makes it a little easier to deal with the Word Object Model. I am having a problem though - all the text is in Tables, and when I pull the strings out of the CELLS I want, I get a strange little box character at the end of each string. My code looks like:</p> <pre><code>sFile = "D:\temp\output.txt" fnum = FreeFile Open sFile For Output As #fnum num_rows = Application.ActiveDocument.Tables(2).Rows.Count For n = 1 To num_rows Descr = Application.ActiveDocument.Tables(2).Cell(n, 2).Range.Text Assign = Application.ActiveDocument.Tables(2).Cell(n, 3).Range.Text Target = Application.ActiveDocument.Tables(2).Cell(n, 4).Range.Text If Target = "" Then ExportText = "" Else ExportText = Descr &amp; Chr(44) &amp; Assign &amp; Chr(44) &amp; _ Target &amp; Chr(13) &amp; Chr(10) Print #fnum, ExportText End If Next n Close #fnum </code></pre> <p>What's up with the little control character box? Is some kind of character code coming across from Word?</p>
5
2009-02-03T03:27:53Z
505,969
<p>Well, I've never scripted Word, but it's pretty easy to do simple stuff with win32com. Something like:</p> <pre><code>from win32com.client import Dispatch word = Dispatch('Word.Application') doc = word.Open('d:\\stuff\\myfile.doc') doc.SaveAs(FileName='d:\\stuff\\text\\myfile.txt', FileFormat=?) # not sure what to use for ? </code></pre> <p>This is untested, but I think something like that will just open the file and save it as plain text (provided you can find the right fileformat) – you could then read the text into python and manipulate it from there. There is probably a way to grab the contents of the file directly, too, but I don't know it off hand; documentation can be hard to find, but if you've got VBA docs or experience, you should be able to carry them across.</p> <p>Have a look at this post from a while ago: <a href="http://mail.python.org/pipermail/python-list/2002-October/168785.html" rel="nofollow">http://mail.python.org/pipermail/python-list/2002-October/168785.html</a> Scroll down to COMTools.py; there's some good examples there.</p> <p>You can also run makepy.py (part of the pythonwin distribution) to generate python "signatures" for the COM functions available, and then look through it as a kind of documentation.</p>
1
2009-02-03T03:58:49Z
[ "python", "vba", "ms-word", "word-vba", "pywin32" ]
Extracting data from MS Word
505,925
<p>I am looking for a way to extract / scrape data from Word files into a database. Our corporate procedures have Minutes of Meetings with clients documented in MS Word files, mostly due to history and inertia.</p> <p>I want to be able to pull the action items from these meeting minutes into a database so that we can access them from a web-interface, turn them into tasks and update them as they are completed.</p> <p>Which is the best way to do this:</p> <ol> <li>VBA macro from inside Word to create CSV and then upload to the DB?</li> <li>VBA macro in Word with connection to DB (how does one connect to MySQL from VBA?)</li> <li>Python script via win32com then upload to DB?</li> </ol> <p>The last one is attractive to me as the web-interface is being built with Django, but I've never used win32com or tried scripting Word from python.</p> <p><strong>EDIT:</strong> I've started extracting the text with VBA because it makes it a little easier to deal with the Word Object Model. I am having a problem though - all the text is in Tables, and when I pull the strings out of the CELLS I want, I get a strange little box character at the end of each string. My code looks like:</p> <pre><code>sFile = "D:\temp\output.txt" fnum = FreeFile Open sFile For Output As #fnum num_rows = Application.ActiveDocument.Tables(2).Rows.Count For n = 1 To num_rows Descr = Application.ActiveDocument.Tables(2).Cell(n, 2).Range.Text Assign = Application.ActiveDocument.Tables(2).Cell(n, 3).Range.Text Target = Application.ActiveDocument.Tables(2).Cell(n, 4).Range.Text If Target = "" Then ExportText = "" Else ExportText = Descr &amp; Chr(44) &amp; Assign &amp; Chr(44) &amp; _ Target &amp; Chr(13) &amp; Chr(10) Print #fnum, ExportText End If Next n Close #fnum </code></pre> <p>What's up with the little control character box? Is some kind of character code coming across from Word?</p>
5
2009-02-03T03:27:53Z
506,002
<p>how about saving the file as xml. then using python or something else and pull the data out of word and into the database. </p>
0
2009-02-03T04:23:52Z
[ "python", "vba", "ms-word", "word-vba", "pywin32" ]