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
automatic keystroke to stay logged in
969,849
<p>I have a web based email application that logs me out after 10 minutes of inactivity ("For security reasons"). I would like to write something that either a) imitates a keystroke b) pings an ip or c) some other option every 9 minutes so that I stay logged in. I am on my personal laptop in an office with a door, so I'm not too worried about needing to be logged out.</p> <p>I have written a small python script to ping an ip and then sleep for 9 minutes, and this works dandy, but I would like something that I could include in my startup applications. I don't know if this means I need to compile something into an exe, or can I add this python script to startup apps?</p>
1
2009-06-09T12:40:42Z
969,897
<p>You can also use the <strong>Scheduled Tasks</strong> feature (on the Control Panel) to run it at startup, or you can change your script to ping the IP and exit, and scheduled it to run every 9 minutes. You have nice settings there, for example, you can stop running it at night, so you'll still log out.<br /> You might still need the bat file though, I don't know about Python. </p> <p>In fact, if you need just a simple ping you can scheduled ping.exe.</p>
3
2009-06-09T12:53:25Z
[ "python", "authentication" ]
automatic keystroke to stay logged in
969,849
<p>I have a web based email application that logs me out after 10 minutes of inactivity ("For security reasons"). I would like to write something that either a) imitates a keystroke b) pings an ip or c) some other option every 9 minutes so that I stay logged in. I am on my personal laptop in an office with a door, so I'm not too worried about needing to be logged out.</p> <p>I have written a small python script to ping an ip and then sleep for 9 minutes, and this works dandy, but I would like something that I could include in my startup applications. I don't know if this means I need to compile something into an exe, or can I add this python script to startup apps?</p>
1
2009-06-09T12:40:42Z
971,984
<p>Pinging an IP will not likely keep your session from timing out. You will likely need to do an HTTP GET and include the session cookie supplied by the server to your browser when you login. Your script <strong>may</strong> be able to read the cookie from your browser's cookies folder after you have logged in via the browser.</p> <p>Also, the web page may have javascript that calls the logout page when it times out. You <strong>may</strong> be able to use codemonkey to disable this behavior.</p>
2
2009-06-09T19:18:29Z
[ "python", "authentication" ]
automatic keystroke to stay logged in
969,849
<p>I have a web based email application that logs me out after 10 minutes of inactivity ("For security reasons"). I would like to write something that either a) imitates a keystroke b) pings an ip or c) some other option every 9 minutes so that I stay logged in. I am on my personal laptop in an office with a door, so I'm not too worried about needing to be logged out.</p> <p>I have written a small python script to ping an ip and then sleep for 9 minutes, and this works dandy, but I would like something that I could include in my startup applications. I don't know if this means I need to compile something into an exe, or can I add this python script to startup apps?</p>
1
2009-06-09T12:40:42Z
983,562
<p>i use the reloadEvery plugin for firefox to keep me logged into websites (forums, phpmyadmin, etc). simple yet effective.</p>
0
2009-06-11T20:46:43Z
[ "python", "authentication" ]
automatic keystroke to stay logged in
969,849
<p>I have a web based email application that logs me out after 10 minutes of inactivity ("For security reasons"). I would like to write something that either a) imitates a keystroke b) pings an ip or c) some other option every 9 minutes so that I stay logged in. I am on my personal laptop in an office with a door, so I'm not too worried about needing to be logged out.</p> <p>I have written a small python script to ping an ip and then sleep for 9 minutes, and this works dandy, but I would like something that I could include in my startup applications. I don't know if this means I need to compile something into an exe, or can I add this python script to startup apps?</p>
1
2009-06-09T12:40:42Z
1,786,506
<p>I've been using this for a while, works great! <a href="http://stackoverflow.com/questions/969849/automatic-keystroke-to-stay-logged-in/971984#971984">http://stackoverflow.com/questions/969849/automatic-keystroke-to-stay-logged-in/971984#971984</a></p>
0
2009-11-23T22:28:44Z
[ "python", "authentication" ]
users module errors in Google App Engine
969,877
<p>I want to use user service of my domain in google App, but... Is it possible to solve this problem by my side?</p> <pre> Traceback (most recent call last): File "/base/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 501, in __call__ handler.get(*groups) File "/base/data/home/apps/myapp2009/1.334081739634584397/helloworld.py", line 13, in get self.redirect(users.create_login_url(self.request.uri)) File "/base/python_lib/versions/1/google/appengine/api/users.py", line 176, in create_login_url raise NotAllowedError NotAllowedError </pre>
1
2009-06-09T12:48:23Z
14,879,943
<p>Actually not my answer, but from the OP, that didn't act on S. Lott's comment:</p> <blockquote> <p>It works now! but I didnt change anything actually, seems like Google need time to update its database for app engine. like 20 mins.</p> </blockquote>
1
2013-02-14T16:52:04Z
[ "python", "google-app-engine", "user" ]
Subclassing list
970,425
<p>I want create a DataSet class which is basically a list of samples. But I need to override each insertion operation to the DataSet.</p> <p>Is there any simple way to do this without writing my own append, extend, iadd etc. ?</p> <p><strong>UPDATE:</strong> I want to add a backpointer to each sample, holding index of the sample in the DataSet. This is needed to the processing algorithm I use. I have a solution, but it seems unelegant - a renumber() function -- it ensures that the backpointers are valid.</p>
4
2009-06-09T14:35:47Z
970,439
<p>I don't know of a way of doing what you're asking -- overriding mutators without overriding them. With a class decorator, however, you can "automate" the overriding versions (assuming each can be achieved by wrapping the corresponding method in the base class), so it's not too bad...</p> <p>Suppose for example that what you want to do is add a "modified" flag, true if the data may have been changed since the last call to <code>.save</code> (a method of yours which persist the data and sets <code>self.modified</code> to False).</p> <p>Then...:</p> <pre><code>def wrapMethod(cls, n): f = getattr(cls, n) def wrap(self, *a): self.dirty = True return f(self, *a) return wrap def wrapListMutators(cls): for n in '''__setitem__ __delitem__ __iadd__ __imul__ append extend insert pop remove reverse sort'''.split(): f = wrapMethod(cls, n) setattr(cls, n, f) return cls @wrapListMutators class DataSet(list): dirty = False def save(self): self.dirty = False </code></pre> <p>This syntax requires Python 2.6 or better, but, in earlier Python versions (ones which only support decorators on <code>def</code> statements, not on <code>class</code> statements; or even very old ones that don't support decorators at all), you just need to change the very last part (the <code>class</code> statement), to:</p> <pre><code>class DataSet(list): dirty = False def save(self): self.dirty = False DataSet = wrapListMutators(DataSet) </code></pre> <p>IOW, the neat decorator syntax is just a small amount of syntax sugar on top of a normal function call which takes the class as the argument and reassigns it.</p> <p>Edit: now that you have edited your question to clarify your exact requirements -- maintain on each item a field <code>bp</code> such that, for all <code>i</code>, <code>theset[i].bp == i</code> -- it's easier to weigh the pro and con of various approaches.</p> <p>You could adapt the approach I sketched, but instead of <code>self.dirty</code> assignment before the call to the wrapped method, have a <code>self.renumber()</code> call after it, i.e.:</p> <pre><code>def wrapMethod(cls, n): f = getattr(cls, n) def wrap(self, *a): temp = f(self, *a) self.renumber() return temp return wrap </code></pre> <p>this meets your stated requirements, but in many cases it will do far more work than necessary: for example, when you <code>append</code> an item, this needlessly "renumbers" all existing ones (to the same values they already had). But how could any fully automated approach "know" which items, if any, it must recompute the <code>.bp</code> of, without <code>O(N)</code> effort? At least it must look at each and every one of them (since you don't want to separately code, e.g., <code>append</code> vs <code>insert</code> &amp;c), and that's already <code>O(N)</code>.</p> <p>So this will be acceptable only if it's OK for every single change to the list to be <code>O(N)</code> (basically only if the list always stays small and/or doesn't change often).</p> <p>A more fruitful idea might be to not maintain <code>.bp</code> values all the time, but only "just in time" when needed. Make <code>bp</code> a (read-only) property, calling a method which checks if the container is "dirty" (where the "dirty" flag in the container is maintained using the automated code I've already given) and only then renumbers the container (and sets its "dirty" attribute to <code>False</code>).</p> <p>This will work well when the list typically is subject to a burst of changes and only then do you need to access the items' <code>bp</code> for a while, then another bunch of changes, etc. Such bursty alternation between changing and reading is not rare in real-world containers, but only you can know whether it applies in your specific case!</p> <p>To get performance beyond this I think you need to do <em>some</em> manual coding on top of this general approach to take advantage of frequent special cases. For example, <code>append</code> may be called very often, and the amount of work to do in a special-cases <code>append</code> is really small, so it may well be worth your while to write those two or three lines of code (not setting the dirty bit for that case).</p> <p>One caveat: no approach will work (indeed your requirement becomes self contradictory) if any item is present twice in the list -- which of course is perfectly possible unless you take precautions to avoid it (you could easily diagnose it in <code>renumber</code> -- by keeping a set of elements already seen and raising an exception on any duplication -- if that's not too late for you; it's harder to diagnose "on the fly", i.e. at the time of a mutation that causes a duplicate, if that's what you require). Maybe you can relax your requirement so that, if an item is present twice, that's OK and the <code>bp</code> can just indicate one of the indices; or make <code>bp</code> into a <em>set</em> of indices where the element is present (that would also offer a smooth approach to the case of getting <code>bp</code> from an element that's <strong>not</strong> in the list). Etc, etc; I recommend you consider (and <strong>document</strong>!) all of these corner cases in depth -- correctness before performance!</p>
5
2009-06-09T14:38:51Z
[ "python" ]
What is the most state-of-the-art, pure python, XML parser available?
970,531
<p>Considering that I want to write python code that would run on Google App Engine and also inside jython, C-extensions are not an option. Amara was a nice library, but due to its C-extensions, I can't use it for either of these platforms.</p>
5
2009-06-09T14:53:34Z
970,537
<p><a href="http://effbot.org/zone/element-index.htm" rel="nofollow">ElementTree</a> is very nice. It's also part of <a href="http://docs.python.org/library/xml.etree.elementtree.html" rel="nofollow">2.5</a>.</p>
7
2009-06-09T14:54:32Z
[ "python", "xml", "google-app-engine", "jython" ]
What is the most state-of-the-art, pure python, XML parser available?
970,531
<p>Considering that I want to write python code that would run on Google App Engine and also inside jython, C-extensions are not an option. Amara was a nice library, but due to its C-extensions, I can't use it for either of these platforms.</p>
5
2009-06-09T14:53:34Z
970,548
<p><a href="http://docs.python.org/library/xml.sax.html" rel="nofollow">xml.sax</a> is a builtin SAX parser</p>
1
2009-06-09T14:55:24Z
[ "python", "xml", "google-app-engine", "jython" ]
What is the most state-of-the-art, pure python, XML parser available?
970,531
<p>Considering that I want to write python code that would run on Google App Engine and also inside jython, C-extensions are not an option. Amara was a nice library, but due to its C-extensions, I can't use it for either of these platforms.</p>
5
2009-06-09T14:53:34Z
970,554
<p>There's also <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a> (which may be geared more toward HTML, but it also does XML).</p>
4
2009-06-09T14:56:03Z
[ "python", "xml", "google-app-engine", "jython" ]
What is the most state-of-the-art, pure python, XML parser available?
970,531
<p>Considering that I want to write python code that would run on Google App Engine and also inside jython, C-extensions are not an option. Amara was a nice library, but due to its C-extensions, I can't use it for either of these platforms.</p>
5
2009-06-09T14:53:34Z
970,621
<p>I would normally recommend lxml, but since that uses a C-library (libxml) the alternative would have to be, as Aaron has already suggested, ElementTree (as far as I know there is both a pure python and a c implementation of it available). <a href="http://code.google.com/p/googleappengine/issues/detail?id=18" rel="nofollow">Found this via google search</a></p> <p>Good luck!</p>
1
2009-06-09T15:05:00Z
[ "python", "xml", "google-app-engine", "jython" ]
How to strip color codes used by mIRC users?
970,545
<p>I'm writing a IRC bot in Python using irclib and I'm trying to log the messages on certain channels.<br /> The issue is that some mIRC users and some Bots write using <a href="http://www.mirc.com/help/color.txt" rel="nofollow">color codes</a>.<br /> Any idea on how i could strip those parts and leave only the clear ascii text message?</p>
6
2009-06-09T14:55:08Z
970,598
<pre><code>p = re.compile("\x03\d+(?:,\d+)?") p.sub('', text) </code></pre>
1
2009-06-09T15:02:06Z
[ "python", "irc" ]
How to strip color codes used by mIRC users?
970,545
<p>I'm writing a IRC bot in Python using irclib and I'm trying to log the messages on certain channels.<br /> The issue is that some mIRC users and some Bots write using <a href="http://www.mirc.com/help/color.txt" rel="nofollow">color codes</a>.<br /> Any idea on how i could strip those parts and leave only the clear ascii text message?</p>
6
2009-06-09T14:55:08Z
970,723
<p>Regular expressions are your cleanest bet in my opinion. If you haven't used them before, <a href="http://www.diveintopython.org/regular%5Fexpressions/index.html">this</a> is a good resource. For the full details on Python's regex library, go <a href="http://docs.python.org/library/re.html">here</a>.</p> <pre><code>import re regex = re.compile("\x03(?:\d{1,2}(?:,\d{1,2})?)?", re.UNICODE) </code></pre> <p>The regex searches for ^C (which is \x03 in <a href="http://en.wikipedia.org/wiki/ASCII">ASCII</a>, you can confirm by doing chr(3) on the command line), and then optionally looks for one or two [0-9] characters, then optionally followed by a comma and then another one or two [0-9] characters.</p> <p><strong>(?: ... )</strong> says to forget about storing what was found in the parenthesis (as we don't need to backreference it), <strong>?</strong> means to match 0 or 1 and <strong>{n,m}</strong> means to match n to m of the previous grouping. Finally, <strong>\d</strong> means to match [0-9].</p> <p>The rest can be decoded using the links I refer to above.</p> <pre><code>&gt;&gt;&gt; regex.sub("", "blabla \x035,12to be colored text and background\x03 blabla") 'blabla to be colored text and background blabla' </code></pre> <p><em>chaos</em>' solution is similar, but may end up eating more than a max of two numbers and will also not remove any loose ^C characters that may be hanging about (such as the one that closes the colour command)</p>
11
2009-06-09T15:17:27Z
[ "python", "irc" ]
How to strip color codes used by mIRC users?
970,545
<p>I'm writing a IRC bot in Python using irclib and I'm trying to log the messages on certain channels.<br /> The issue is that some mIRC users and some Bots write using <a href="http://www.mirc.com/help/color.txt" rel="nofollow">color codes</a>.<br /> Any idea on how i could strip those parts and leave only the clear ascii text message?</p>
6
2009-06-09T14:55:08Z
1,591,971
<p>I even had to add '<code>\x0f</code>', whatever use it has</p> <pre><code>regex = re.compile("\x0f|\x1f|\x02|\x03(?:\d{1,2}(?:,\d{1,2})?)?", re.UNICODE) regex.sub('', msg) </code></pre>
0
2009-10-20T01:12:18Z
[ "python", "irc" ]
How to strip color codes used by mIRC users?
970,545
<p>I'm writing a IRC bot in Python using irclib and I'm trying to log the messages on certain channels.<br /> The issue is that some mIRC users and some Bots write using <a href="http://www.mirc.com/help/color.txt" rel="nofollow">color codes</a>.<br /> Any idea on how i could strip those parts and leave only the clear ascii text message?</p>
6
2009-06-09T14:55:08Z
2,451,544
<p>As I found this question useful, I figured I'd contribute.</p> <p>I added a couple things to the regex</p> <pre><code>regex = re.compile("\x1f|\x02|\x03|\x16|\x0f(?:\d{1,2}(?:,\d{1,2})?)?", re.UNICODE) </code></pre> <p><code>\x16</code> removed the "reverse" character. <code>\x0f</code> gets rid of another bold character.</p>
1
2010-03-16T01:12:10Z
[ "python", "irc" ]
How to strip color codes used by mIRC users?
970,545
<p>I'm writing a IRC bot in Python using irclib and I'm trying to log the messages on certain channels.<br /> The issue is that some mIRC users and some Bots write using <a href="http://www.mirc.com/help/color.txt" rel="nofollow">color codes</a>.<br /> Any idea on how i could strip those parts and leave only the clear ascii text message?</p>
6
2009-06-09T14:55:08Z
3,504,063
<p>The second-rated and following suggestions are defective, as they look for digits after whatever character, but not after the color code character.</p> <p>I have improved and combined all posts, with the following consequences:</p> <ul> <li>we <em>do</em> remove the reverse character</li> <li>remove color codes <em>without</em> leaving digits in the text.</li> </ul> <p>Solution:</p> <p><code> regex = re.compile("\x1f|\x02|\x12|\x0f|\x16|\x03(?:\d{1,2}(?:,\d{1,2})?)?", re.UNICODE)</code></p>
7
2010-08-17T15:21:24Z
[ "python", "irc" ]
How to strip color codes used by mIRC users?
970,545
<p>I'm writing a IRC bot in Python using irclib and I'm trying to log the messages on certain channels.<br /> The issue is that some mIRC users and some Bots write using <a href="http://www.mirc.com/help/color.txt" rel="nofollow">color codes</a>.<br /> Any idea on how i could strip those parts and leave only the clear ascii text message?</p>
6
2009-06-09T14:55:08Z
29,279,757
<p>AutoDl-irssi had a very good one written in perl, here it is in python:</p> <p><code>def stripMircColorCodes(line) : line = re.sub("\x03\d\d?,\d\d?","",line) line = re.sub("\x03\d\d?","",line) line = re.sub("[\x01-\x1F]","",line) return line</code></p>
1
2015-03-26T13:30:43Z
[ "python", "irc" ]
How to strip color codes used by mIRC users?
970,545
<p>I'm writing a IRC bot in Python using irclib and I'm trying to log the messages on certain channels.<br /> The issue is that some mIRC users and some Bots write using <a href="http://www.mirc.com/help/color.txt" rel="nofollow">color codes</a>.<br /> Any idea on how i could strip those parts and leave only the clear ascii text message?</p>
6
2009-06-09T14:55:08Z
29,645,095
<p>I know I posted wanting a regex solution because it could be cleaner, I have created a non regex solution that works perfect. </p> <pre><code>def colourstrip(data): find = data.find('\x03') while find &gt; -1: done = False data = data[0:find] + data[find+1:] if len(data) &lt;= find+1: done = True try: assert int(data[find]) data = data[0:find] + data[find+1:] except: done = True try: assert not done assert int(data[find]) data = data[0:find] + data[find+1:] except: if not done and (data[find] != ','): done = True if (len(data) &gt; find+1) and (data[find] == ','): try: assert not done assert int(data[find+1]) data = data[0:find] + data[find+1:] data = data[0:find] + data[find+1:] except: done = True try: assert not done assert int(data[find]) data = data[0:find] + data[find+1:] except: pass find = data.find('\x03') data = data.replace('\x1d','') data = data.replace('\x1f','') data = data.replace('\x16','') data = data.replace('\x0f','') return data datastring = '\x0312,4This is coolour \x032,4This is too\x03' print(colourstrip(datastring)) </code></pre> <p>Thank you for all the help everyone.</p>
0
2015-04-15T08:19:55Z
[ "python", "irc" ]
Is a file on the same filesystem as another file in python?
970,742
<p>Is there a simple way of finding out if a file is on the same filesystem as another file?</p> <p>The following command:</p> <pre><code>import shutil shutil.move('filepatha', 'filepathb') </code></pre> <p>will try and rename the file (if it's on the same filesystem), otherwise it will copy it, then unlink.</p> <p>I want to find out before calling this command whether it will preform the quick or slow option, how do I do this?</p>
4
2009-06-09T15:20:23Z
970,830
<p>Use <code>os.stat</code> (on a filename) or <code>os.fstat</code> (on a file descriptor). The <code>st_dev</code> of the result will be the device number. If they are on the same file system, it will be the same in both.</p> <pre><code>import os def same_fs(file1, file2): dev1 = os.stat(file1).st_dev dev2 = os.stat(file2).st_dev return dev1 == dev2 </code></pre>
10
2009-06-09T15:33:38Z
[ "python", "filesystems" ]
Threads in Java and Python
970,909
<p>i have few questions about threads in Python and Java...</p> <ol> <li>Is it possible to give priorities to Python threads, as it is in Java?</li> <li>How can I kill, stop, suspend and interrupt thread in Python?</li> <li>Thread groups - what are they really for? Does Python support them too?</li> <li>Synchronization - in Java we use simply keyword synchorinized for a method, object...What about Python? </li> </ol> <p>Tnx!</p>
5
2009-06-09T15:49:05Z
970,960
<p>Assuming we're talking about the classic (CPython) implementation:</p> <ol> <li>no, no priorities in Python's threads</li> <li>you can't do any of these things to a thread in Python</li> <li>no thread groups in Python</li> <li>you can use many approaches, such as locks, but the recommended approach is generally to use the Queue module from the standard library (and limit your threads' interactions to what Queue lets you program)</li> </ol> <p>In other words, Python threads are really much less rich than Java's -- not to mention that only one thread per process can in fact run Python code (others may be running C code or waiting).</p> <p>For anything fancy, i.e. anything beyond Python's limited threading capabilities, it's recommended you use the <a href="http://docs.python.org/library/multiprocessing.html"><code>multiprocessing</code></a> module from the standard library -- or switch to implementations of Python that let you use richer threading approaches, such as Jython for the JVM or IronPython for .NET.</p>
12
2009-06-09T15:55:02Z
[ "java", "python", "multithreading" ]
Threads in Java and Python
970,909
<p>i have few questions about threads in Python and Java...</p> <ol> <li>Is it possible to give priorities to Python threads, as it is in Java?</li> <li>How can I kill, stop, suspend and interrupt thread in Python?</li> <li>Thread groups - what are they really for? Does Python support them too?</li> <li>Synchronization - in Java we use simply keyword synchorinized for a method, object...What about Python? </li> </ol> <p>Tnx!</p>
5
2009-06-09T15:49:05Z
971,025
<p>Just a sidestep about point 1 here, because Java Thread priorities might not work as one would expect.</p> <p>From the SCJP guide:</p> <blockquote> <p>Because thread-scheduling priority behaviour is not guaranteed, use thread priorities as a way to improve the efficiency of your program, but just be sure your program doesn't depend on that behaviour for correctness.</p> </blockquote>
0
2009-06-09T16:06:03Z
[ "java", "python", "multithreading" ]
Threads in Java and Python
970,909
<p>i have few questions about threads in Python and Java...</p> <ol> <li>Is it possible to give priorities to Python threads, as it is in Java?</li> <li>How can I kill, stop, suspend and interrupt thread in Python?</li> <li>Thread groups - what are they really for? Does Python support them too?</li> <li>Synchronization - in Java we use simply keyword synchorinized for a method, object...What about Python? </li> </ol> <p>Tnx!</p>
5
2009-06-09T15:49:05Z
971,134
<p>Regular java thread priorities can't be counted on. You may find a lower priority thread running when a higher priority thread is ready and waiting. </p> <p>There is something called "realtime java" (see <a href="http://www.rtsj.org" rel="nofollow">http://www.rtsj.org</a>) which does enforce thread priority, at least for the RealtimeThread class. Regular java.lang.Thread may still not enforce true priority ordering.</p>
1
2009-06-09T16:27:29Z
[ "java", "python", "multithreading" ]
Threads in Java and Python
970,909
<p>i have few questions about threads in Python and Java...</p> <ol> <li>Is it possible to give priorities to Python threads, as it is in Java?</li> <li>How can I kill, stop, suspend and interrupt thread in Python?</li> <li>Thread groups - what are they really for? Does Python support them too?</li> <li>Synchronization - in Java we use simply keyword synchorinized for a method, object...What about Python? </li> </ol> <p>Tnx!</p>
5
2009-06-09T15:49:05Z
972,935
<p>Unfortunately the standard Python package has something called the GIL, or global interpreter lock. This means only one of your threads will ever be running at a time. That being said, simple multithreaded applications are possible and pretty easy to write. The threading module contains basic synchronization primitives like mutexes, sempahores, etc. </p> <p>There is also an awesome with statement that automates most aspects of lock usages. For an example:</p> <pre><code>import threading myLock = threading.Lock() </code></pre> <p>Then to use the lock:</p> <pre><code>with myLock: #lock has now been acquired print "I have the lock and can now to fun stuff" print "The lock has been released" </code></pre>
0
2009-06-09T23:02:07Z
[ "java", "python", "multithreading" ]
Threads in Java and Python
970,909
<p>i have few questions about threads in Python and Java...</p> <ol> <li>Is it possible to give priorities to Python threads, as it is in Java?</li> <li>How can I kill, stop, suspend and interrupt thread in Python?</li> <li>Thread groups - what are they really for? Does Python support them too?</li> <li>Synchronization - in Java we use simply keyword synchorinized for a method, object...What about Python? </li> </ol> <p>Tnx!</p>
5
2009-06-09T15:49:05Z
977,446
<p>I felt the need to debunk the common myths perpetuated here:</p> <blockquote> <p>Is it possible to give priorities to Python threads, as it is in Java?</p> </blockquote> <p>Not in the OS sense. But you can use cooperative multitasking and your own custom scheduler to ensure that certain threads use more time. You can also set the timeslices between a thread with this: </p> <p><a href="http://docs.python.org/library/sys.html#sys.setcheckinterval" rel="nofollow">http://docs.python.org/library/sys.html#sys.setcheckinterval</a></p> <blockquote> <p>How can I kill, stop, suspend and interrupt thread in Python?</p> </blockquote> <p>Note that you <strong>can</strong> do it. Its just difficult, and people will wax philosophical about how it is evil. But this is true in any language. You can either use the following API function:</p> <p><a href="http://docs.python.org/c-api/init.html#PyThreadState_SetAsyncExc" rel="nofollow">http://docs.python.org/c-api/init.html#PyThreadState_SetAsyncExc</a></p> <p>Or you can use your underlying OS like TerminateThread in windows off the TID. Just be sure to acquire the global lock.</p> <blockquote> <p>Thread groups - what are they really for? Does Python support them too?</p> </blockquote> <p>I don't believe so. They are for controlling groups of threads.</p> <blockquote> <p>Synchronization - in Java we use simply keyword synchorinized for a method, object...What about Python?</p> </blockquote> <p>Read the thread and threading module.</p>
1
2009-06-10T18:42:17Z
[ "java", "python", "multithreading" ]
Threads in Java and Python
970,909
<p>i have few questions about threads in Python and Java...</p> <ol> <li>Is it possible to give priorities to Python threads, as it is in Java?</li> <li>How can I kill, stop, suspend and interrupt thread in Python?</li> <li>Thread groups - what are they really for? Does Python support them too?</li> <li>Synchronization - in Java we use simply keyword synchorinized for a method, object...What about Python? </li> </ol> <p>Tnx!</p>
5
2009-06-09T15:49:05Z
983,519
<p>here's an example of how I allow my threads to be halted (only works for threads within loops really, unless you wanted to place an if "self.alive" before every line):</p> <pre><code>import threading, Queue class HaltableThread(object.Thread): def __init__(self): self.stringQueue = Queue.Queue() self.alive = True def run(self): while self.alive: try: data = self.stringQueue.read(0.01) #100ms block until data except Queue.Empty: pass else: print data def stop(self): self.alive = False </code></pre>
1
2009-06-11T20:36:58Z
[ "java", "python", "multithreading" ]
Testing for mysterious load errors in python/django
970,953
<p>This is related to this <a href="http://stackoverflow.com/questions/926579/configure-apache-to-recover-from-modpython-errors">http://stackoverflow.com/questions/926579/configure-apache-to-recover-from-modpython-errors</a>, although I've since stopped assuming that this has anything to do with mod_python. Essentially, I have a problem that I wasn't able to reproduce consistently and I wanted some feedback on whether the proposed solution seems likely and some potential ways to try and reproduce this problem.</p> <p>The setup: a django-powered site would begin throwing errors after a few days of use. They were always <code>ImportError</code>s or <code>ImproperlyConfigured</code> errors, which amount to the same thing, since the message always specified trouble loading some module referenced in the settings.py file. It was not generally the same class. I am using preforked apache with 8 forked children, and whenever this problem would come up, one process would be broken and seven would be fine. Once broken, every request (with Debug On in the apache conf) would display the same trace every time it served a request, even if the failed load is not relevant to the particular request. An <code>httpd restart</code> always made the problem go away in the short run.</p> <p>Noted problems: installation and updates are performed via svn with some post-update scripts. A few <code>.pyc</code> files accidentally were checked into the repository. Additionally, the project itself was owned by one user (not apache, although apache had permissions on the project) and there was a persistent plugin that ended up getting backgrounded as root. I call these noted problems because they would be wrong whether or not I noticed this error, and hence I have fixed them. The project is owned by apache and the plugin is backgrounded as apache. All <code>.pyc</code> files are out of the repository, and they are all force-recompiled after each checkout while the server and plugin have been stopped.</p> <p>What I want to know is</p> <ol> <li>Do these configuration disasters seem like a likely explanation for sporadic <code>ImportError</code>s?</li> <li>If there <em>is</em> still a problem somewhere else in my code, how would I best reproduce it?</li> </ol> <p>As for 2, my approach thus far has been to write some stress tests that repeatedly request the same page so as to execute common code paths.</p> <p>Incidentally, this has been running without incident for about 2 days since the fix, but the problem was observed with 1 to 10 day intervals between.</p>
0
2009-06-09T15:54:13Z
971,454
<p><strong>"Do these configuration disasters seem like a likely explanation for sporadic ImportErrors"</strong></p> <p>Yes. An old <code>.pyc</code> file is a disaster of the first magnitude.</p> <p>We develop on Windows, but run production on Red Hat Linux. An accidentally moved .pyc file is an absolute mystery to debug because (1) it usually runs and (2) it has a Windows filename for the original source, making the traceback error absolutely senseless. I spent hours staring at logs -- on linux -- wondering why the file was "C:\This\N\That".</p> <p><strong>"If there is still a problem somewhere else in my code, how would I best reproduce it?"</strong></p> <p>Before reproducing errors, you should try to prevent them.</p> <p>First, create unit tests to exercise everything. </p> <p>Start with Django's <code>tests.py</code> <a href="http://docs.djangoproject.com/en/dev/topics/testing/#topics-testing" rel="nofollow">testing</a>. Then expand to <a href="http://docs.python.org/library/unittest.html" rel="nofollow">unittest</a> for all non-Django components. Then write yourself a "run_tests" script that runs every test you own. Run this periodically. Daily isn't often enough.</p> <p>Second, be sure you're using <a href="http://docs.python.org/library/logging.html" rel="nofollow">logging</a>. Heavily. </p> <p>Third, wrap anything that uses external resources in generic exception-logging blocks like this.</p> <pre><code>try: some_external_resource_processing() except Exception, e: logger.exception( e ) raise </code></pre> <p>This will help you pinpoint problems with external resources. Files and databases are often the source of bad behavior due to permission or access problems.</p> <p>At this point, you have prevented a large number of errors. If you want to run cyclic load testing, that's not a bad idea either. Use unittest for this. </p> <pre><code>class SomeLoadtest( unittest.TestCase ): def test_something( self ): self.connection = urllib2.urlopen( "localhost:8000/some/path" ) results = self.connection.read() </code></pre> <p>This isn't the <em>best</em> way to do things, but it shows one approach. You might want to start using <a href="http://seleniumhq.org/" rel="nofollow">Selenium</a> to test the web site "from the outside" as a complement to your unittests.</p>
2
2009-06-09T17:32:29Z
[ "python", "django", "apache", "configuration" ]
Python and reading lines
970,975
<p>When i run an .exe file it prints stuff out to the screen. I don't know the specific line of where i want printed out but is there a way I can get python to print the next line after one that says "Summary" ? I know that is in there when it prints and I need the info right after. Thanks!</p>
0
2009-06-09T15:57:31Z
971,003
<p>actually </p> <pre><code>program.exe | grep -A 1 Summary </code></pre> <p>would do your job.</p>
2
2009-06-09T16:02:18Z
[ "python", "printing", "command-prompt" ]
Python and reading lines
970,975
<p>When i run an .exe file it prints stuff out to the screen. I don't know the specific line of where i want printed out but is there a way I can get python to print the next line after one that says "Summary" ? I know that is in there when it prints and I need the info right after. Thanks!</p>
0
2009-06-09T15:57:31Z
971,029
<p>Really simple Python solution:</p> <pre><code>def getSummary(s): return s[s.find('\nSummary'):] </code></pre> <p>This returns everything after the first instance of <strong>Summary</strong> <br>If you need to be more specific, I'd recommend regular expressions.</p>
3
2009-06-09T16:06:18Z
[ "python", "printing", "command-prompt" ]
Python and reading lines
970,975
<p>When i run an .exe file it prints stuff out to the screen. I don't know the specific line of where i want printed out but is there a way I can get python to print the next line after one that says "Summary" ? I know that is in there when it prints and I need the info right after. Thanks!</p>
0
2009-06-09T15:57:31Z
975,486
<p>If the exe prints to screen then pipe that output to a text file. I have assumed the exe is on windows, then from the command line: </p> <blockquote> <p>myapp.exe > output.txt</p> </blockquote> <p>And your reasonably robust python code would be something like:</p> <pre><code>try: f = open("output.txt", "r") lines = f.readlines() # Using enumerate gives a convenient index. for i, line in enumerate(lines) : if 'Summary' in line : print lines[i+1] break # exit early # Python throws this if 'Summary' was there but nothing is after it. except IndexError, e : print "I didn't find a line after the Summary" # You could catch other exceptions, as needed. finally : f.close() </code></pre>
1
2009-06-10T13:13:27Z
[ "python", "printing", "command-prompt" ]
Have csv.reader tell when it is on the last line
970,983
<p>Apparently some csv output implementation somewhere truncates field separators from the right on the last row and only the last row in the file when the fields are null.</p> <p>Example input csv, fields 'c' and 'd' are nullable:</p> <pre><code>a|b|c|d 1|2|| 1|2|3|4 3|4|| 2|3 </code></pre> <p>In something like the script below, how can I tell whether I am on the last line so I know how to handle it appropriately?</p> <pre><code>import csv reader = csv.reader(open('somefile.csv'), delimiter='|', quotechar=None) header = reader.next() for line_num, row in enumerate(reader): assert len(row) == len(header) .... </code></pre>
6
2009-06-09T15:58:47Z
971,015
<p>Basically you only know you've run out <em>after</em> you've run out. So you could wrap the <code>reader</code> iterator, e.g. as follows:</p> <pre><code>def isLast(itr): old = itr.next() for new in itr: yield False, old old = new yield True, old </code></pre> <p>and change your code to:</p> <pre><code>for line_num, (is_last, row) in enumerate(isLast(reader)): if not is_last: assert len(row) == len(header) </code></pre> <p>etc.</p>
10
2009-06-09T16:03:43Z
[ "python", "csv" ]
Have csv.reader tell when it is on the last line
970,983
<p>Apparently some csv output implementation somewhere truncates field separators from the right on the last row and only the last row in the file when the fields are null.</p> <p>Example input csv, fields 'c' and 'd' are nullable:</p> <pre><code>a|b|c|d 1|2|| 1|2|3|4 3|4|| 2|3 </code></pre> <p>In something like the script below, how can I tell whether I am on the last line so I know how to handle it appropriately?</p> <pre><code>import csv reader = csv.reader(open('somefile.csv'), delimiter='|', quotechar=None) header = reader.next() for line_num, row in enumerate(reader): assert len(row) == len(header) .... </code></pre>
6
2009-06-09T15:58:47Z
971,024
<p>Just extend the row to the length of the header:</p> <pre><code>for line_num, row in enumerate(reader): while len(row) &lt; len(header): row.append('') ... </code></pre>
0
2009-06-09T16:05:57Z
[ "python", "csv" ]
Have csv.reader tell when it is on the last line
970,983
<p>Apparently some csv output implementation somewhere truncates field separators from the right on the last row and only the last row in the file when the fields are null.</p> <p>Example input csv, fields 'c' and 'd' are nullable:</p> <pre><code>a|b|c|d 1|2|| 1|2|3|4 3|4|| 2|3 </code></pre> <p>In something like the script below, how can I tell whether I am on the last line so I know how to handle it appropriately?</p> <pre><code>import csv reader = csv.reader(open('somefile.csv'), delimiter='|', quotechar=None) header = reader.next() for line_num, row in enumerate(reader): assert len(row) == len(header) .... </code></pre>
6
2009-06-09T15:58:47Z
1,203,092
<p>Could you not just catch the error when the csv reader reads the last line in a </p> <p>try: ... do your stuff here... except: StopIteration </p> <p>condition ?</p> <p>See the following python code on stackoverflow for an example of how to use the try: catch: <a href="http://stackoverflow.com/questions/1202855/python-csv-dictreader-writer-issues">http://stackoverflow.com/questions/1202855/python-csv-dictreader-writer-issues</a></p>
0
2009-07-29T21:15:46Z
[ "python", "csv" ]
Have csv.reader tell when it is on the last line
970,983
<p>Apparently some csv output implementation somewhere truncates field separators from the right on the last row and only the last row in the file when the fields are null.</p> <p>Example input csv, fields 'c' and 'd' are nullable:</p> <pre><code>a|b|c|d 1|2|| 1|2|3|4 3|4|| 2|3 </code></pre> <p>In something like the script below, how can I tell whether I am on the last line so I know how to handle it appropriately?</p> <pre><code>import csv reader = csv.reader(open('somefile.csv'), delimiter='|', quotechar=None) header = reader.next() for line_num, row in enumerate(reader): assert len(row) == len(header) .... </code></pre>
6
2009-06-09T15:58:47Z
1,204,103
<p>If you have an expectation of a fixed number of columns in each row, then you should be defensive against:</p> <p>(1) <em>ANY</em> row being shorter -- e.g. a writer (SQL Server / Query Analyzer IIRC) may omit trailing NULLs <em>at random</em>; users may fiddle with the file using a text editor, including leaving blank lines.</p> <p>(2) <em>ANY</em> row being longer -- e.g. commas not quoted properly.</p> <p>You don't need any fancy tricks. Just an old-fashioned if-test in your row-reading loop:</p> <pre><code>for row in csv.reader(...): ncols = len(row) if ncols != expected_cols: appropriate_action() </code></pre>
1
2009-07-30T02:09:46Z
[ "python", "csv" ]
Have csv.reader tell when it is on the last line
970,983
<p>Apparently some csv output implementation somewhere truncates field separators from the right on the last row and only the last row in the file when the fields are null.</p> <p>Example input csv, fields 'c' and 'd' are nullable:</p> <pre><code>a|b|c|d 1|2|| 1|2|3|4 3|4|| 2|3 </code></pre> <p>In something like the script below, how can I tell whether I am on the last line so I know how to handle it appropriately?</p> <pre><code>import csv reader = csv.reader(open('somefile.csv'), delimiter='|', quotechar=None) header = reader.next() for line_num, row in enumerate(reader): assert len(row) == len(header) .... </code></pre>
6
2009-06-09T15:58:47Z
10,833,767
<p>If you use <code>for row in reader:</code>, it will just stop the loop after the last item has been read.</p>
0
2012-05-31T12:36:52Z
[ "python", "csv" ]
Have csv.reader tell when it is on the last line
970,983
<p>Apparently some csv output implementation somewhere truncates field separators from the right on the last row and only the last row in the file when the fields are null.</p> <p>Example input csv, fields 'c' and 'd' are nullable:</p> <pre><code>a|b|c|d 1|2|| 1|2|3|4 3|4|| 2|3 </code></pre> <p>In something like the script below, how can I tell whether I am on the last line so I know how to handle it appropriately?</p> <pre><code>import csv reader = csv.reader(open('somefile.csv'), delimiter='|', quotechar=None) header = reader.next() for line_num, row in enumerate(reader): assert len(row) == len(header) .... </code></pre>
6
2009-06-09T15:58:47Z
22,941,027
<p>if you want to get exactly the last row try this code:</p> <pre><code>with open("\\".join([myPath,files]), 'r') as f: print f.readlines()[-1] #or your own manipulations </code></pre> <p>If you want to continue working with values from row do the following:</p> <pre><code>f.readlines()[-1].split(",")[0] #this would let you get columns by their index </code></pre>
1
2014-04-08T15:08:37Z
[ "python", "csv" ]
gql does not work for get paramters for keys
971,153
<p>I am trying to compare the key to filter results in gql in python but the direct comparision nor typecasting to int works. There fore I am forced to make a work around as mentioned in uncommented lines below. Any clues.</p> <pre><code>row = self.request.get("selectedrow") #mydbobject = DbModel.gql("WHERE key=:1", row).fetch(1) #mydbobject = DbModel.gql("WHERE key=:1", int(row)).fetch(1)#invalid literal for int() with base 10 #print mydbobject,row que = db.Query(DbModel) results = que.fetch(100) mydbobject = None for item in results: if item.key().__str__() in row: mydbobject = item </code></pre> <p>EDIT1- one more attempt that does not retrieve the record, the key exists in datastore along with record mydbobject = DbModel.gql("WHERE key = KEY('%s')"%row).fetch(1)</p>
0
2009-06-09T16:31:59Z
972,195
<p>Am I correct in my assumption that you're basically just want to retrieve an object with a particular key? If so, the <a href="http://code.google.com/appengine/docs/python/datastore/modelclass.html" rel="nofollow">get and get_by_id methods</a> may be of help:</p> <pre><code>mydbobject = DbModel.get_by_id(int(self.request.get("selectedrow"))) </code></pre>
1
2009-06-09T19:58:55Z
[ "python", "google-app-engine", "gqlquery" ]
gql does not work for get paramters for keys
971,153
<p>I am trying to compare the key to filter results in gql in python but the direct comparision nor typecasting to int works. There fore I am forced to make a work around as mentioned in uncommented lines below. Any clues.</p> <pre><code>row = self.request.get("selectedrow") #mydbobject = DbModel.gql("WHERE key=:1", row).fetch(1) #mydbobject = DbModel.gql("WHERE key=:1", int(row)).fetch(1)#invalid literal for int() with base 10 #print mydbobject,row que = db.Query(DbModel) results = que.fetch(100) mydbobject = None for item in results: if item.key().__str__() in row: mydbobject = item </code></pre> <p>EDIT1- one more attempt that does not retrieve the record, the key exists in datastore along with record mydbobject = DbModel.gql("WHERE key = KEY('%s')"%row).fetch(1)</p>
0
2009-06-09T16:31:59Z
972,350
<p>The error "invalid literal for int()" indicate that the paramater pass to int was not a string representing an integer. Try to print the value of "row" for debuging, I bet it is an empty string.</p> <p>The correct way to retrieve an element from the key is simply by using the method "get" or "get_by_id". In your case:</p> <pre><code>row = self.request.get("selectedrow") mydbobject = DbModel.get(row) </code></pre>
0
2009-06-09T20:34:56Z
[ "python", "google-app-engine", "gqlquery" ]
cx_Oracle And User Defined Types
971,250
<p>Does anyone know an easier way to work with user defined types in Oracle using cx_Oracle?</p> <p>For example, if I have these two types:</p> <pre><code>CREATE type my_type as object( component varchar2(30) ,key varchar2(100) ,value varchar2(4000)) / CREATE type my_type_tab as table of my_type / </code></pre> <p>And then a procedure in package <code>my_package</code> as follows:</p> <pre><code>PROCEDURE my_procedure (param in my_type_tab); </code></pre> <p>To execute the procedure in PL/SQL I can do something like this:</p> <pre><code>declare l_parms my_type_tab; l_cnt pls_integer; begin l_parms := my_type_tab(); l_parms.extend; l_cnt := l_parms.count; l_parms(l_cnt) := my_type('foo','bar','hello'); l_parms.extend; l_cnt := l_parms.count; l_parms(l_cnt) := my_type('faz','baz','world'); my_package.my_procedure(l_parms); end; </code></pre> <p>However, I was wondering how I can do it in Python, similar to this code:</p> <pre><code>import cx_Oracle orcl = cx_Oracle.connect('foo:bar@mydb.com:5555/blah' + instance) curs = orcl.cursor() params = ??? curs.execute('begin my_package.my_procedure(:params)', params=params) </code></pre> <p>If the parameter was a string I can do this as above, but since it's an user-defined type, I have no idea how to call it without resorting to pure PL/SQL code.</p> <p>Edit: Sorry, I should have said that I was looking for ways to do more in Python code instead of PL/SQL. </p>
2
2009-06-09T16:50:27Z
971,328
<p>Are you trying to populate the table of objects more efficiently?</p> <p>If you can do a SELECT, have a look at the BULK COLLECT INTO clause</p>
0
2009-06-09T17:06:55Z
[ "python", "oracle", "cx-oracle" ]
cx_Oracle And User Defined Types
971,250
<p>Does anyone know an easier way to work with user defined types in Oracle using cx_Oracle?</p> <p>For example, if I have these two types:</p> <pre><code>CREATE type my_type as object( component varchar2(30) ,key varchar2(100) ,value varchar2(4000)) / CREATE type my_type_tab as table of my_type / </code></pre> <p>And then a procedure in package <code>my_package</code> as follows:</p> <pre><code>PROCEDURE my_procedure (param in my_type_tab); </code></pre> <p>To execute the procedure in PL/SQL I can do something like this:</p> <pre><code>declare l_parms my_type_tab; l_cnt pls_integer; begin l_parms := my_type_tab(); l_parms.extend; l_cnt := l_parms.count; l_parms(l_cnt) := my_type('foo','bar','hello'); l_parms.extend; l_cnt := l_parms.count; l_parms(l_cnt) := my_type('faz','baz','world'); my_package.my_procedure(l_parms); end; </code></pre> <p>However, I was wondering how I can do it in Python, similar to this code:</p> <pre><code>import cx_Oracle orcl = cx_Oracle.connect('foo:bar@mydb.com:5555/blah' + instance) curs = orcl.cursor() params = ??? curs.execute('begin my_package.my_procedure(:params)', params=params) </code></pre> <p>If the parameter was a string I can do this as above, but since it's an user-defined type, I have no idea how to call it without resorting to pure PL/SQL code.</p> <p>Edit: Sorry, I should have said that I was looking for ways to do more in Python code instead of PL/SQL. </p>
2
2009-06-09T16:50:27Z
972,200
<p>I'm not quite sure what you mean by hard-coded, but you can build a dynamic array like this:</p> <pre><code>SQL&gt; desc my_procedure Parameter Type Mode Default? --------- ----------- ---- -------- P_IN MY_TYPE_TAB IN SQL&gt; declare 2 l_tab my_type_tab; 3 begin 4 select my_type(owner, table_name, column_name) 5 bulk collect into l_tab 6 from all_tab_columns 7 where rownum &lt;= 10; 8 my_procedure (l_tab); 9 end; 10 / PL/SQL procedure successfully completed </code></pre> <p>This has been tested with Oracle 11.1.0.6.</p>
-1
2009-06-09T19:59:55Z
[ "python", "oracle", "cx-oracle" ]
cx_Oracle And User Defined Types
971,250
<p>Does anyone know an easier way to work with user defined types in Oracle using cx_Oracle?</p> <p>For example, if I have these two types:</p> <pre><code>CREATE type my_type as object( component varchar2(30) ,key varchar2(100) ,value varchar2(4000)) / CREATE type my_type_tab as table of my_type / </code></pre> <p>And then a procedure in package <code>my_package</code> as follows:</p> <pre><code>PROCEDURE my_procedure (param in my_type_tab); </code></pre> <p>To execute the procedure in PL/SQL I can do something like this:</p> <pre><code>declare l_parms my_type_tab; l_cnt pls_integer; begin l_parms := my_type_tab(); l_parms.extend; l_cnt := l_parms.count; l_parms(l_cnt) := my_type('foo','bar','hello'); l_parms.extend; l_cnt := l_parms.count; l_parms(l_cnt) := my_type('faz','baz','world'); my_package.my_procedure(l_parms); end; </code></pre> <p>However, I was wondering how I can do it in Python, similar to this code:</p> <pre><code>import cx_Oracle orcl = cx_Oracle.connect('foo:bar@mydb.com:5555/blah' + instance) curs = orcl.cursor() params = ??? curs.execute('begin my_package.my_procedure(:params)', params=params) </code></pre> <p>If the parameter was a string I can do this as above, but since it's an user-defined type, I have no idea how to call it without resorting to pure PL/SQL code.</p> <p>Edit: Sorry, I should have said that I was looking for ways to do more in Python code instead of PL/SQL. </p>
2
2009-06-09T16:50:27Z
976,322
<p>While cx_Oracle can select user defined types, it does not to my knowledge support passing in user defined types as bind variables. So for example the following will work:</p> <pre><code>cursor.execute("select my_type('foo', 'bar', 'hello') from dual") val, = cursor.fetchone() print val.COMPONENT, val.KEY, val.VALUE </code></pre> <p>However what you can't do is construct a Python object, pass it in as an input argument and then have cx_Oracle "translate" the Python object into your Oracle type. So I would say you're going to have to construct your input argument within a PL/SQL block.</p> <p>You can pass in Python lists, so the following should work:</p> <pre><code>components=["foo", "faz"] values=["bar", "baz"] keys=["hello", "world"] cursor.execute(""" declare type udt_StringList is table of varchar2(4000) index by binary_integer; l_components udt_StringList := :p_components; l_keys udt_StringList := :p_keys; l_values udt_StringList := :p_values; l_parms my_type_tab; begin l_parms.extend(l_components.count); for i in 1..l_components.count loop l_parms(i) := my_type(l_components(i), l_keys(i), l_values(i)); end loop; my_package.my_procedure(l_parms); end;""", p_components=components, p_values=values, p_keys=keys) </code></pre>
3
2009-06-10T15:24:04Z
[ "python", "oracle", "cx-oracle" ]
Opencv sort sequences in python
971,629
<p>I'm using the Python OpenCV bindings to find the contours in an Image. I'm know looking for the possibility to sort this sequence. </p> <p>It seems the usual python ways for list sorting don't apply here because of the linked list structure generated from OpenCV. </p> <p>Do you know a good way to sort the Contours by Size (Area/BoundingRectangle) in python? Is it possible to give some example code? </p>
1
2009-06-09T18:08:31Z
971,697
<p>You have to be able to look at an entire sequence in order to sort it (easily). Thus you should copy it to sort it.</p> <p>I would do something like</p> <pre><code> contourList = list(&lt;your linked list&gt;) def sizeKey(countour): &lt;get size from contour&gt; contourList.sort(key = sizeKey) </code></pre> <p>If everything is not being stored in memory already you can also look at <a href="http://en.wikipedia.org/wiki/External%5Fsorting" rel="nofollow">external sorting</a> algorithms.</p>
2
2009-06-09T18:22:16Z
[ "python", "sorting", "image-processing", "opencv", "contour" ]
Interfacing web crawler with Django front end
971,660
<p>I'm trying to do three things.</p> <p>One: crawl and archive, at least daily, a predefined set of sites.</p> <p>Two: run overnight batch python scripts on this data (text classification).</p> <p>Three: expose a Django based front end to users to let them search the crawled data.</p> <p>I've been playing with Apache Nutch/Lucene but getting it to play nice with Django just seems too difficult when I could just use another crawler engine.</p> <p>Question <a href="http://stackoverflow.com/questions/950790/use-django-framework-with-website-and-stand-alone-app">950790</a> suggests I could just write the crawler in Django itself, but I'm not sure how to go about this.</p> <p>Basically - any pointers to writing a crawler in Django or an existing python crawler that I could adapt? Or should I incorporate 'turning into Django-friendly stuff' in step two and write some glue code? Or, finally, should I abandon Django altogether? I really need something that can search quickly from the front end, though.</p>
2
2009-06-09T18:14:07Z
971,729
<p>If you insert your django project's app directories into sys.path, you can write standard Python scripts that utilize the Django ORM functionality. We have an /admin/ directory that contains scripts to perform various tasks-- at the top of each script is a block that looks like:</p> <pre><code>sys.path.insert(0,os.path.abspath('../my_django_project')) sys.path.insert(0,os.path.abspath('../')) sys.path.insert(0,os.path.abspath('../../')) os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' </code></pre> <p>Then it's just a matter of using your tool of choice to crawl the web and using the Django database API to store the data.</p>
3
2009-06-09T18:28:06Z
[ "python", "django", "web-crawler" ]
Interfacing web crawler with Django front end
971,660
<p>I'm trying to do three things.</p> <p>One: crawl and archive, at least daily, a predefined set of sites.</p> <p>Two: run overnight batch python scripts on this data (text classification).</p> <p>Three: expose a Django based front end to users to let them search the crawled data.</p> <p>I've been playing with Apache Nutch/Lucene but getting it to play nice with Django just seems too difficult when I could just use another crawler engine.</p> <p>Question <a href="http://stackoverflow.com/questions/950790/use-django-framework-with-website-and-stand-alone-app">950790</a> suggests I could just write the crawler in Django itself, but I'm not sure how to go about this.</p> <p>Basically - any pointers to writing a crawler in Django or an existing python crawler that I could adapt? Or should I incorporate 'turning into Django-friendly stuff' in step two and write some glue code? Or, finally, should I abandon Django altogether? I really need something that can search quickly from the front end, though.</p>
2
2009-06-09T18:14:07Z
971,752
<p>If you don't want to write crawler using Django ORM (or already have working crawler) you could share database between crawler and Django-powred front-end.</p> <p>To be able to search (and edit) existing database using Django admin you should create Django models. The easy way for that is described here:</p> <p><a href="http://docs.djangoproject.com/en/dev/howto/legacy-databases/" rel="nofollow">http://docs.djangoproject.com/en/dev/howto/legacy-databases/</a> </p>
1
2009-06-09T18:32:19Z
[ "python", "django", "web-crawler" ]
Interfacing web crawler with Django front end
971,660
<p>I'm trying to do three things.</p> <p>One: crawl and archive, at least daily, a predefined set of sites.</p> <p>Two: run overnight batch python scripts on this data (text classification).</p> <p>Three: expose a Django based front end to users to let them search the crawled data.</p> <p>I've been playing with Apache Nutch/Lucene but getting it to play nice with Django just seems too difficult when I could just use another crawler engine.</p> <p>Question <a href="http://stackoverflow.com/questions/950790/use-django-framework-with-website-and-stand-alone-app">950790</a> suggests I could just write the crawler in Django itself, but I'm not sure how to go about this.</p> <p>Basically - any pointers to writing a crawler in Django or an existing python crawler that I could adapt? Or should I incorporate 'turning into Django-friendly stuff' in step two and write some glue code? Or, finally, should I abandon Django altogether? I really need something that can search quickly from the front end, though.</p>
2
2009-06-09T18:14:07Z
971,834
<p>You write your own crawler using <a href="http://docs.python.org/library/urllib2.html" rel="nofollow">urllib2</a> to get the pages and <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a> to parse the HTML looking for the content.</p> <p>Here's an example of reading a page:</p> <p><a href="http://docs.python.org/library/urllib2.html#examples" rel="nofollow">http://docs.python.org/library/urllib2.html#examples</a></p> <p>Here's an example of parsing the page:</p> <p><a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#Parsing" rel="nofollow">http://www.crummy.com/software/BeautifulSoup/documentation.html#Parsing</a> HTML</p>
2
2009-06-09T18:52:47Z
[ "python", "django", "web-crawler" ]
Iterating through a multidimensional array in Python
971,678
<p>I have created a multidimensional array in Python like this:</p> <pre><code>self.cells = np.empty((r,c),dtype=np.object) </code></pre> <p>Now I want to iterate through all elements of my twodimensional array, and I do not care about the order. How do I achieve this?</p>
21
2009-06-09T18:18:06Z
971,733
<p>Just iterate over one dimension, then the other.</p> <pre><code>for row in self.cells: for cell in row: do_something(cell) </code></pre> <p>Of course, with only two dimensions, you can compress this down to a single loop using a <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions">list comprehension</a> or generator expression, but that's not very scalable or readable:</p> <pre><code>for cell in (cell for row in self.cells for cell in row): do_something(cell) </code></pre> <p>If you need to scale this to multiple dimensions and really want a flat list, you can <a href="http://rightfootin.blogspot.com/2006/09/more-on-python-flatten.html">write a <code>flatten</code> function</a>.</p>
11
2009-06-09T18:29:32Z
[ "python", "arrays", "multidimensional-array", "numpy", "iteration" ]
Iterating through a multidimensional array in Python
971,678
<p>I have created a multidimensional array in Python like this:</p> <pre><code>self.cells = np.empty((r,c),dtype=np.object) </code></pre> <p>Now I want to iterate through all elements of my twodimensional array, and I do not care about the order. How do I achieve this?</p>
21
2009-06-09T18:18:06Z
971,774
<p>It's clear you're using numpy. With numpy you can just do:</p> <pre><code>for cell in self.cells.flat: do_somethin(cell) </code></pre>
34
2009-06-09T18:34:53Z
[ "python", "arrays", "multidimensional-array", "numpy", "iteration" ]
Iterating through a multidimensional array in Python
971,678
<p>I have created a multidimensional array in Python like this:</p> <pre><code>self.cells = np.empty((r,c),dtype=np.object) </code></pre> <p>Now I want to iterate through all elements of my twodimensional array, and I do not care about the order. How do I achieve this?</p>
21
2009-06-09T18:18:06Z
971,777
<p>How about this:</p> <pre><code>import itertools for cell in itertools.chain(*self.cells): cell.drawCell(surface, posx, posy) </code></pre>
4
2009-06-09T18:35:06Z
[ "python", "arrays", "multidimensional-array", "numpy", "iteration" ]
Iterating through a multidimensional array in Python
971,678
<p>I have created a multidimensional array in Python like this:</p> <pre><code>self.cells = np.empty((r,c),dtype=np.object) </code></pre> <p>Now I want to iterate through all elements of my twodimensional array, and I do not care about the order. How do I achieve this?</p>
21
2009-06-09T18:18:06Z
4,613,211
<p>If you need to change the values of the individual cells then ndenumerate (in numpy) is your friend. Even if you don't it probably still is!</p> <pre><code>for index,value in ndenumerate( self.cells ): do_something( value ) self.cells[index] = new_value </code></pre>
21
2011-01-06T08:56:36Z
[ "python", "arrays", "multidimensional-array", "numpy", "iteration" ]
Iterating through a multidimensional array in Python
971,678
<p>I have created a multidimensional array in Python like this:</p> <pre><code>self.cells = np.empty((r,c),dtype=np.object) </code></pre> <p>Now I want to iterate through all elements of my twodimensional array, and I do not care about the order. How do I achieve this?</p>
21
2009-06-09T18:18:06Z
33,863,653
<p>you can get the index of each element as well as the element itself using enumerate command:</p> <pre><code>for (i,row) in enumerate(cells): for (j,value) in enumerate(row): print i,j,value </code></pre> <p><code>i</code>,<code>j</code> contain the row and column index of the element and <code>value</code> is the element itself.</p>
2
2015-11-23T04:18:17Z
[ "python", "arrays", "multidimensional-array", "numpy", "iteration" ]
Iterating through a multidimensional array in Python
971,678
<p>I have created a multidimensional array in Python like this:</p> <pre><code>self.cells = np.empty((r,c),dtype=np.object) </code></pre> <p>Now I want to iterate through all elements of my twodimensional array, and I do not care about the order. How do I achieve this?</p>
21
2009-06-09T18:18:06Z
35,247,114
<p>No one has an answer that will work form arbitrarily many dimensions without numpy, so I'll put here a recursive solution that I've used</p> <pre><code>def iterThrough(lists): if not hasattr(lists[0], '__iter__'): for val in lists: yield val else: for l in lists: for val in iterThrough(l): yield val for val in iterThrough( [[[111,112,113],[121,122,123],[131,132,133]], [[211,212,213],[221,222,223],[231,232,233]], [[311,312,313],[321,322,323],[331,332,333]]]): print(val) # 111 # 112 # 113 # 121 # .. </code></pre> <p>There isn't very good error checking but it works for me</p>
0
2016-02-06T22:12:58Z
[ "python", "arrays", "multidimensional-array", "numpy", "iteration" ]
Django conditional aggregation
971,695
<p>Does anyone know of how I would, through the django ORM, produce a query that conditionally aggregated related models?</p> <p>Let's say, for example, that you run a site that sells stuff, and you want to know how much each employee has sold in the last seven days. It's simple enough to do this over all sales:</p> <pre><code>q = Employee.objects.filter(type='salesman').annotate(total_sales = models.Sum('sale__total')) </code></pre> <p>assuming Employee and Sale models with a many-to-many relationship between them. OK, but now how would I go about constraining this to all sales for the last seven days (or any arbitrary time frame)? Does anyone know?</p>
1
2009-06-09T18:21:34Z
972,234
<p>Alright, I guess I didn't think this through very far. I didn't realize that filter handled things with a left join (though thinking on it, how else would it map to the db?), so the obvious answer is:</p> <pre><code>Employee.objects.filter(type='salesman').filter(sale__timestamp__gte = start_date)\ .exclude(sale__timestamp__gte = end_date).annotate(... </code></pre>
2
2009-06-09T20:08:05Z
[ "python", "database", "django", "conditional", "aggregation" ]
Caching values in Python list comprehensions
971,857
<p>I'm using the following list comprehension:</p> <pre><code>resources = [obj.get("file") for obj in iterator if obj.get("file") != None] </code></pre> <p>Is there a way to "cache" the value of <code>obj.get("file")</code> when it's checked in the if statement so that it doesn't have to call <code>get</code> again on obj when it generates the return list?</p>
4
2009-06-09T18:57:40Z
971,880
<pre><code>resources = filter(None, (obj.get("file") for obj in iterator)) </code></pre> <p>See the documentation for <a href="http://docs.python.org/library/functions.html#filter">filter</a> for how to provide your own evaluation function. Passing <code>None</code> for the function (as above) filters out all values which aren't true.</p> <p>If obj.get() returns an object which has a weird <code>__nonzero__</code> method then you'd need to pass <code>lambda obj: obj != None</code> to get exactly the same result as your original code.</p>
9
2009-06-09T19:01:36Z
[ "python", "list-comprehension" ]
Caching values in Python list comprehensions
971,857
<p>I'm using the following list comprehension:</p> <pre><code>resources = [obj.get("file") for obj in iterator if obj.get("file") != None] </code></pre> <p>Is there a way to "cache" the value of <code>obj.get("file")</code> when it's checked in the if statement so that it doesn't have to call <code>get</code> again on obj when it generates the return list?</p>
4
2009-06-09T18:57:40Z
971,890
<p>Try something like this: </p> <pre><code>resources = filter( lambda x: x is not None, [obj.get("file") for ob jin iterator]) </code></pre>
1
2009-06-09T19:02:58Z
[ "python", "list-comprehension" ]
Caching values in Python list comprehensions
971,857
<p>I'm using the following list comprehension:</p> <pre><code>resources = [obj.get("file") for obj in iterator if obj.get("file") != None] </code></pre> <p>Is there a way to "cache" the value of <code>obj.get("file")</code> when it's checked in the if statement so that it doesn't have to call <code>get</code> again on obj when it generates the return list?</p>
4
2009-06-09T18:57:40Z
971,999
<p>Create a temporary dict to hold values. Then, create a function that uses this dict as a cache, and use that function in the list comprehension, like so:</p> <pre><code>obj_cache = {} def cache_get (target, key): if (target, key) not in obj_cache: obj_cache[(target, key)] = target.get(key) return obj_cache[(target, key)] resources = [cache_get(obj, "file") for obj in iterator if cache_get(obj, "file") != None] </code></pre> <p>Also, you probably already know this (and if so, please disregard this answer), but unless obj.get("file") is making a database call, opening a file, making a request over a network, or doing something else potentially expensive, calling it twice per iteration instead of once is probably harmless, since you're only adding O(n) to your cost.</p>
1
2009-06-09T19:20:55Z
[ "python", "list-comprehension" ]
Caching values in Python list comprehensions
971,857
<p>I'm using the following list comprehension:</p> <pre><code>resources = [obj.get("file") for obj in iterator if obj.get("file") != None] </code></pre> <p>Is there a way to "cache" the value of <code>obj.get("file")</code> when it's checked in the if statement so that it doesn't have to call <code>get</code> again on obj when it generates the return list?</p>
4
2009-06-09T18:57:40Z
972,253
<p>If you want to stay with list / iterator comprehensions instead of using <code>filter</code> you can simply use: </p> <pre><code>resources = [file_obj for file_obj in (obj.get("file") for obj in iterator) if file_obj is not None] </code></pre>
6
2009-06-09T20:12:22Z
[ "python", "list-comprehension" ]
How to access the session object in Django Syndication framework code
972,267
<p>Quick question. In my syndication feed framework code, </p> <p><a href="http://docs.djangoproject.com/en/dev/ref/contrib/syndication/" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/contrib/syndication/</a> </p> <p>what is the best way to get access to the session? I don't have access to the request, and I can't use </p> <pre><code>from django.contrib.sessions.backends.db import SessionStore </code></pre> <p>as I don't know the session ID, but I need to access some of the variables in the session. </p> <p>i.e. I have:</p> <pre><code>from django.contrib.syndication.feeds import Feed class LatestPhotos(Feed): ... </code></pre> <p>and in that LatestPhotos class, I need to access something in the session to help control the logic flow. I can't find any documentation on the best way to do it.</p> <p>Thanks</p> <p>Thanks! </p>
1
2009-06-09T20:15:35Z
972,477
<p>It seems like a design flaw to be trying to access session data in the LatestPhoto's class. I would assume that if your syndication feed depended on a session variable, then the items you're syndicating (<code>LatestPhotos</code>) should be constructed with that variable?</p> <p>Can you make the logic flow decision before you construct the <code>LatestPhotos</code> object, or at the very least pass the session ID in to the <code>LatestPhotos</code> init routine?</p>
2
2009-06-09T21:00:15Z
[ "python", "django" ]
How to access the session object in Django Syndication framework code
972,267
<p>Quick question. In my syndication feed framework code, </p> <p><a href="http://docs.djangoproject.com/en/dev/ref/contrib/syndication/" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/contrib/syndication/</a> </p> <p>what is the best way to get access to the session? I don't have access to the request, and I can't use </p> <pre><code>from django.contrib.sessions.backends.db import SessionStore </code></pre> <p>as I don't know the session ID, but I need to access some of the variables in the session. </p> <p>i.e. I have:</p> <pre><code>from django.contrib.syndication.feeds import Feed class LatestPhotos(Feed): ... </code></pre> <p>and in that LatestPhotos class, I need to access something in the session to help control the logic flow. I can't find any documentation on the best way to do it.</p> <p>Thanks</p> <p>Thanks! </p>
1
2009-06-09T20:15:35Z
975,410
<p>Figured it out - drrr, so simple. The syndication framework Feed class has a member called request...so simple I never thought of it :)</p> <p>[this comment applies to django 1.1 and earlier syndication framework]</p>
0
2009-06-10T13:00:54Z
[ "python", "django" ]
spawning process from python
972,362
<p>im spawning a script that runs for a long time from a web app like this:</p> <pre><code>os.spawnle(os.P_NOWAIT, "../bin/producenotify.py", "producenotify.py", "xx",os.environ) </code></pre> <p>the script is spawned successfully and it runs, but till it gets over i am not able to free the port that is used by the web app, or in other words i am not able to restart the web app. how do i spawn off a process and make it completely independent of the web app?</p> <p>this is on linux os.</p>
11
2009-06-09T20:38:50Z
972,383
<p>As @mark clarified it's a Linux system, the script could easily make itself fully independent, i.e., a <em>daemon</em>, by following this <a href="http://code.activestate.com/recipes/278731/" rel="nofollow">recipe</a>. (You could also do it in the parent after an <code>os.fork</code> and only then <code>os.exec...</code> the child process).</p> <p>Edit: to clarify some details wrt @mark's comment on my answer: super-user privileges are not needed to "daemonize" a process as per the cookbook recipes, nor is there any need to change the current working directory (though the code in the recipe does do that and more, that's not the crucial part -- rather it's the proper logic sequence of <code>fork</code>, <code>_exit</code> and <code>setsid</code> calls). The various <code>os.exec...</code> variants that do <em>not</em> end in <code>e</code> use the parent process's environment, so that part is easy too -- see <a href="http://docs.python.org/library/os.html#process-management" rel="nofollow">Python online docs</a>.</p> <p>To address suggestions made in others' comments and answers: I believe <code>subprocess</code> and <code>multiprocessing</code> per se don't daemonize the child process, which seems to be what @mark needs; the script could do it for itself, but since <em>some</em> code has to be doing <code>fork</code>s and <code>setsid</code>, it seems neater to me to keep all of the spawning on that low-level plane rather than mix some high-level and some low-level code in the course of the operation.</p> <p>Here's a vastly reduced and simplified version of the recipe at the above URL, tailored to be called in the parent to spawn a daemon child -- this way, the code can be used to execute non-Python executables just as well. As given, the code should meet the needs @mark explained, of course it can be tailored in many ways -- I strongly recommend reading the original recipe and its comments and discussions, as well as the books it recommends, for more information.</p> <pre><code>import os import sys def spawnDaemon(path_to_executable, *args) """Spawn a completely detached subprocess (i.e., a daemon). E.g. for mark: spawnDaemon("../bin/producenotify.py", "producenotify.py", "xx") """ # fork the first time (to make a non-session-leader child process) try: pid = os.fork() except OSError, e: raise RuntimeError("1st fork failed: %s [%d]" % (e.strerror, e.errno)) if pid != 0: # parent (calling) process is all done return # detach from controlling terminal (to make child a session-leader) os.setsid() try: pid = os.fork() except OSError, e: raise RuntimeError("2nd fork failed: %s [%d]" % (e.strerror, e.errno)) raise Exception, "%s [%d]" % (e.strerror, e.errno) if pid != 0: # child process is all done os._exit(0) # grandchild process now non-session-leader, detached from parent # grandchild process must now close all open files try: maxfd = os.sysconf("SC_OPEN_MAX") except (AttributeError, ValueError): maxfd = 1024 for fd in range(maxfd): try: os.close(fd) except OSError: # ERROR, fd wasn't open to begin with (ignored) pass # redirect stdin, stdout and stderr to /dev/null os.open(os.devnull, os.O_RDWR) # standard input (0) os.dup2(0, 1) os.dup2(0, 2) # and finally let's execute the executable for the daemon! try: os.execv(path_to_executable, args) except Exception, e: # oops, we're cut off from the world, let's just give up os._exit(255) </code></pre>
25
2009-06-09T20:43:37Z
[ "python", "process", "spawn" ]
spawning process from python
972,362
<p>im spawning a script that runs for a long time from a web app like this:</p> <pre><code>os.spawnle(os.P_NOWAIT, "../bin/producenotify.py", "producenotify.py", "xx",os.environ) </code></pre> <p>the script is spawned successfully and it runs, but till it gets over i am not able to free the port that is used by the web app, or in other words i am not able to restart the web app. how do i spawn off a process and make it completely independent of the web app?</p> <p>this is on linux os.</p>
11
2009-06-09T20:38:50Z
972,963
<p>You can use the multiprocessing library to spawn processes. A basic example is shown here:</p> <pre><code>from multiprocessing import Process def f(name): print 'hello', name if __name__ == '__main__': p = Process(target=f, args=('bob',)) p.start() p.join() </code></pre>
11
2009-06-09T23:10:20Z
[ "python", "process", "spawn" ]
Python regular expression for multiple tags
972,749
<p>I would like to know how to retrieve all results from each <code>&lt;p&gt;</code> tag.</p> <pre><code>import re htmlText = '&lt;p data="5" size="4"&gt;item1&lt;/p&gt;&lt;p size="4"&gt;item2&lt;/p&gt;&lt;p size="4"&gt;item3&lt;/p&gt;' print re.match('&lt;p[^&gt;]*size="[0-9]"&gt;(.*?)&lt;/p&gt;', htmlText).groups() </code></pre> <p>result:</p> <pre><code>('item1', ) </code></pre> <p>what I need:</p> <pre><code>('item1', 'item2', 'item3') </code></pre>
2
2009-06-09T22:09:22Z
972,760
<p>You can use <code>re.findall</code> like this:</p> <pre><code>import re html = '&lt;p data="5" size="4"&gt;item1&lt;/p&gt;&lt;p size="4"&gt;item2&lt;/p&gt;&lt;p size="4"&gt;item3&lt;/p&gt;' print re.findall('&lt;p[^&gt;]*size="[0-9]"&gt;(.*?)&lt;/p&gt;', html) # This prints: ['item1', 'item2', 'item3'] </code></pre> <p><strong>Edit</strong>: ...but as the many commenters have pointed out, using regular expressions to parse HTML is usually a bad idea.</p>
2
2009-06-09T22:12:46Z
[ "python", "html", "regex" ]
Python regular expression for multiple tags
972,749
<p>I would like to know how to retrieve all results from each <code>&lt;p&gt;</code> tag.</p> <pre><code>import re htmlText = '&lt;p data="5" size="4"&gt;item1&lt;/p&gt;&lt;p size="4"&gt;item2&lt;/p&gt;&lt;p size="4"&gt;item3&lt;/p&gt;' print re.match('&lt;p[^&gt;]*size="[0-9]"&gt;(.*?)&lt;/p&gt;', htmlText).groups() </code></pre> <p>result:</p> <pre><code>('item1', ) </code></pre> <p>what I need:</p> <pre><code>('item1', 'item2', 'item3') </code></pre>
2
2009-06-09T22:09:22Z
972,768
<p>For this type of problem, it is recommended to use a DOM parser, not regex.</p> <p>I've seen <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a> frequently recommended for Python</p>
11
2009-06-09T22:14:02Z
[ "python", "html", "regex" ]
Python regular expression for multiple tags
972,749
<p>I would like to know how to retrieve all results from each <code>&lt;p&gt;</code> tag.</p> <pre><code>import re htmlText = '&lt;p data="5" size="4"&gt;item1&lt;/p&gt;&lt;p size="4"&gt;item2&lt;/p&gt;&lt;p size="4"&gt;item3&lt;/p&gt;' print re.match('&lt;p[^&gt;]*size="[0-9]"&gt;(.*?)&lt;/p&gt;', htmlText).groups() </code></pre> <p>result:</p> <pre><code>('item1', ) </code></pre> <p>what I need:</p> <pre><code>('item1', 'item2', 'item3') </code></pre>
2
2009-06-09T22:09:22Z
972,846
<p>Alternatively, <a href="http://docs.python.org/3.0/library/xml.dom.minidom.html" rel="nofollow">xml.dom.minidom</a> will parse your HTML if,</p> <ul> <li>...it is wellformed</li> <li>...you embed it in a single root element.</li> </ul> <p>E.g.,</p> <pre><code>&gt;&gt;&gt; import xml.dom.minidom &gt;&gt;&gt; htmlText = '&lt;p data="5" size="4"&gt;item1&lt;/p&gt;&lt;p size="4"&gt;item2&lt;/p&gt;&lt;p size="4"&gt;item3&lt;/p&gt;' &gt;&gt;&gt; d = xml.dom.minidom.parseString('&lt;not_p&gt;%s&lt;/not_p&gt;' % htmlText) &gt;&gt;&gt; tuple(map(lambda e: e.firstChild.wholeText, d.firstChild.childNodes)) ('item1', 'item2', 'item3') </code></pre>
2
2009-06-09T22:38:25Z
[ "python", "html", "regex" ]
Python regular expression for multiple tags
972,749
<p>I would like to know how to retrieve all results from each <code>&lt;p&gt;</code> tag.</p> <pre><code>import re htmlText = '&lt;p data="5" size="4"&gt;item1&lt;/p&gt;&lt;p size="4"&gt;item2&lt;/p&gt;&lt;p size="4"&gt;item3&lt;/p&gt;' print re.match('&lt;p[^&gt;]*size="[0-9]"&gt;(.*?)&lt;/p&gt;', htmlText).groups() </code></pre> <p>result:</p> <pre><code>('item1', ) </code></pre> <p>what I need:</p> <pre><code>('item1', 'item2', 'item3') </code></pre>
2
2009-06-09T22:09:22Z
972,928
<p>Beautiful soup is definitely the way to go with a problem like this. The code is cleaner and easier to read. Once you have it installed, getting all the tags looks something like this.</p> <pre><code>from BeautifulSoup import BeautifulSoup import urllib2 def getTags(tag): f = urllib2.urlopen("http://cnn.com") soup = BeautifulSoup(f.read()) return soup.findAll(tag) if __name__ == '__main__': tags = getTags('p') for tag in tags: print(tag.contents) </code></pre> <p>This will print out all the values of the p tags.</p>
5
2009-06-09T23:00:36Z
[ "python", "html", "regex" ]
Python regular expression for multiple tags
972,749
<p>I would like to know how to retrieve all results from each <code>&lt;p&gt;</code> tag.</p> <pre><code>import re htmlText = '&lt;p data="5" size="4"&gt;item1&lt;/p&gt;&lt;p size="4"&gt;item2&lt;/p&gt;&lt;p size="4"&gt;item3&lt;/p&gt;' print re.match('&lt;p[^&gt;]*size="[0-9]"&gt;(.*?)&lt;/p&gt;', htmlText).groups() </code></pre> <p>result:</p> <pre><code>('item1', ) </code></pre> <p>what I need:</p> <pre><code>('item1', 'item2', 'item3') </code></pre>
2
2009-06-09T22:09:22Z
973,538
<p>The regex answer is extremely fragile. Here's proof (and a working BeautifulSoup example).</p> <pre><code>from BeautifulSoup import BeautifulSoup # Here's your HTML html = '&lt;p data="5" size="4"&gt;item1&lt;/p&gt;&lt;p size="4"&gt;item2&lt;/p&gt;&lt;p size="4"&gt;item3&lt;/p&gt;' # Here's some simple HTML that breaks your accepted # answer, but doesn't break BeautifulSoup. # For each example, the regex will ignore the first &lt;p&gt; tag. html2 = '&lt;p size="4" data="5"&gt;item1&lt;/p&gt;&lt;p size="4"&gt;item2&lt;/p&gt;&lt;p size="4"&gt;item3&lt;/p&gt;' html3 = '&lt;p data="5" size="4" &gt;item1&lt;/p&gt;&lt;p size="4"&gt;item2&lt;/p&gt;&lt;p size="4"&gt;item3&lt;/p&gt;' html4 = '&lt;p data="5" size="12"&gt;item1&lt;/p&gt;&lt;p size="4"&gt;item2&lt;/p&gt;&lt;p size="4"&gt;item3&lt;/p&gt;' # This BeautifulSoup code works for all the examples. paragraphs = BeautifulSoup(html).findAll('p') items = [''.join(p.findAll(text=True)) for p in paragraphs] </code></pre> <p>Use BeautifulSoup.</p>
4
2009-06-10T03:19:07Z
[ "python", "html", "regex" ]
Google App Engine and Amazon S3 File Uploads
972,895
<p>I know this has been asked before but there is really not a clear answer. My problem is I built a file upload script for GAE and only found out after, that you can only store files up to aprox. 1MB in the data store. I can stop you right here if you can tell me that if I enable billing the 1MB limit is history but I doubt it.</p> <p>I need to be able to upload up to 20mb per file so I thought maybe I can use Amazon's S3. Any ideas on how to accomplish this?</p> <p>I was told to use a combination of GAE + Ec2 and S3 but I have no idea how this would work.</p> <p>Thanks, Max</p>
6
2009-06-09T22:52:13Z
972,915
<p>Google App Engine and EC2 are competitors. They do the same thing, although GAE provides an environment for your app to run in with strict language restrictions, while EC2 provides you a virtual machine ( think VMWare ) on which to host your application.</p> <p>S3 on the other hand is a raw storage api. You can use a SOAP or REST api to access it. If you want to stick with GAE, you can simply use the <a href="http://developer.amazonwebservices.com/connect/entry.jspa?externalID=134" rel="nofollow">Amazon S3 Python Library</a> to make REST calls from Python to S3.</p> <p>You will, of course, have to pay for usage on S3. Its amazing how granular their billing is. When getting started I was literally charged 4 cents one month.</p>
3
2009-06-09T22:57:34Z
[ "python", "google-app-engine", "amazon-s3", "amazon-ec2" ]
Google App Engine and Amazon S3 File Uploads
972,895
<p>I know this has been asked before but there is really not a clear answer. My problem is I built a file upload script for GAE and only found out after, that you can only store files up to aprox. 1MB in the data store. I can stop you right here if you can tell me that if I enable billing the 1MB limit is history but I doubt it.</p> <p>I need to be able to upload up to 20mb per file so I thought maybe I can use Amazon's S3. Any ideas on how to accomplish this?</p> <p>I was told to use a combination of GAE + Ec2 and S3 but I have no idea how this would work.</p> <p>Thanks, Max</p>
6
2009-06-09T22:52:13Z
972,998
<p>Some Google App Engine + S3 links:</p> <p><a href="http://stackoverflow.com/questions/842426/google-app-engine-large-file-upload">Previous related post... 10mb limit</a>.</p> <p><a href="http://blog.localkinegrinds.com/2009/04/02/lessons-learned-google-app-engine-app-engine-patch-django-boto/" rel="nofollow">This link demonstrates small file uploads</a>. I haven't found an example of large uploads yet... </p> <p><a href="http://bizo-dev.blogspot.com/2009/05/google-app-engine-java-and-s3.html" rel="nofollow">This link</a> shows a different approach, (<a href="http://code.google.com/p/googleappengine/issues/detail?id=1454" rel="nofollow">with a fix for a known issue</a>)</p>
0
2009-06-09T23:23:15Z
[ "python", "google-app-engine", "amazon-s3", "amazon-ec2" ]
Google App Engine and Amazon S3 File Uploads
972,895
<p>I know this has been asked before but there is really not a clear answer. My problem is I built a file upload script for GAE and only found out after, that you can only store files up to aprox. 1MB in the data store. I can stop you right here if you can tell me that if I enable billing the 1MB limit is history but I doubt it.</p> <p>I need to be able to upload up to 20mb per file so I thought maybe I can use Amazon's S3. Any ideas on how to accomplish this?</p> <p>I was told to use a combination of GAE + Ec2 and S3 but I have no idea how this would work.</p> <p>Thanks, Max</p>
6
2009-06-09T22:52:13Z
973,082
<p>From the <a href="http://docs.amazonwebservices.com/AmazonS3/2006-03-01/UsingHTTPPOST.html">Amazon S3 documentation</a>:</p> <ol> <li><p>The user opens a web browser and accesses your web page.</p></li> <li><p>Your web page contains an HTTP form that contains all the information necessary for the user to upload content to Amazon S3.</p></li> <li><p>The user uploads content directly to Amazon S3.</p></li> </ol> <p>GAE prepares and serves the web page, a speedy operation. You user uploads to S3, a lengthy operation, but that is between your user's browser and Amazon; GAE is not involved. </p> <p>Part of the S3 protocol is a *success_action_redirect*, that lets you tell S3 where to aim the browser in the event of a successful upload. That redirect can be to GAE.</p>
13
2009-06-09T23:57:15Z
[ "python", "google-app-engine", "amazon-s3", "amazon-ec2" ]
Google App Engine and Amazon S3 File Uploads
972,895
<p>I know this has been asked before but there is really not a clear answer. My problem is I built a file upload script for GAE and only found out after, that you can only store files up to aprox. 1MB in the data store. I can stop you right here if you can tell me that if I enable billing the 1MB limit is history but I doubt it.</p> <p>I need to be able to upload up to 20mb per file so I thought maybe I can use Amazon's S3. Any ideas on how to accomplish this?</p> <p>I was told to use a combination of GAE + Ec2 and S3 but I have no idea how this would work.</p> <p>Thanks, Max</p>
6
2009-06-09T22:52:13Z
2,004,598
<p>For future reference, Google added support for large file upload (up to 50 MB): The new feature was released as part of the <a href="http://code.google.com/appengine/docs/python/blobstore/overview.html" rel="nofollow">Blobstore API</a> and is discussed <a href="http://code.google.com/appengine/docs/python/blobstore/overview.html" rel="nofollow">here</a>. </p>
2
2010-01-05T06:51:35Z
[ "python", "google-app-engine", "amazon-s3", "amazon-ec2" ]
Google App Engine and Amazon S3 File Uploads
972,895
<p>I know this has been asked before but there is really not a clear answer. My problem is I built a file upload script for GAE and only found out after, that you can only store files up to aprox. 1MB in the data store. I can stop you right here if you can tell me that if I enable billing the 1MB limit is history but I doubt it.</p> <p>I need to be able to upload up to 20mb per file so I thought maybe I can use Amazon's S3. Any ideas on how to accomplish this?</p> <p>I was told to use a combination of GAE + Ec2 and S3 but I have no idea how this would work.</p> <p>Thanks, Max</p>
6
2009-06-09T22:52:13Z
3,515,499
<p>Thomas L Holaday's answer is the correct answer, I suppose. Anyway, just in case, here's a link to Amazon Web Services SDK for App Engine (Java), which you can use e.g. to upload files from App Engine to Amazon S3. (<strong>Edit:</strong> Oh, just noticed -- <em>excepting S3</em>) <a href="http://apetresc.wordpress.com/2010/06/22/introducing-the-gae-aws-sdk-for-java/" rel="nofollow">http://apetresc.wordpress.com/2010/06/22/introducing-the-gae-aws-sdk-for-java/</a></p> <p>Written by Adrian Petrescu. From his web site:</p> <blockquote> <p>[<em>It is</em>] a version of the Amazon Web Services SDK for Java that will run from inside of Google App Engine. This wouldn’t work if you simply included the JAR that AWS provides directly into GAE’s WAR, because GAE’s security model doesn’t allow the Apache Commons HTTP Client to create the sockets and low-level networking primitives it requires to establish an HTTP connection; instead, Google requires you to make all connections through its URLFetch utility</p> </blockquote>
1
2010-08-18T18:41:14Z
[ "python", "google-app-engine", "amazon-s3", "amazon-ec2" ]
Pixmap transparency in PyGTK
973,073
<p>How can I create PyGTK pixmaps with one pixel value set to transparent? I know it has <em>something</em> to do with creating a pixmap of depth 1 and setting it as a mask, but all I find is that it either does nothing or totally erases my pixmap when drawn. At the moment, I make a pixmap with</p> <pre><code>r = self.get_allocation() p1 = gtk.gdk.Pixmap(self.window,r.width,r.height) p1_c = p1.cairo_create() </code></pre> <p>then draw black lines all over it using Cairo. What I'd like to be able to do is to have all of the area not covered by lines transparent (making white the transparent colour, say), so that when I draw it to the window with draw_drawable, it leaves everything 'underneath' intact.</p> <p>The FAQs and mailing list postings regarding this issue are most unhelpful as they are so outdated. Someone must know here!</p>
1
2009-06-09T23:53:30Z
973,095
<p>It looks like you want to use a Pixbuf and not a Pixmap. The Pixbuf includes an alpha setting, which will give you transparency, whereas the Pixmap does not.</p>
1
2009-06-10T00:03:54Z
[ "python", "transparency", "pygtk" ]
Pixmap transparency in PyGTK
973,073
<p>How can I create PyGTK pixmaps with one pixel value set to transparent? I know it has <em>something</em> to do with creating a pixmap of depth 1 and setting it as a mask, but all I find is that it either does nothing or totally erases my pixmap when drawn. At the moment, I make a pixmap with</p> <pre><code>r = self.get_allocation() p1 = gtk.gdk.Pixmap(self.window,r.width,r.height) p1_c = p1.cairo_create() </code></pre> <p>then draw black lines all over it using Cairo. What I'd like to be able to do is to have all of the area not covered by lines transparent (making white the transparent colour, say), so that when I draw it to the window with draw_drawable, it leaves everything 'underneath' intact.</p> <p>The FAQs and mailing list postings regarding this issue are most unhelpful as they are so outdated. Someone must know here!</p>
1
2009-06-09T23:53:30Z
996,923
<p>I don't think you can do what you want with a <code>Pixmap</code> or <code>Pixbuf</code>, but here are two strategies for implementing scribbling on top of an existing <code>Widget</code>. The most obvious one is just to catch the draw event and draw straight onto the <code>Widget</code>'s <code>Drawable</code>, with no retained image in the middle:</p> <pre><code>from gtk import Window, Button, main from math import pi import cairo w = Window() b = Button("Draw on\ntop of me!") def scribble_on(cr): cr.set_source_rgb(0, 0, 0) cr.rectangle(10, 10, 30, 30) cr.fill() cr.arc(50, 50, 10, 0, pi) cr.stroke() def expose_handler(widget, event): cr = widget.window.cairo_create() cr.rectangle(event.area.x, event.area.y, event.area.width, event.area.height) cr.clip() scribble_on(cr) return False b.connect_after("expose_event", expose_handler) w.add(b) w.set_size_request(100, 100) w.show_all() main() </code></pre> <p>A second option, if you want to have an intermediary ARGB image that you don't have to update each time a redraw is requested, would be to pre-render the image to an <code>ImageSurface</code>. Here's a replacement for <code>expose_handler</code>, above, that only draws the image once:</p> <pre><code>import cairo surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 100, 100) scribble_on(cairo.Context(surface)) def expose_image_handler(widget, event): cr = widget.window.cairo_create() cr.rectangle(event.area.x, event.area.y, event.area.width, event.area.height) cr.clip() cr.set_source_surface(surface) cr.paint() </code></pre> <p>If this is the sort of thing you're looking for, I would recommend updating the title of the question to reflect your real need :).</p>
2
2009-06-15T16:00:01Z
[ "python", "transparency", "pygtk" ]
How can I make lxml's parser preserve whitespace outside of the root element?
973,079
<p>I am using lxml to manipulate some existing XML documents, and I want to introduce as little diff noise as possible. Unfortunately by default <a href="http://codespeak.net/lxml/api/lxml.etree.XMLParser-class.html" rel="nofollow">lxml.etree.XMLParser</a> doesn't preserve whitespace before or after the root element of a document:</p> <pre><code>&gt;&gt;&gt; xml = '\n &lt;etaoin&gt;shrdlu&lt;/etaoin&gt;\n' &gt;&gt;&gt; lxml.etree.tostring(lxml.etree.fromstring(xml)) '&lt;etaoin&gt;shrdlu&lt;/etaoin&gt;' &gt;&gt;&gt; lxml.etree.tostring(lxml.etree.fromstring(xml)) == xml False </code></pre> <p>Is this possible using lxml? Is it supported by the underlying libxml2?</p>
1
2009-06-09T23:56:01Z
973,147
<p>Capture the whitespace with a regex and add it back to the string when you're done.</p>
1
2009-06-10T00:21:15Z
[ "python", "xml", "whitespace", "lxml" ]
How can I make lxml's parser preserve whitespace outside of the root element?
973,079
<p>I am using lxml to manipulate some existing XML documents, and I want to introduce as little diff noise as possible. Unfortunately by default <a href="http://codespeak.net/lxml/api/lxml.etree.XMLParser-class.html" rel="nofollow">lxml.etree.XMLParser</a> doesn't preserve whitespace before or after the root element of a document:</p> <pre><code>&gt;&gt;&gt; xml = '\n &lt;etaoin&gt;shrdlu&lt;/etaoin&gt;\n' &gt;&gt;&gt; lxml.etree.tostring(lxml.etree.fromstring(xml)) '&lt;etaoin&gt;shrdlu&lt;/etaoin&gt;' &gt;&gt;&gt; lxml.etree.tostring(lxml.etree.fromstring(xml)) == xml False </code></pre> <p>Is this possible using lxml? Is it supported by the underlying libxml2?</p>
1
2009-06-09T23:56:01Z
977,955
<p>I don't know of any XML library that will do it for you. But using a regex sounds like a decent idea if you really need to do this.</p> <pre><code>&gt;&gt;&gt; xml = '\n &lt;etaoin&gt;shrdlu&lt;/etaoin&gt;\n' &gt;&gt;&gt; head, tail = re.findall(r"^\s*|\s*$", xml)[:2] &gt;&gt;&gt; root = etree.fromstring(xml) &gt;&gt;&gt; out = head + etree.tostring(root) + tail &gt;&gt;&gt; out == xml True </code></pre>
1
2009-06-10T20:25:51Z
[ "python", "xml", "whitespace", "lxml" ]
What is the clojure equivalent of the Python idiom "if __name__ == '__main__'"?
973,106
<p>I'm dabbling in clojure and am having a little trouble trying to determine the clojure (and / or Lisp) equivalent of this common python idiom.</p> <p>The idiom is that at the bottom of a python module there is often a bit of test code, and then a statement which runs the code, for example:</p> <pre><code># mymodule.py class MyClass(object): """Main logic / code for the library lives here""" pass def _runTests(): # Code which tests various aspects of MyClass... mc = MyClass() # etc... assert 2 + 2 == 4 if __name__ == '__main__': _runTests() </code></pre> <p>This is useful for simple, ad-hoc testing. One would normally use this module by writing <code>from mymodule import MyClass</code>, in which case <code>_runTests()</code> is never called, but with the snippet at the end, one can also run it by typing <code>python mymodule.py</code> directly from the command line.</p> <p>Is there an equivalent idiom in Clojure (and/or common lisp)? I'm not after a full-blown unit testing library (well, I am, but not in this question), I'd just like to include some code in a module which will only be run under some circumstances, so I can have a quick way to run code I've been working on but still allow my file to be imported like a normal module / namespace.</p>
24
2009-06-10T00:07:58Z
973,432
<p>I'm very new to Clojure but I think <a href="http://groups.google.com/group/clojure/browse_thread/thread/d3c2c328787c328f/8c8c526fee2d6deb?lnk=gst&amp;q=clojure+python+__name__#8c8c526fee2d6deb" rel="nofollow">this discussion</a> on the Clojure groups may be a solution and/or workaround, specifically the post by Stuart Sierra on April 17th at 10:40 PM. </p>
1
2009-06-10T02:28:39Z
[ "python", "lisp", "clojure", "idioms" ]
What is the clojure equivalent of the Python idiom "if __name__ == '__main__'"?
973,106
<p>I'm dabbling in clojure and am having a little trouble trying to determine the clojure (and / or Lisp) equivalent of this common python idiom.</p> <p>The idiom is that at the bottom of a python module there is often a bit of test code, and then a statement which runs the code, for example:</p> <pre><code># mymodule.py class MyClass(object): """Main logic / code for the library lives here""" pass def _runTests(): # Code which tests various aspects of MyClass... mc = MyClass() # etc... assert 2 + 2 == 4 if __name__ == '__main__': _runTests() </code></pre> <p>This is useful for simple, ad-hoc testing. One would normally use this module by writing <code>from mymodule import MyClass</code>, in which case <code>_runTests()</code> is never called, but with the snippet at the end, one can also run it by typing <code>python mymodule.py</code> directly from the command line.</p> <p>Is there an equivalent idiom in Clojure (and/or common lisp)? I'm not after a full-blown unit testing library (well, I am, but not in this question), I'd just like to include some code in a module which will only be run under some circumstances, so I can have a quick way to run code I've been working on but still allow my file to be imported like a normal module / namespace.</p>
24
2009-06-10T00:07:58Z
973,662
<p>You might want to have a look at the <a href="http://code.google.com/p/clojure-contrib/source/browse/trunk/src/clojure/contrib/test%5Fis.clj" rel="nofollow">test-is</a> library from clojure-contrib. It's not the same idiom, but it should support a pretty similar workflow.</p>
0
2009-06-10T04:17:37Z
[ "python", "lisp", "clojure", "idioms" ]
What is the clojure equivalent of the Python idiom "if __name__ == '__main__'"?
973,106
<p>I'm dabbling in clojure and am having a little trouble trying to determine the clojure (and / or Lisp) equivalent of this common python idiom.</p> <p>The idiom is that at the bottom of a python module there is often a bit of test code, and then a statement which runs the code, for example:</p> <pre><code># mymodule.py class MyClass(object): """Main logic / code for the library lives here""" pass def _runTests(): # Code which tests various aspects of MyClass... mc = MyClass() # etc... assert 2 + 2 == 4 if __name__ == '__main__': _runTests() </code></pre> <p>This is useful for simple, ad-hoc testing. One would normally use this module by writing <code>from mymodule import MyClass</code>, in which case <code>_runTests()</code> is never called, but with the snippet at the end, one can also run it by typing <code>python mymodule.py</code> directly from the command line.</p> <p>Is there an equivalent idiom in Clojure (and/or common lisp)? I'm not after a full-blown unit testing library (well, I am, but not in this question), I'd just like to include some code in a module which will only be run under some circumstances, so I can have a quick way to run code I've been working on but still allow my file to be imported like a normal module / namespace.</p>
24
2009-06-10T00:07:58Z
973,694
<p>In Common Lisp you can use conditional reading with <a href="http://www.lispworks.com/documentation/HyperSpec/Body/24%5Fab.htm" rel="nofollow">features</a>.</p> <pre><code>#+testing (run-test 'is-answer-equal-42) </code></pre> <p>Above will only be read and thus execute during load if the list of features bound to <a href="http://www.lispworks.com/documentation/HyperSpec/Body/v%5Ffeatur.htm#STfeaturesST" rel="nofollow">cl:*features*</a> will contain the symbol :testing .</p> <p>For example</p> <pre><code>(let ((*features* (cons :testing *features*))) (load "/foo/bar/my-answerlib.lisp")) </code></pre> <p>will temporarily add :testing to the list of features.</p> <p>You can define your own features and control which expressions the Common Lisp system reads and which it skips.</p> <p>Additionally you can also do:</p> <pre><code>#-testing (print '|we are in production mode|) </code></pre>
1
2009-06-10T04:33:24Z
[ "python", "lisp", "clojure", "idioms" ]
What is the clojure equivalent of the Python idiom "if __name__ == '__main__'"?
973,106
<p>I'm dabbling in clojure and am having a little trouble trying to determine the clojure (and / or Lisp) equivalent of this common python idiom.</p> <p>The idiom is that at the bottom of a python module there is often a bit of test code, and then a statement which runs the code, for example:</p> <pre><code># mymodule.py class MyClass(object): """Main logic / code for the library lives here""" pass def _runTests(): # Code which tests various aspects of MyClass... mc = MyClass() # etc... assert 2 + 2 == 4 if __name__ == '__main__': _runTests() </code></pre> <p>This is useful for simple, ad-hoc testing. One would normally use this module by writing <code>from mymodule import MyClass</code>, in which case <code>_runTests()</code> is never called, but with the snippet at the end, one can also run it by typing <code>python mymodule.py</code> directly from the command line.</p> <p>Is there an equivalent idiom in Clojure (and/or common lisp)? I'm not after a full-blown unit testing library (well, I am, but not in this question), I'd just like to include some code in a module which will only be run under some circumstances, so I can have a quick way to run code I've been working on but still allow my file to be imported like a normal module / namespace.</p>
24
2009-06-10T00:07:58Z
973,935
<p>Common Lisp and Clojure (as well as other lisps) provide interactive environment with REPL, and you do not need tricks like «<code>if __name__ == '__main__'</code>». There are REPL-like environments for python: the python from command-line, ipython, python mode for Emacs, etc.</p> <p>You should just create the library, add a testsuite to it (there are many testing frameworks for Common Lisp; I prefer the <a href="http://common-lisp.net/project/bese/FiveAM.html" rel="nofollow">5am</a> framework, there is a survey of frameworks available <a href="http://aperiodic.net/phil/archives/Geekery/notes-on-lisp-testing-frameworks.html" rel="nofollow">here</a>). And then you load the library, and in the REPL you can do anything with the library: run tests, call functions, experiment, etc.</p> <p>When you find a failing test, you make a fix to it, recompile the changed code, and continue experimenting, running tests without restarting the whole application. This saves a lot of time, because the running application might have accumulated a lot of state (it might have created gui windows, connected to databases, reached some critical moment that is not easily reproduceable), and you don't have to restart it after every change.</p> <p>Here's an example for Common Lisp (from my cl-sqlite library):</p> <p>The code:</p> <pre><code>(def-suite sqlite-suite) (defun run-all-tests () (run! 'sqlite-suite));' (in-suite sqlite-suite) (test test-connect (with-open-database (db ":memory:"))) (test test-disconnect-with-statements (finishes (with-open-database (db ":memory:") (prepare-statement db "create table users (id integer primary key, user_name text not null, age integer null)")))) ... </code></pre> <p>and the interactive session:</p> <pre><code>CL-USER&gt; (sqlite-tests:run-all-tests) ....... Did 7 checks. Pass: 7 (100%) Skip: 0 ( 0%) Fail: 0 ( 0%) NIL CL-USER&gt; (defvar *db* (sqlite:connect ":memory:")) *DB* CL-USER&gt; (sqlite:execute-non-query *db* "create table t1 (field text not null)") ; No value CL-USER&gt; (sqlite:execute-non-query *db* "insert into t1 (field) values (?)" "hello") ; No value CL-USER&gt; (sqlite:execute-to-list *db* "select * from t1") (("hello")) CL-USER&gt; </code></pre> <p>Now suppose that I found bug in sqlite:execute-to-list. I go to the code of this function, fix the bug and recompile this function. Then I call the fixed function and ensure that it works. The in-memory database is not gone, it has the same state as it had before recompile.</p>
0
2009-06-10T06:10:12Z
[ "python", "lisp", "clojure", "idioms" ]
What is the clojure equivalent of the Python idiom "if __name__ == '__main__'"?
973,106
<p>I'm dabbling in clojure and am having a little trouble trying to determine the clojure (and / or Lisp) equivalent of this common python idiom.</p> <p>The idiom is that at the bottom of a python module there is often a bit of test code, and then a statement which runs the code, for example:</p> <pre><code># mymodule.py class MyClass(object): """Main logic / code for the library lives here""" pass def _runTests(): # Code which tests various aspects of MyClass... mc = MyClass() # etc... assert 2 + 2 == 4 if __name__ == '__main__': _runTests() </code></pre> <p>This is useful for simple, ad-hoc testing. One would normally use this module by writing <code>from mymodule import MyClass</code>, in which case <code>_runTests()</code> is never called, but with the snippet at the end, one can also run it by typing <code>python mymodule.py</code> directly from the command line.</p> <p>Is there an equivalent idiom in Clojure (and/or common lisp)? I'm not after a full-blown unit testing library (well, I am, but not in this question), I'd just like to include some code in a module which will only be run under some circumstances, so I can have a quick way to run code I've been working on but still allow my file to be imported like a normal module / namespace.</p>
24
2009-06-10T00:07:58Z
974,286
<p>It's not idiomatic to run Clojure scripts over and over from the command line. The REPL is a better command line. Clojure being a Lisp, it's common to fire up Clojure and leave the same instance running forever, and interact with it rather than restart it. You can change functions in the running instance one at a time, run them and poke them as needed. Escaping the tedious and slow traditional edit/compile/debug cycle is a great feature of Lisps. </p> <p>You can easily write functions to do things like run unit tests, and just call those functions from the REPL whenever you want to run them and ignore them otherwise. It's common in Clojure to use <code>clojure.contrib.test-is</code>, add your test functions to your namespace, then use <code>clojure.contrib.test-is/run-tests</code> to run them all.</p> <p>Another good reason not to run Clojure from the commandline is that the startup time of the JVM can be prohibitive.</p> <p>If you really want to run a Clojure script from the command line, there are a bunch of ways you can do it. See <a href="http://groups.google.com/group/clojure/browse%5Fthread/thread/ca60d98fb4f7e71e/ddc68367d4fa1bc7">the Clojure mailing list</a> for some discussion.</p> <p>One way is to test for the presence of command line arguments. Given this <code>foo.clj</code> in the current directory:</p> <pre><code>(ns foo) (defn hello [x] (println "Hello," x)) (if *command-line-args* (hello "command line") (hello "REPL")) </code></pre> <p>You'll get different behavior depending how you start Clojure.</p> <pre><code>$ java -cp ~/path/to/clojure.jar:. clojure.main foo.clj -- Hello, command line $ java -cp ~/path/to/clojure.jar:. clojure.main Clojure 1.1.0-alpha-SNAPSHOT user=&gt; (use 'foo) Hello, REPL nil user=&gt; </code></pre> <p>See <code>src/clj/clojure/main.clj</code> in the Clojure source if you want to see how this is working.</p> <p>Another way is to compile your code into <code>.class</code> files and invoke them from the Java command line. Given a source file <code>foo.clj</code>:</p> <pre><code>(ns foo (:gen-class)) (defn hello [x] (println "Hello," x)) (defn -main [] (hello "command line")) </code></pre> <p>Make a directory to store the compiled <code>.class</code> files; this defaults to <code>./classes</code>. You must make this folder yourself, Clojure won't create it. Also make sure you set <code>$CLASSPATH</code> to include <code>./classes</code> and the directory with your source code; I'll assume <code>foo.clj</code> is in the current directory. So from the command line:</p> <pre><code>$ mkdir classes $ java -cp ~/path/to/clojure.jar:./classes:. clojure.main Clojure 1.1.0-alpha-SNAPSHOT user=&gt; (compile 'foo) foo </code></pre> <p>In the <code>classes</code> directory you will now have a bunch of <code>.class</code> files. To invoke your code from the command line (running the <code>-main</code> function by default):</p> <pre><code>$ java -cp ~/path/to/clojure.jar:./classes foo Hello, command line. </code></pre> <p>There's a lot of information about compiling Clojure code on <a href="http://clojure.org/compilation">clojure.org</a>.</p>
27
2009-06-10T08:18:39Z
[ "python", "lisp", "clojure", "idioms" ]
What is the clojure equivalent of the Python idiom "if __name__ == '__main__'"?
973,106
<p>I'm dabbling in clojure and am having a little trouble trying to determine the clojure (and / or Lisp) equivalent of this common python idiom.</p> <p>The idiom is that at the bottom of a python module there is often a bit of test code, and then a statement which runs the code, for example:</p> <pre><code># mymodule.py class MyClass(object): """Main logic / code for the library lives here""" pass def _runTests(): # Code which tests various aspects of MyClass... mc = MyClass() # etc... assert 2 + 2 == 4 if __name__ == '__main__': _runTests() </code></pre> <p>This is useful for simple, ad-hoc testing. One would normally use this module by writing <code>from mymodule import MyClass</code>, in which case <code>_runTests()</code> is never called, but with the snippet at the end, one can also run it by typing <code>python mymodule.py</code> directly from the command line.</p> <p>Is there an equivalent idiom in Clojure (and/or common lisp)? I'm not after a full-blown unit testing library (well, I am, but not in this question), I'd just like to include some code in a module which will only be run under some circumstances, so I can have a quick way to run code I've been working on but still allow my file to be imported like a normal module / namespace.</p>
24
2009-06-10T00:07:58Z
1,010,736
<p>If you are talking about having an "entry point" you can certainly do that:</p> <pre><code>(ns foo) (defn foo [n] (inc n)) (defn main [] (println "working") (println "Foo has ran:" (foo 1))) (main) </code></pre> <p>what will happen now is that any time this code is (load-file "foo.clj")'d or (use 'foo) or (require 'foo), then (main) will be called, that's usually not done.</p> <p>Much more common is that a file of code can be loaded at the REPL and then the main function would be called by the user.</p>
-3
2009-06-18T04:11:40Z
[ "python", "lisp", "clojure", "idioms" ]
What is the clojure equivalent of the Python idiom "if __name__ == '__main__'"?
973,106
<p>I'm dabbling in clojure and am having a little trouble trying to determine the clojure (and / or Lisp) equivalent of this common python idiom.</p> <p>The idiom is that at the bottom of a python module there is often a bit of test code, and then a statement which runs the code, for example:</p> <pre><code># mymodule.py class MyClass(object): """Main logic / code for the library lives here""" pass def _runTests(): # Code which tests various aspects of MyClass... mc = MyClass() # etc... assert 2 + 2 == 4 if __name__ == '__main__': _runTests() </code></pre> <p>This is useful for simple, ad-hoc testing. One would normally use this module by writing <code>from mymodule import MyClass</code>, in which case <code>_runTests()</code> is never called, but with the snippet at the end, one can also run it by typing <code>python mymodule.py</code> directly from the command line.</p> <p>Is there an equivalent idiom in Clojure (and/or common lisp)? I'm not after a full-blown unit testing library (well, I am, but not in this question), I'd just like to include some code in a module which will only be run under some circumstances, so I can have a quick way to run code I've been working on but still allow my file to be imported like a normal module / namespace.</p>
24
2009-06-10T00:07:58Z
6,061,668
<p>There's also a list of different possibilities at <a href="http://rosettacode.org/wiki/Scripted_Main#Clojure" rel="nofollow">http://rosettacode.org/wiki/Scripted_Main#Clojure</a>. (If you find a new one - please add it. ;-))</p>
1
2011-05-19T16:17:58Z
[ "python", "lisp", "clojure", "idioms" ]
What is the clojure equivalent of the Python idiom "if __name__ == '__main__'"?
973,106
<p>I'm dabbling in clojure and am having a little trouble trying to determine the clojure (and / or Lisp) equivalent of this common python idiom.</p> <p>The idiom is that at the bottom of a python module there is often a bit of test code, and then a statement which runs the code, for example:</p> <pre><code># mymodule.py class MyClass(object): """Main logic / code for the library lives here""" pass def _runTests(): # Code which tests various aspects of MyClass... mc = MyClass() # etc... assert 2 + 2 == 4 if __name__ == '__main__': _runTests() </code></pre> <p>This is useful for simple, ad-hoc testing. One would normally use this module by writing <code>from mymodule import MyClass</code>, in which case <code>_runTests()</code> is never called, but with the snippet at the end, one can also run it by typing <code>python mymodule.py</code> directly from the command line.</p> <p>Is there an equivalent idiom in Clojure (and/or common lisp)? I'm not after a full-blown unit testing library (well, I am, but not in this question), I'd just like to include some code in a module which will only be run under some circumstances, so I can have a quick way to run code I've been working on but still allow my file to be imported like a normal module / namespace.</p>
24
2009-06-10T00:07:58Z
35,319,034
<p><a href="https://github.com/boot-clj/boot" rel="nofollow">Boot</a> is a build tooling (an alternative to leiningen), that <a href="https://github.com/boot-clj/boot/wiki/Scripts" rel="nofollow">supports scripts</a>. So you could have a boot script beginning with <code>#!/usr/bin/env boot</code> that can have a <code>-main</code> method.</p> <p>You could also make tasks invoked from the command line that would call up different functions of your code. And you could have a packaging task that can create an uberjar for one of these functions as entry points.</p>
0
2016-02-10T15:19:51Z
[ "python", "lisp", "clojure", "idioms" ]
Running a set of Python scripts in a list
973,231
<p>I am working on a Python project that includes a lot of simple example scripts to help new users get used to the system. As well as the source code for each example, I include the output I get on my test machine so users know what to expect when all goes well.</p> <p>It occured to me that I could use this as a crude form of unit testing. Automatically run all the example scripts and do a load of diffs against the expected output.</p> <p>All of my example scripts end with extension .py so I can get their filenames easily enough with something like</p> <pre><code>pythonfiles=[filename for filename in os.listdir(source_directory) if filename[-3:]=='.py'] </code></pre> <p>So, pythonfiles contains something like ['example1.py', 'cool_example.py'] and so on.</p> <p>What syntax can I use to actually run the scripts referenced in this list?</p>
2
2009-06-10T00:56:03Z
973,244
<p>You want to use the <a href="http://docs.python.org/library/subprocess.html#module-subprocess" rel="nofollow">subprocess module</a>.</p>
4
2009-06-10T01:00:54Z
[ "python" ]
Running a set of Python scripts in a list
973,231
<p>I am working on a Python project that includes a lot of simple example scripts to help new users get used to the system. As well as the source code for each example, I include the output I get on my test machine so users know what to expect when all goes well.</p> <p>It occured to me that I could use this as a crude form of unit testing. Automatically run all the example scripts and do a load of diffs against the expected output.</p> <p>All of my example scripts end with extension .py so I can get their filenames easily enough with something like</p> <pre><code>pythonfiles=[filename for filename in os.listdir(source_directory) if filename[-3:]=='.py'] </code></pre> <p>So, pythonfiles contains something like ['example1.py', 'cool_example.py'] and so on.</p> <p>What syntax can I use to actually run the scripts referenced in this list?</p>
2
2009-06-10T00:56:03Z
973,256
<p>You could leverage <a href="http://docs.python.org/library/doctest.html" rel="nofollow">doctest</a> to help you get this done. Write a method that executes each script, and in the docstring for each method you paste the expected output:</p> <pre><code>def run_example1(): """ This is example number 1. Running it should give you the following output: &gt;&gt;&gt; run_example1() "This is the output from example1.py" """ os.system('python example1.py') # or you could use subprocess here if __name__ == "__main__": import doctest doctest.testmod() </code></pre> <p>Note I haven't tested this.</p> <p>Alternatively, as Shane mentioned, you could use subprocess. Something like this will work:</p> <pre><code>import subprocess cmd = ('example1.py', 'any', 'more', 'arguments') expected_out = """Your expected output of the script""" exampleP = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = exampleP.communicate() # out and err are stdout and stderr, respectively if out != expected_out: print "Output does not match" </code></pre>
8
2009-06-10T01:04:41Z
[ "python" ]
Running a set of Python scripts in a list
973,231
<p>I am working on a Python project that includes a lot of simple example scripts to help new users get used to the system. As well as the source code for each example, I include the output I get on my test machine so users know what to expect when all goes well.</p> <p>It occured to me that I could use this as a crude form of unit testing. Automatically run all the example scripts and do a load of diffs against the expected output.</p> <p>All of my example scripts end with extension .py so I can get their filenames easily enough with something like</p> <pre><code>pythonfiles=[filename for filename in os.listdir(source_directory) if filename[-3:]=='.py'] </code></pre> <p>So, pythonfiles contains something like ['example1.py', 'cool_example.py'] and so on.</p> <p>What syntax can I use to actually run the scripts referenced in this list?</p>
2
2009-06-10T00:56:03Z
973,321
<p>If they are similarly structured (All are executed with a run function for example), you can import the them as python scripts, and call thier run function.</p> <pre><code>import sys import os import imp pythonfiles = [filename for filename in os.listdir(source_directory) if filename[-3:]=='.py'] for py_file in pythonfiles: mod_name = os.path.splitext(py_file)[0] py_filepath = os.path.join(source_directory, py_file) py_mod = imp.load_source(mod_name, py_filepath) if hasattr(py_mod, "run"): py_mod.run() else: print '%s has no "run"' % (py_filepath) </code></pre>
3
2009-06-10T01:29:56Z
[ "python" ]
Getting a list of all subdirectories in the current directory
973,473
<p>Is there a way to return a list of all the subdirectories in the current directory in Python?</p> <p>I know you can do this with files, but I need to get the list of directories instead.</p>
179
2009-06-10T02:48:21Z
973,488
<p>Do you mean immediate subdirectories, or every directory right down the tree? </p> <p>Either way, you could use <a href="http://docs.python.org/library/os.html#os.walk"><code>os.walk</code></a> to do this:</p> <pre><code>os.walk(directory) </code></pre> <p>will yield a tuple for each subdirectory. Ths first entry in the 3-tuple is a directory name, so</p> <pre><code>[x[0] for x in os.walk(directory)] </code></pre> <p>should give you all of the directories.</p> <p>Note that the second entry in the tuple is the list of child directories of the entry in the first position, so you could use this instead, but it's not likely to save you much.</p> <p>However, you could use it just to give you the immediate child directories:</p> <pre><code>next(os.walk('.'))[1] </code></pre> <p>Or see the other solutions already posted, using <a href="http://docs.python.org/library/os.html#os.listdir"><code>os.listdir</code></a> and <a href="http://docs.python.org/library/os.path.html#os.path.isdir"><code>os.path.isdir</code></a>, including those at "<a href="http://stackoverflow.com/questions/800197/get-all-of-the-immediate-subdirectories-in-python">get all of the immediate subdirectories in python</a>".</p>
218
2009-06-10T02:54:45Z
[ "python", "directory", "subdirectory" ]
Getting a list of all subdirectories in the current directory
973,473
<p>Is there a way to return a list of all the subdirectories in the current directory in Python?</p> <p>I know you can do this with files, but I need to get the list of directories instead.</p>
179
2009-06-10T02:48:21Z
973,489
<p>If you need a recursive solution that will find all the subdirectories in the subdirectories, use walk as proposed before.</p> <p>If you only need the current directory's child directories, combine <code>os.listdir</code> with <code>os.path.isdir</code></p>
23
2009-06-10T02:56:09Z
[ "python", "directory", "subdirectory" ]
Getting a list of all subdirectories in the current directory
973,473
<p>Is there a way to return a list of all the subdirectories in the current directory in Python?</p> <p>I know you can do this with files, but I need to get the list of directories instead.</p>
179
2009-06-10T02:48:21Z
973,492
<pre><code>import os d='.' [os.path.join(d,o) for o in os.listdir(d) if os.path.isdir(os.path.join(d,o))] </code></pre>
72
2009-06-10T02:57:07Z
[ "python", "directory", "subdirectory" ]
Getting a list of all subdirectories in the current directory
973,473
<p>Is there a way to return a list of all the subdirectories in the current directory in Python?</p> <p>I know you can do this with files, but I need to get the list of directories instead.</p>
179
2009-06-10T02:48:21Z
16,488,785
<p>Thanks for the tips, guys. I ran into an issue with softlinks (infinite recursion) being returned as dirs. Softlinks? We don't want no stinkin' soft links! So...</p> <p>This rendered just the dirs, not softlinks:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; inf = os.walk('.') &gt;&gt;&gt; [x[0] for x in inf] ['.', './iamadir'] </code></pre>
3
2013-05-10T18:38:40Z
[ "python", "directory", "subdirectory" ]
Getting a list of all subdirectories in the current directory
973,473
<p>Is there a way to return a list of all the subdirectories in the current directory in Python?</p> <p>I know you can do this with files, but I need to get the list of directories instead.</p>
179
2009-06-10T02:48:21Z
19,017,207
<p>Implemented this using python-os-walk. (<a href="http://www.pythonforbeginners.com/code-snippets-source-code/python-os-walk/">http://www.pythonforbeginners.com/code-snippets-source-code/python-os-walk/</a>)</p> <pre><code>import os print "root prints out directories only from what you specified" print "dirs prints out sub-directories from root" print "files prints out all files from root and directories" print "*" * 20 for root, dirs, files in os.walk("/var/log"): print root print dirs print files </code></pre>
10
2013-09-26T00:08:29Z
[ "python", "directory", "subdirectory" ]
Getting a list of all subdirectories in the current directory
973,473
<p>Is there a way to return a list of all the subdirectories in the current directory in Python?</p> <p>I know you can do this with files, but I need to get the list of directories instead.</p>
179
2009-06-10T02:48:21Z
19,204,316
<p>With full path and accounting for path being '.', '..', '\', '..\..\subfolder', etc</p> <pre><code>import os, pprint pprint.pprint([os.path.join(os.path.abspath(path), x[0]) for x in os.walk(os.path.abspath(path))]) </code></pre>
2
2013-10-06T01:00:57Z
[ "python", "directory", "subdirectory" ]
Getting a list of all subdirectories in the current directory
973,473
<p>Is there a way to return a list of all the subdirectories in the current directory in Python?</p> <p>I know you can do this with files, but I need to get the list of directories instead.</p>
179
2009-06-10T02:48:21Z
26,237,100
<p>You can get the list of subdirectories in python 2.7 using os.listdir(path)</p> <pre><code> import os, sys subdirectories = os.listdir(path) </code></pre>
4
2014-10-07T13:23:40Z
[ "python", "directory", "subdirectory" ]
Getting a list of all subdirectories in the current directory
973,473
<p>Is there a way to return a list of all the subdirectories in the current directory in Python?</p> <p>I know you can do this with files, but I need to get the list of directories instead.</p>
179
2009-06-10T02:48:21Z
26,846,646
<p>Since I stumbled upon this problem using Python 3.4 and Windows UNC paths, here's a variant for this environment:</p> <pre><code>from pathlib import WindowsPath def SubDirPath (d): return [f for f in d.iterdir() if f.is_dir()] subdirs = SubDirPath(WindowsPath(r'\\file01.acme.local\home$')) print(subdirs) </code></pre> <p>Pathlib is new in Python 3.4 and makes working with paths under different OSes much easier: <a href="https://docs.python.org/3.4/library/pathlib.html" rel="nofollow">https://docs.python.org/3.4/library/pathlib.html</a></p>
4
2014-11-10T15:02:47Z
[ "python", "directory", "subdirectory" ]
Getting a list of all subdirectories in the current directory
973,473
<p>Is there a way to return a list of all the subdirectories in the current directory in Python?</p> <p>I know you can do this with files, but I need to get the list of directories instead.</p>
179
2009-06-10T02:48:21Z
32,505,092
<p>I prefer using filter (<a href="https://docs.python.org/2/library/functions.html#filter">https://docs.python.org/2/library/functions.html#filter</a>), but this is just a matter of taste.</p> <pre><code>d='.' filter(lambda x: os.path.isdir(os.path.join(d, x)), os.listdir(d)) </code></pre>
12
2015-09-10T14:46:58Z
[ "python", "directory", "subdirectory" ]
Getting a list of all subdirectories in the current directory
973,473
<p>Is there a way to return a list of all the subdirectories in the current directory in Python?</p> <p>I know you can do this with files, but I need to get the list of directories instead.</p>
179
2009-06-10T02:48:21Z
34,600,048
<p>Building upon Eli Bendersky's solution, use the following example:</p> <pre><code>import os test_directory = &lt;your_directory&gt; for child in os.listdir(test_directory): test_path = os.path.join(test_directory, child) if os.path.isdir(test_path): print test_path # Do stuff to the directory "test_path" </code></pre> <p>where <code>&lt;your_directory&gt;</code> is the path to the directory you want to traverse.</p>
3
2016-01-04T21:19:33Z
[ "python", "directory", "subdirectory" ]
Getting a list of all subdirectories in the current directory
973,473
<p>Is there a way to return a list of all the subdirectories in the current directory in Python?</p> <p>I know you can do this with files, but I need to get the list of directories instead.</p>
179
2009-06-10T02:48:21Z
35,261,270
<p>use a filter function <code>os.path.isdir</code> over <code>os.listdir()</code> something like this <code>filter(os.path.isdir,[os.path.join(os.path.abspath('PATH'),p) for p in os.listdir('PATH/')])</code></p>
0
2016-02-08T01:30:14Z
[ "python", "directory", "subdirectory" ]
Getting a list of all subdirectories in the current directory
973,473
<p>Is there a way to return a list of all the subdirectories in the current directory in Python?</p> <p>I know you can do this with files, but I need to get the list of directories instead.</p>
179
2009-06-10T02:48:21Z
36,426,997
<p>You could just use <code>glob.glob</code></p> <pre><code>from glob import glob glob("/path/to/directory/*/") </code></pre> <p>Don't forget the trailing <code>/</code> after the <code>*</code>.</p>
11
2016-04-05T12:55:54Z
[ "python", "directory", "subdirectory" ]
Getting a list of all subdirectories in the current directory
973,473
<p>Is there a way to return a list of all the subdirectories in the current directory in Python?</p> <p>I know you can do this with files, but I need to get the list of directories instead.</p>
179
2009-06-10T02:48:21Z
38,245,063
<p>Although this question is answered a long time ago. I want to recommend to use the <a href="https://docs.python.org/3.4/library/pathlib.html#pathlib.Path" rel="nofollow"><code>pathlib</code></a> module since this is a robust way to work on Windows and Unix OS.</p> <p>So to get all paths in a specific directory including subdirectories:</p> <pre><code>from pathlib import Path paths = list(Path('myhomefolder', 'folder').glob('**/*.txt')) # all sorts of operations file = paths[0] file.name file.stem file.parent file.suffix </code></pre> <p>etc.</p>
1
2016-07-07T12:06:46Z
[ "python", "directory", "subdirectory" ]
Getting a list of all subdirectories in the current directory
973,473
<p>Is there a way to return a list of all the subdirectories in the current directory in Python?</p> <p>I know you can do this with files, but I need to get the list of directories instead.</p>
179
2009-06-10T02:48:21Z
39,222,660
<h1>Listing Out only directories</h1> <pre><code>print "\nWe are listing out only the directories in current directory -" directories_in_curdir = filter(os.path.isdir, os.listdir(os.curdir)) print directories_in_curdir </code></pre> <h1>Listing Out only files in current directory</h1> <pre><code>files = filter(os.path.isfile, os.listdir(os.curdir)) print "\nTHe following are the list of all files in the curent directory -" print files </code></pre>
0
2016-08-30T08:40:44Z
[ "python", "directory", "subdirectory" ]
Dynamic Table Creation and ORM mapping in SqlAlchemy
973,481
<p>I'm fairly new to using relational databases, so I prefer using a good ORM to simplify things. I spent time evaluating different Python ORMs and I think SQLAlchemy is what I need. However, I've come to a mental dead end.</p> <p>I need to create a new table to go along with each instance of a player I create in my app's player table. I think I know how to create the table by changing the name of the table through the metadata then calling the create function, but I have no clue on how to map it to a new dynamic class.</p> <p>Can someone give me some tips to help me get past my brain freeze? Is this even possible? </p> <p>Note: I'm open to other ORMs in Python if what I'm asking is easier to implement.Just show me how :-)</p>
7
2009-06-10T02:51:11Z
973,564
<p>May be look at sql soup , which is layer over sqlalchemy <a href="http://www.sqlalchemy.org/trac/wiki/SqlSoup" rel="nofollow">http://www.sqlalchemy.org/trac/wiki/SqlSoup</a></p> <p>or elixir (again a wrapper over sqlalchemy) <a href="http://elixir.ematia.de/trac/wiki" rel="nofollow">http://elixir.ematia.de/trac/wiki</a></p> <p>you may also create table using plain sql, and to dynamically map use these libs if they already don't have create table function.</p> <p>or alternatively create a dynamic class and map it e.g. snippet from my own code</p> <pre><code>tableClass = type(str(table.fullname), (BaseTable.BaseTable,), {}) mapper(tableClass, table) </code></pre> <p>where BaseTable can be any python class which you want all your table classes to inherit from, e.g. such Base class may have some utility or common methods, e.g. basic CRUD methods</p> <pre><code>class BaseTable(object): pass </code></pre> <p>otherwise you need not pass any bases to <code>type(...)</code></p>
3
2009-06-10T03:29:30Z
[ "python", "database", "sqlalchemy" ]
Dynamic Table Creation and ORM mapping in SqlAlchemy
973,481
<p>I'm fairly new to using relational databases, so I prefer using a good ORM to simplify things. I spent time evaluating different Python ORMs and I think SQLAlchemy is what I need. However, I've come to a mental dead end.</p> <p>I need to create a new table to go along with each instance of a player I create in my app's player table. I think I know how to create the table by changing the name of the table through the metadata then calling the create function, but I have no clue on how to map it to a new dynamic class.</p> <p>Can someone give me some tips to help me get past my brain freeze? Is this even possible? </p> <p>Note: I'm open to other ORMs in Python if what I'm asking is easier to implement.Just show me how :-)</p>
7
2009-06-10T02:51:11Z
973,567
<p>We are absolutely spoiled by SqlAlchemy. <br /> What follows below is taken directly from the <a href="http://www.sqlalchemy.org/docs/05/ormtutorial.html">tutorial</a>, <br /> and is really easy to setup and get working.</p> <p>And because it is done so often, <br /> Mike Bayer has made this even easier <br /> with the <a href="http://www.sqlalchemy.org/docs/05/ormtutorial.html#creating-table-class-and-mapper-all-at-once-declaratively">all-in-one "declarative" method</a>.</p> <p>Setup your environment (I'm using the SQLite in-memory db to test):</p> <pre><code>&gt;&gt;&gt; from sqlalchemy import create_engine &gt;&gt;&gt; engine = create_engine('sqlite:///:memory:', echo=True) &gt;&gt;&gt; from sqlalchemy import Table, Column, Integer, String, MetaData &gt;&gt;&gt; metadata = MetaData() </code></pre> <p>Define your table:</p> <pre><code>&gt;&gt;&gt; players_table = Table('players', metadata, ... Column('id', Integer, primary_key=True), ... Column('name', String), ... Column('score', Integer) ... ) &gt;&gt;&gt; metadata.create_all(engine) # create the table </code></pre> <p>If you have logging turned on, you'll see the SQL that SqlAlchemy creates for you.</p> <p>Define your class:</p> <pre><code>&gt;&gt;&gt; class Player(object): ... def __init__(self, name, score): ... self.name = name ... self.score = score ... ... def __repr__(self): ... return "&lt;Player('%s','%s')&gt;" % (self.name, self.score) </code></pre> <p>Map the class to your table:</p> <pre><code>&gt;&gt;&gt; from sqlalchemy.orm import mapper &gt;&gt;&gt; mapper(Player, players_table) &lt;Mapper at 0x...; Player&gt; </code></pre> <p>Create a player:</p> <pre><code>&gt;&gt;&gt; a_player = Player('monty', 0) &gt;&gt;&gt; a_player.name 'monty' &gt;&gt;&gt; a_player.score 0 </code></pre> <p>That's it, you now have a your player table. <br /> Also, the SqlAlchemy googlegroup is great. <br /> Mike Bayer is very quick to answer questions.</p>
17
2009-06-10T03:30:15Z
[ "python", "database", "sqlalchemy" ]
Dynamic Table Creation and ORM mapping in SqlAlchemy
973,481
<p>I'm fairly new to using relational databases, so I prefer using a good ORM to simplify things. I spent time evaluating different Python ORMs and I think SQLAlchemy is what I need. However, I've come to a mental dead end.</p> <p>I need to create a new table to go along with each instance of a player I create in my app's player table. I think I know how to create the table by changing the name of the table through the metadata then calling the create function, but I have no clue on how to map it to a new dynamic class.</p> <p>Can someone give me some tips to help me get past my brain freeze? Is this even possible? </p> <p>Note: I'm open to other ORMs in Python if what I'm asking is easier to implement.Just show me how :-)</p>
7
2009-06-10T02:51:11Z
1,052,559
<p>you can use declarative method for dynamically creating tables in database</p> <pre><code>from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey Base = declarative_base() class Language(Base): __tablename__ = 'languages' id = Column(Integer, primary_key=True) name = Column(String(20)) extension = Column(String(20)) def __init__(self, name, extension): self.name = name self.extension = extension </code></pre>
1
2009-06-27T10:15:08Z
[ "python", "database", "sqlalchemy" ]