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
sequence |
---|---|---|---|---|---|---|---|---|---|
OPENGL User Interface Programming | 78,238 | <p>I'm developing a graphical application to present data (not a game but a real workhorse app). It needs to be cross platform, so I have chosen:</p>
<ul>
<li>python</li>
<li>openGL (I need 3D, blending, textures etc)</li>
<li>pyopengl</li>
<li>wx/pywx - windowing, dialogs etc.</li>
</ul>
<p>The last component - WX - raises the question. I can put together a very nice looking app (the prototypes look slick) - but when I need to interact with the user to ask questions, get input, I have to use WX. It makes the app look inconsistent to have traditional UI with traditional dialogs and combos and text entry on top of a full screen 3D app with blending, smooth motion, textures etc.</p>
<p>Has anyone developed a GUI using OpenGL and python? Can you share with me the toolkits and/or tricks you used? I need combos, text entry, buttons, radios, option buttons, tree view.</p>
<p>There are some toolkits out there, but they are either incomplete or old and unmaintained. A great example is pyUI (http://pyui.sourceforge.net/) - looks slick but untouched for years.</p>
| 1 | 2008-09-16T23:11:31Z | 78,483 | <p>Try Qt instead of wx.</p>
<p>QT is cross platform, and you can style things alot using CSS. It's extremely well documented and has excellent python bindings. In point of fact, I use the C++ documentation and not the PyQT documentation.</p>
| 1 | 2008-09-16T23:57:37Z | [
"python",
"user-interface",
"opengl"
] |
OPENGL User Interface Programming | 78,238 | <p>I'm developing a graphical application to present data (not a game but a real workhorse app). It needs to be cross platform, so I have chosen:</p>
<ul>
<li>python</li>
<li>openGL (I need 3D, blending, textures etc)</li>
<li>pyopengl</li>
<li>wx/pywx - windowing, dialogs etc.</li>
</ul>
<p>The last component - WX - raises the question. I can put together a very nice looking app (the prototypes look slick) - but when I need to interact with the user to ask questions, get input, I have to use WX. It makes the app look inconsistent to have traditional UI with traditional dialogs and combos and text entry on top of a full screen 3D app with blending, smooth motion, textures etc.</p>
<p>Has anyone developed a GUI using OpenGL and python? Can you share with me the toolkits and/or tricks you used? I need combos, text entry, buttons, radios, option buttons, tree view.</p>
<p>There are some toolkits out there, but they are either incomplete or old and unmaintained. A great example is pyUI (http://pyui.sourceforge.net/) - looks slick but untouched for years.</p>
| 1 | 2008-09-16T23:11:31Z | 78,589 | <p>Python + Qt + OpenGL -
I surely believe any application can be written faster and better using python.
QT4 is cross-platform, beautifull, implements everything you need from widgets (acessibility, etc...), and...it integrates with OpenGL. That means, you can simply have a widget that is a viewport to openGL stuff you render in your code.</p>
<p>Another 3D capable solution that would cover most things, but not so nioce on user interface is to extend Blender3D with a python script. It has the 3d capabilities and rendering , you script it in python all of the same, and it would be cross platform - and you get higher level tools for woriking with the 3D things than openGL alone.
There are obvious drawbacks, mainly from the UI standpoint when compared with PyQT but it could be done. </p>
| 3 | 2008-09-17T00:14:41Z | [
"python",
"user-interface",
"opengl"
] |
OPENGL User Interface Programming | 78,238 | <p>I'm developing a graphical application to present data (not a game but a real workhorse app). It needs to be cross platform, so I have chosen:</p>
<ul>
<li>python</li>
<li>openGL (I need 3D, blending, textures etc)</li>
<li>pyopengl</li>
<li>wx/pywx - windowing, dialogs etc.</li>
</ul>
<p>The last component - WX - raises the question. I can put together a very nice looking app (the prototypes look slick) - but when I need to interact with the user to ask questions, get input, I have to use WX. It makes the app look inconsistent to have traditional UI with traditional dialogs and combos and text entry on top of a full screen 3D app with blending, smooth motion, textures etc.</p>
<p>Has anyone developed a GUI using OpenGL and python? Can you share with me the toolkits and/or tricks you used? I need combos, text entry, buttons, radios, option buttons, tree view.</p>
<p>There are some toolkits out there, but they are either incomplete or old and unmaintained. A great example is pyUI (http://pyui.sourceforge.net/) - looks slick but untouched for years.</p>
| 1 | 2008-09-16T23:11:31Z | 85,490 | <p>Both wx and QT do an excellent job of creating an application that matches the OS look and feel.
It is also possible to implment all the widgets yourself directly in openg, this slashdot post lists some of the sets available </p>
<p><a href="http://ask.slashdot.org/askslashdot/02/12/24/1813219.shtml?tid=156" rel="nofollow">http://ask.slashdot.org/askslashdot/02/12/24/1813219.shtml?tid=156</a>
fox is probably the most developed but looks like windows on all platforms.</p>
| 1 | 2008-09-17T17:14:16Z | [
"python",
"user-interface",
"opengl"
] |
OPENGL User Interface Programming | 78,238 | <p>I'm developing a graphical application to present data (not a game but a real workhorse app). It needs to be cross platform, so I have chosen:</p>
<ul>
<li>python</li>
<li>openGL (I need 3D, blending, textures etc)</li>
<li>pyopengl</li>
<li>wx/pywx - windowing, dialogs etc.</li>
</ul>
<p>The last component - WX - raises the question. I can put together a very nice looking app (the prototypes look slick) - but when I need to interact with the user to ask questions, get input, I have to use WX. It makes the app look inconsistent to have traditional UI with traditional dialogs and combos and text entry on top of a full screen 3D app with blending, smooth motion, textures etc.</p>
<p>Has anyone developed a GUI using OpenGL and python? Can you share with me the toolkits and/or tricks you used? I need combos, text entry, buttons, radios, option buttons, tree view.</p>
<p>There are some toolkits out there, but they are either incomplete or old and unmaintained. A great example is pyUI (http://pyui.sourceforge.net/) - looks slick but untouched for years.</p>
| 1 | 2008-09-16T23:11:31Z | 138,630 | <p>In the latest releases of QT you can draw widgets <em>into</em> your OpenGL context, if you really would like to do something like that. Otherwise there is <a href="http://www.cegui.org.uk/wiki/index.php/Main_Page">CEGui</a> that is used in some game engines. </p>
<p>Implementing GUI Widgets yourself unless you want to edify yourself is a waste of your time, unless you would be satisfied with the most rudimentary of looks and functionality. </p>
| 7 | 2008-09-26T10:21:40Z | [
"python",
"user-interface",
"opengl"
] |
OPENGL User Interface Programming | 78,238 | <p>I'm developing a graphical application to present data (not a game but a real workhorse app). It needs to be cross platform, so I have chosen:</p>
<ul>
<li>python</li>
<li>openGL (I need 3D, blending, textures etc)</li>
<li>pyopengl</li>
<li>wx/pywx - windowing, dialogs etc.</li>
</ul>
<p>The last component - WX - raises the question. I can put together a very nice looking app (the prototypes look slick) - but when I need to interact with the user to ask questions, get input, I have to use WX. It makes the app look inconsistent to have traditional UI with traditional dialogs and combos and text entry on top of a full screen 3D app with blending, smooth motion, textures etc.</p>
<p>Has anyone developed a GUI using OpenGL and python? Can you share with me the toolkits and/or tricks you used? I need combos, text entry, buttons, radios, option buttons, tree view.</p>
<p>There are some toolkits out there, but they are either incomplete or old and unmaintained. A great example is pyUI (http://pyui.sourceforge.net/) - looks slick but untouched for years.</p>
| 1 | 2008-09-16T23:11:31Z | 7,697,287 | <p>Blender is the only app I know of with a GUI written fully in OpenGL...
the only problem is it's in C++.</p>
<p>I'm a Python developer as well, but I'm just getting into using OGL</p>
<p>I honestly don't think there are any toolkits to develop a GUI in OGL...</p>
<p>the Blender developers are giving me runaround documentation instead of direct help...
but I'll let you know what I figure out ;)</p>
<p>EDIT:
here's a bit of documentation on PyOpenGL's functions:
<a href="http://pyopengl.sourceforge.net/documentation/manual/reference-GLUT.html" rel="nofollow">http://pyopengl.sourceforge.net/documentation/manual/reference-GLUT.html</a></p>
| 1 | 2011-10-08T13:59:37Z | [
"python",
"user-interface",
"opengl"
] |
OPENGL User Interface Programming | 78,238 | <p>I'm developing a graphical application to present data (not a game but a real workhorse app). It needs to be cross platform, so I have chosen:</p>
<ul>
<li>python</li>
<li>openGL (I need 3D, blending, textures etc)</li>
<li>pyopengl</li>
<li>wx/pywx - windowing, dialogs etc.</li>
</ul>
<p>The last component - WX - raises the question. I can put together a very nice looking app (the prototypes look slick) - but when I need to interact with the user to ask questions, get input, I have to use WX. It makes the app look inconsistent to have traditional UI with traditional dialogs and combos and text entry on top of a full screen 3D app with blending, smooth motion, textures etc.</p>
<p>Has anyone developed a GUI using OpenGL and python? Can you share with me the toolkits and/or tricks you used? I need combos, text entry, buttons, radios, option buttons, tree view.</p>
<p>There are some toolkits out there, but they are either incomplete or old and unmaintained. A great example is pyUI (http://pyui.sourceforge.net/) - looks slick but untouched for years.</p>
| 1 | 2008-09-16T23:11:31Z | 7,697,572 | <p>my friend.<br>
I believe I have found your answer ;)<br>
<a href="http://glinter.sourceforge.net/" rel="nofollow">http://glinter.sourceforge.net/</a></p>
<p>I havn't yet tried it, but it seems quite promising.
(I'll edit this if it doesn't work)</p>
<p>EDIT:<br>
eh...<br>
it uses Tk, PMW, and WX...<br>
(not quite what I want)</p>
<p>you can give the CVS download a try...<br>
(there's no released packages, but the CVS runs)</p>
| -1 | 2011-10-08T14:50:03Z | [
"python",
"user-interface",
"opengl"
] |
OPENGL User Interface Programming | 78,238 | <p>I'm developing a graphical application to present data (not a game but a real workhorse app). It needs to be cross platform, so I have chosen:</p>
<ul>
<li>python</li>
<li>openGL (I need 3D, blending, textures etc)</li>
<li>pyopengl</li>
<li>wx/pywx - windowing, dialogs etc.</li>
</ul>
<p>The last component - WX - raises the question. I can put together a very nice looking app (the prototypes look slick) - but when I need to interact with the user to ask questions, get input, I have to use WX. It makes the app look inconsistent to have traditional UI with traditional dialogs and combos and text entry on top of a full screen 3D app with blending, smooth motion, textures etc.</p>
<p>Has anyone developed a GUI using OpenGL and python? Can you share with me the toolkits and/or tricks you used? I need combos, text entry, buttons, radios, option buttons, tree view.</p>
<p>There are some toolkits out there, but they are either incomplete or old and unmaintained. A great example is pyUI (http://pyui.sourceforge.net/) - looks slick but untouched for years.</p>
| 1 | 2008-09-16T23:11:31Z | 26,485,404 | <p>"<a href="http://cegui.org.uk" rel="nofollow">cegui</a>" is a good choise there is also a gui editor called "ceed" to generate the layout xml files. cegui also has python bindings and its well documented and used in many game engines</p>
| 0 | 2014-10-21T11:18:49Z | [
"python",
"user-interface",
"opengl"
] |
Redirect command to input of another in Python | 78,431 | <p>I would like to replicate this in python:</p>
<pre><code>gvimdiff <(hg cat file.txt) file.txt
</code></pre>
<p>(hg cat file.txt outputs the most recently committed version of file.txt)</p>
<p>I know how to pipe the file to gvimdiff, but it won't accept another file:</p>
<pre><code>$ hg cat file.txt | gvimdiff file.txt -
Too many edit arguments: "-"
</code></pre>
<p>Getting to the python part...</p>
<pre><code># hgdiff.py
import subprocess
import sys
file = sys.argv[1]
subprocess.call(["gvimdiff", "<(hg cat %s)" % file, file])
</code></pre>
<p>When subprocess is called it merely passes <code><(hg cat file)</code> onto <code>gvimdiff</code> as a filename.</p>
<p>So, is there any way to redirect a command as bash does?
For simplicity's sake just cat a file and redirect it to diff:</p>
<pre><code>diff <(cat file.txt) file.txt
</code></pre>
| 5 | 2008-09-16T23:46:47Z | 78,459 | <p>There is also the commands module:</p>
<pre><code>import commands
status, output = commands.getstatusoutput("gvimdiff <(hg cat file.txt) file.txt")
</code></pre>
<p>There is also the popen set of functions, if you want to actually grok the data from a command as it is running.</p>
| 2 | 2008-09-16T23:53:40Z | [
"python",
"bash",
"redirect",
"diff",
"vimdiff"
] |
Redirect command to input of another in Python | 78,431 | <p>I would like to replicate this in python:</p>
<pre><code>gvimdiff <(hg cat file.txt) file.txt
</code></pre>
<p>(hg cat file.txt outputs the most recently committed version of file.txt)</p>
<p>I know how to pipe the file to gvimdiff, but it won't accept another file:</p>
<pre><code>$ hg cat file.txt | gvimdiff file.txt -
Too many edit arguments: "-"
</code></pre>
<p>Getting to the python part...</p>
<pre><code># hgdiff.py
import subprocess
import sys
file = sys.argv[1]
subprocess.call(["gvimdiff", "<(hg cat %s)" % file, file])
</code></pre>
<p>When subprocess is called it merely passes <code><(hg cat file)</code> onto <code>gvimdiff</code> as a filename.</p>
<p>So, is there any way to redirect a command as bash does?
For simplicity's sake just cat a file and redirect it to diff:</p>
<pre><code>diff <(cat file.txt) file.txt
</code></pre>
| 5 | 2008-09-16T23:46:47Z | 78,481 | <p>It just dawned on me that you are probably looking for one of the popen functions.</p>
<p>from: <a href="http://docs.python.org/lib/module-popen2.html" rel="nofollow">http://docs.python.org/lib/module-popen2.html</a></p>
<p>popen3(cmd[, bufsize[, mode]])
Executes cmd as a sub-process. Returns the file objects (child_stdout, child_stdin, child_stderr). </p>
<p>namaste,
Mark</p>
| -1 | 2008-09-16T23:57:24Z | [
"python",
"bash",
"redirect",
"diff",
"vimdiff"
] |
Redirect command to input of another in Python | 78,431 | <p>I would like to replicate this in python:</p>
<pre><code>gvimdiff <(hg cat file.txt) file.txt
</code></pre>
<p>(hg cat file.txt outputs the most recently committed version of file.txt)</p>
<p>I know how to pipe the file to gvimdiff, but it won't accept another file:</p>
<pre><code>$ hg cat file.txt | gvimdiff file.txt -
Too many edit arguments: "-"
</code></pre>
<p>Getting to the python part...</p>
<pre><code># hgdiff.py
import subprocess
import sys
file = sys.argv[1]
subprocess.call(["gvimdiff", "<(hg cat %s)" % file, file])
</code></pre>
<p>When subprocess is called it merely passes <code><(hg cat file)</code> onto <code>gvimdiff</code> as a filename.</p>
<p>So, is there any way to redirect a command as bash does?
For simplicity's sake just cat a file and redirect it to diff:</p>
<pre><code>diff <(cat file.txt) file.txt
</code></pre>
| 5 | 2008-09-16T23:46:47Z | 78,482 | <p>It can be done. As of Python 2.5, however, this mechanism is Linux-specific and not portable:</p>
<pre><code>import subprocess
import sys
file = sys.argv[1]
p1 = subprocess.Popen(['hg', 'cat', file], stdout=subprocess.PIPE)
p2 = subprocess.Popen([
'gvimdiff',
'/proc/self/fd/%s' % p1.stdout.fileno(),
file])
p2.wait()
</code></pre>
<p>That said, in the specific case of diff, you can simply take one of the files from stdin, and remove the need to use the bash-alike functionality in question:</p>
<pre><code>file = sys.argv[1]
p1 = subprocess.Popen(['hg', 'cat', file], stdout=subprocess.PIPE)
p2 = subprocess.Popen(['diff', '-', file], stdin=p1.stdout)
diff_text = p2.communicate()[0]
</code></pre>
| 8 | 2008-09-16T23:57:32Z | [
"python",
"bash",
"redirect",
"diff",
"vimdiff"
] |
Redirect command to input of another in Python | 78,431 | <p>I would like to replicate this in python:</p>
<pre><code>gvimdiff <(hg cat file.txt) file.txt
</code></pre>
<p>(hg cat file.txt outputs the most recently committed version of file.txt)</p>
<p>I know how to pipe the file to gvimdiff, but it won't accept another file:</p>
<pre><code>$ hg cat file.txt | gvimdiff file.txt -
Too many edit arguments: "-"
</code></pre>
<p>Getting to the python part...</p>
<pre><code># hgdiff.py
import subprocess
import sys
file = sys.argv[1]
subprocess.call(["gvimdiff", "<(hg cat %s)" % file, file])
</code></pre>
<p>When subprocess is called it merely passes <code><(hg cat file)</code> onto <code>gvimdiff</code> as a filename.</p>
<p>So, is there any way to redirect a command as bash does?
For simplicity's sake just cat a file and redirect it to diff:</p>
<pre><code>diff <(cat file.txt) file.txt
</code></pre>
| 5 | 2008-09-16T23:46:47Z | 78,923 | <p>This is actually an example in the <a href="https://docs.python.org/2.4/lib/node242.html" rel="nofollow">docs</a>:</p>
<pre><code>p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]
</code></pre>
<p>which means for you:</p>
<pre><code>import subprocess
import sys
file = sys.argv[1]
p1 = Popen(["hg", "cat", file], stdout=PIPE)
p2 = Popen(["gvimdiff", "file.txt"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]
</code></pre>
<p>This removes the use of the linux-specific /proc/self/fd bits, making it probably work on other unices like Solaris and the BSDs (including MacOS) and maybe even work on Windows.</p>
| 2 | 2008-09-17T01:26:43Z | [
"python",
"bash",
"redirect",
"diff",
"vimdiff"
] |
Python ReportLab use of splitfirst/splitlast | 78,450 | <p>I'm trying to use Python with ReportLab 2.2 to create a PDF report.<br />
According to the <a href="http://www.reportlab.com/docs/userguide.pdf">user guide</a>,</p>
<blockquote>
<p>Special TableStyle Indeces [sic]</p>
<p>In any style command the first row index may be set to one of the special strings 'splitlast' or 'splitfirst' to indicate that the style should be used only for the last row of a split table, or the first row of a continuation. This allows splitting tables with nicer effects around the split.</p>
</blockquote>
<p>I've tried using several style elements, including:</p>
<pre><code>('TEXTCOLOR', (0, 'splitfirst'), (1, 'splitfirst'), colors.black)
('TEXTCOLOR', (0, 'splitfirst'), (1, 0), colors.black)
('TEXTCOLOR', (0, 'splitfirst'), (1, -1), colors.black)
</code></pre>
<p>and none of these seems to work. The first generates a TypeError with the message: </p>
<pre><code>TypeError: cannot concatenate 'str' and 'int' objects
</code></pre>
<p>and the latter two generate TypeErrors with the message:</p>
<pre><code>TypeError: an integer is required
</code></pre>
<p>Is this functionality simply broken or am I doing something wrong? If the latter, what am I doing wrong?</p>
| 6 | 2008-09-16T23:52:04Z | 78,702 | <blockquote>
<p>[...] In any style command <strong>the first row
index</strong> may be set to one of the special strings [...]</p>
</blockquote>
<p>In your first example you're setting the <em>second</em> row index to a special string as well.</p>
<p>Not sure why the other two don't work... Are you sure this is where the exception is coming from?</p>
| 0 | 2008-09-17T00:40:54Z | [
"python",
"reportlab"
] |
Python ReportLab use of splitfirst/splitlast | 78,450 | <p>I'm trying to use Python with ReportLab 2.2 to create a PDF report.<br />
According to the <a href="http://www.reportlab.com/docs/userguide.pdf">user guide</a>,</p>
<blockquote>
<p>Special TableStyle Indeces [sic]</p>
<p>In any style command the first row index may be set to one of the special strings 'splitlast' or 'splitfirst' to indicate that the style should be used only for the last row of a split table, or the first row of a continuation. This allows splitting tables with nicer effects around the split.</p>
</blockquote>
<p>I've tried using several style elements, including:</p>
<pre><code>('TEXTCOLOR', (0, 'splitfirst'), (1, 'splitfirst'), colors.black)
('TEXTCOLOR', (0, 'splitfirst'), (1, 0), colors.black)
('TEXTCOLOR', (0, 'splitfirst'), (1, -1), colors.black)
</code></pre>
<p>and none of these seems to work. The first generates a TypeError with the message: </p>
<pre><code>TypeError: cannot concatenate 'str' and 'int' objects
</code></pre>
<p>and the latter two generate TypeErrors with the message:</p>
<pre><code>TypeError: an integer is required
</code></pre>
<p>Is this functionality simply broken or am I doing something wrong? If the latter, what am I doing wrong?</p>
| 6 | 2008-09-16T23:52:04Z | 94,869 | <p>Well, it looks as if I will be answering my own question.</p>
<p>First, the documentation flat out lies where it reads "In any style command the first row index may be set to one of the special strings 'splitlast' or 'splitfirst' to indicate that the style should be used only for the last row of a split table, or the first row of a continuation." In the current release, the "splitlast" and "splitfirst" row indices break with the aforementioned TypeErrors on the TEXTCOLOR and BACKGROUND commnds.</p>
<p>My suspicion, based on reading the source code, is that only the tablestyle line commands (GRID, BOX, LINEABOVE, and LINEBELOW) are currently compatible with the 'splitfirst' and 'splitlast' row indices. I suspect that all cell commands break with the aforementioned TypeErrors.</p>
<p>However, I was able to do what I wanted by subclassing the Table class and overriding the onSplit method. Here is my code:</p>
<pre><code>class XTable(Table):
def onSplit(self, T, byRow=1):
T.setStyle(TableStyle([
('TEXTCOLOR', (0, 1), (1, 1), colors.black)]))
</code></pre>
<p>What this does is apply the text color black to the first and second cell of the second row of each page. (The first row is a header, repeated by the repeatRows parameter of the Table.) More precisely, it is doing this to the first and second cell of each frame, but since I am using the SimpleDocTemplate, frames and pages are identical.</p>
| 2 | 2008-09-18T17:46:36Z | [
"python",
"reportlab"
] |
Python ReportLab use of splitfirst/splitlast | 78,450 | <p>I'm trying to use Python with ReportLab 2.2 to create a PDF report.<br />
According to the <a href="http://www.reportlab.com/docs/userguide.pdf">user guide</a>,</p>
<blockquote>
<p>Special TableStyle Indeces [sic]</p>
<p>In any style command the first row index may be set to one of the special strings 'splitlast' or 'splitfirst' to indicate that the style should be used only for the last row of a split table, or the first row of a continuation. This allows splitting tables with nicer effects around the split.</p>
</blockquote>
<p>I've tried using several style elements, including:</p>
<pre><code>('TEXTCOLOR', (0, 'splitfirst'), (1, 'splitfirst'), colors.black)
('TEXTCOLOR', (0, 'splitfirst'), (1, 0), colors.black)
('TEXTCOLOR', (0, 'splitfirst'), (1, -1), colors.black)
</code></pre>
<p>and none of these seems to work. The first generates a TypeError with the message: </p>
<pre><code>TypeError: cannot concatenate 'str' and 'int' objects
</code></pre>
<p>and the latter two generate TypeErrors with the message:</p>
<pre><code>TypeError: an integer is required
</code></pre>
<p>Is this functionality simply broken or am I doing something wrong? If the latter, what am I doing wrong?</p>
| 6 | 2008-09-16T23:52:04Z | 2,623,783 | <p>This seems to be a bug in the ReportLab Table class. Another fix for this in addition to <a href="http://stackoverflow.com/a/94869/669202">DLJessup's own answer</a> is to modify the ReportLab code that's causing the error, in <code>Table._drawBkgrnd()</code>, around line 1301. For 'splitlast', change:</p>
<pre><code>y0 = rowpositions[sr]
</code></pre>
<p>to: </p>
<pre><code>if sr == 'splitlast':
y0 = rowpositions[-2] # last value is 0. Second last is the one we want.
else:
y0 = rowpositions[sr]
</code></pre>
<p>This is easily done in your own code without hacking ReportLab by subclassing Table and overwriting this method. I've not had need to use 'splitfirst'; if I do I'll post the rest of the hack here.</p>
| 1 | 2010-04-12T16:52:07Z | [
"python",
"reportlab"
] |
Is there a benefit to defining a class inside another class in Python? | 78,799 | <p>What I'm talking about here are nested classes. Essentially, I have two classes that I'm modeling. A DownloadManager class and a DownloadThread class. The obvious OOP concept here is composition. However, composition doesn't necessarily mean nesting, right?</p>
<p>I have code that looks something like this:</p>
<pre><code>class DownloadThread:
def foo(self):
pass
class DownloadManager():
def __init__(self):
dwld_threads = []
def create_new_thread():
dwld_threads.append(DownloadThread())
</code></pre>
<p>But now I'm wondering if there's a situation where nesting would be better. Something like:</p>
<pre><code>class DownloadManager():
class DownloadThread:
def foo(self):
pass
def __init__(self):
dwld_threads = []
def create_new_thread():
dwld_threads.append(DownloadManager.DownloadThread())
</code></pre>
| 54 | 2008-09-17T01:02:31Z | 78,855 | <p>No, composition does not mean nesting.
It would make sense to have a nested class if you want to hide it more in the namespace of the outer class.</p>
<p>Anyway, I don't see any practical use for nesting in your case. It would make the code harder to read (understand) and it would also increase the indentation which would make the lines shorter and more prone to splitting.</p>
| 1 | 2008-09-17T01:11:41Z | [
"python",
"oop"
] |
Is there a benefit to defining a class inside another class in Python? | 78,799 | <p>What I'm talking about here are nested classes. Essentially, I have two classes that I'm modeling. A DownloadManager class and a DownloadThread class. The obvious OOP concept here is composition. However, composition doesn't necessarily mean nesting, right?</p>
<p>I have code that looks something like this:</p>
<pre><code>class DownloadThread:
def foo(self):
pass
class DownloadManager():
def __init__(self):
dwld_threads = []
def create_new_thread():
dwld_threads.append(DownloadThread())
</code></pre>
<p>But now I'm wondering if there's a situation where nesting would be better. Something like:</p>
<pre><code>class DownloadManager():
class DownloadThread:
def foo(self):
pass
def __init__(self):
dwld_threads = []
def create_new_thread():
dwld_threads.append(DownloadManager.DownloadThread())
</code></pre>
| 54 | 2008-09-17T01:02:31Z | 78,858 | <p>You might want to do this when the "inner" class is a one-off, which will never be used outside the <em>definition</em> of the outer class. For example to use a metaclass, it's sometimes handy to do</p>
<pre><code>class Foo(object):
class __metaclass__(type):
....
</code></pre>
<p>instead of defining a metaclass separately, if you're only using it once.</p>
<p>The only other time I've used nested classes like that, I used the outer class only as a namespace to group a bunch of closely related classes together:</p>
<pre><code>class Group(object):
class cls1(object):
...
class cls2(object):
...
</code></pre>
<p>Then from another module, you can import Group and refer to these as Group.cls1, Group.cls2 etc. However one might argue that you can accomplish exactly the same (perhaps in a less confusing way) by using a module.</p>
| 72 | 2008-09-17T01:12:59Z | [
"python",
"oop"
] |
Is there a benefit to defining a class inside another class in Python? | 78,799 | <p>What I'm talking about here are nested classes. Essentially, I have two classes that I'm modeling. A DownloadManager class and a DownloadThread class. The obvious OOP concept here is composition. However, composition doesn't necessarily mean nesting, right?</p>
<p>I have code that looks something like this:</p>
<pre><code>class DownloadThread:
def foo(self):
pass
class DownloadManager():
def __init__(self):
dwld_threads = []
def create_new_thread():
dwld_threads.append(DownloadThread())
</code></pre>
<p>But now I'm wondering if there's a situation where nesting would be better. Something like:</p>
<pre><code>class DownloadManager():
class DownloadThread:
def foo(self):
pass
def __init__(self):
dwld_threads = []
def create_new_thread():
dwld_threads.append(DownloadManager.DownloadThread())
</code></pre>
| 54 | 2008-09-17T01:02:31Z | 78,868 | <p>I don't know Python, but your question seems very general. Ignore me if it's specific to Python.</p>
<p>Class nesting is all about scope. If you think that one class will only make sense in the context of another one, then the former is probably a good candidate to become a nested class.</p>
<p>It is a common pattern make helper classes as private, nested classes.</p>
| 14 | 2008-09-17T01:14:33Z | [
"python",
"oop"
] |
Is there a benefit to defining a class inside another class in Python? | 78,799 | <p>What I'm talking about here are nested classes. Essentially, I have two classes that I'm modeling. A DownloadManager class and a DownloadThread class. The obvious OOP concept here is composition. However, composition doesn't necessarily mean nesting, right?</p>
<p>I have code that looks something like this:</p>
<pre><code>class DownloadThread:
def foo(self):
pass
class DownloadManager():
def __init__(self):
dwld_threads = []
def create_new_thread():
dwld_threads.append(DownloadThread())
</code></pre>
<p>But now I'm wondering if there's a situation where nesting would be better. Something like:</p>
<pre><code>class DownloadManager():
class DownloadThread:
def foo(self):
pass
def __init__(self):
dwld_threads = []
def create_new_thread():
dwld_threads.append(DownloadManager.DownloadThread())
</code></pre>
| 54 | 2008-09-17T01:02:31Z | 78,968 | <p>You could be using a class as class generator. Like (in some off the cuff code :)</p>
<pre><code>class gen(object):
class base_1(object): pass
...
class base_n(object): pass
def __init__(self, ...):
...
def mk_cls(self, ..., type):
'''makes a class based on the type passed in, the current state of
the class, and the other inputs to the method'''
</code></pre>
<p>I feel like when you need this functionality it will be very clear to you. If you don't need to be doing something similar than it probably isn't a good use case.</p>
| 2 | 2008-09-17T01:34:41Z | [
"python",
"oop"
] |
Is there a benefit to defining a class inside another class in Python? | 78,799 | <p>What I'm talking about here are nested classes. Essentially, I have two classes that I'm modeling. A DownloadManager class and a DownloadThread class. The obvious OOP concept here is composition. However, composition doesn't necessarily mean nesting, right?</p>
<p>I have code that looks something like this:</p>
<pre><code>class DownloadThread:
def foo(self):
pass
class DownloadManager():
def __init__(self):
dwld_threads = []
def create_new_thread():
dwld_threads.append(DownloadThread())
</code></pre>
<p>But now I'm wondering if there's a situation where nesting would be better. Something like:</p>
<pre><code>class DownloadManager():
class DownloadThread:
def foo(self):
pass
def __init__(self):
dwld_threads = []
def create_new_thread():
dwld_threads.append(DownloadManager.DownloadThread())
</code></pre>
| 54 | 2008-09-17T01:02:31Z | 79,094 | <p>There is really no benefit to doing this, except if you are dealing with metaclasses.</p>
<p>the class: suite really isn't what you think it is. It is a weird scope, and it does strange things. It really doesn't even make a class! It is just a way of collecting some variables - the name of the class, the bases, a little dictionary of attributes, and a metaclass.</p>
<p>The name, the dictionary and the bases are all passed to the function that is the metaclass, and then it is assigned to the variable 'name' in the scope where the class: suite was.</p>
<p>What you can gain by messing with metaclasses, and indeed by nesting classes within your stock standard classes, is harder to read code, harder to understand code, and odd errors that are terribly difficult to understand without being intimately familiar with why the 'class' scope is entirely different to any other python scope.</p>
| 4 | 2008-09-17T01:52:55Z | [
"python",
"oop"
] |
How to check for memory leaks in Guile extension modules? | 78,900 | <p>I develop an extension module for Guile, written in C. This extension module embeds a Python interpreter.</p>
<p>Since this extension module invokes the Python interpreter, I need to verify that it properly manages the memory occupied by Python objects. </p>
<p>I found that the Python interpreter is well-behaved in its own memory handling, so that by running valgrind I can find memory leaks due to bugs in my own Python interpreter embedding code, if there are no other interfering factors. </p>
<p>However, when I run Guile under valgrind, valgrind reports memory leaks. Such memory leaks obscure any memory leaks due to my own code. </p>
<p>The question is what can I do to separate memory leaks due to bugs in my code from memory leaks reported by valgrind as due to Guile. Another tool instead of valgrind? Special valgrind options? Give up and rely upon manual code walkthrough?</p>
| 3 | 2008-09-17T01:22:56Z | 78,990 | <p>You've got a couple options. One is to write a supressions file for valgrind that turns off reporting of stuff that you're not working on. Python has such a file, for example:
<a href="http://svn.python.org/projects/python/trunk/Misc/valgrind-python.supp" rel="nofollow">http://svn.python.org/projects/python/trunk/Misc/valgrind-python.supp</a></p>
<p>If valgrind doesn't like your setup, another possibility is using <code>libmudflap</code>; you compile your program with <code>gcc -fmudflap -lmudflap</code>, and the resulting code is instrumented for pointer debugging. Described in the gcc docs, and here: <a href="http://gcc.gnu.org/wiki/Mudflap_Pointer_Debugging" rel="nofollow">http://gcc.gnu.org/wiki/Mudflap_Pointer_Debugging</a></p>
| 4 | 2008-09-17T01:38:24Z | [
"python",
"memory-leaks",
"valgrind",
"guile"
] |
Testing GUI code: should I use a mocking library? | 79,454 | <p>Recently I've been experimenting with TDD while developing a GUI application in Python. I find it very reassuring to have tests that verify the functionality of my code, but it's been tricky to follow some of the recommened practices of TDD. Namely, writing tests first has been hard. And I'm finding it difficult to make my tests readable (due to extensive use of a mocking library).</p>
<p>I chose a mocking library called <a href="http://labix.org/mocker" rel="nofollow">mocker</a>. I use it a lot since much of the code I'm testing makes calls to (a) other methods in my application that depend on system state or (b) ObjC/Cocoa objects that cannot exist without an event loop, etc.</p>
<p>Anyway, I've got a lot of tests that look like this:</p>
<pre><code>def test_current_window_controller():
def test(config):
ac = AppController()
m = Mocker()
ac.iter_window_controllers = iwc = m.replace(ac.iter_window_controllers)
expect(iwc()).result(iter(config))
with m:
result = ac.current_window_controller()
assert result == (config[0] if config else None)
yield test, []
yield test, [0]
yield test, [1, 0]
</code></pre>
<p>Notice that this is actually three tests; all use the same parameterized test function. Here's the code that is being tested:</p>
<pre><code>def current_window_controller(self):
try:
# iter_window_controllers() iterates in z-order starting
# with the controller of the top-most window
# assumption: the top-most window is the "current" one
wc = self.iter_window_controllers().next()
except StopIteration:
return None
return wc
</code></pre>
<p>One of the things I've noticed with using mocker is that it's easier to write the application code first and then go back and write the tests second, since most of the time I'm mocking many method calls and the syntax to write the mocked calls is much more verbose (thus harder to write) than the application code. It's easier to write the app code and then model the test code off of that.</p>
<p>I find that with this testing method (and a bit of discipline) I can easily write code with 100% test coverage.</p>
<p>I'm wondering if these tests are good tests? Will I regret doing it this way down the road when I finally discover the secret to writing good tests?</p>
<p>Am I violating the core principles of TDD so much that my testing is in vain?</p>
| 5 | 2008-09-17T02:52:58Z | 79,667 | <p>Unit tests are really useful when you refactor your code (ie. completely rewrite or move a module). As long as you have unit tests before you do the big changes, you'll have confidence that you havent forgotten to move or include something when you finish.</p>
| -2 | 2008-09-17T03:30:19Z | [
"python",
"unit-testing",
"user-interface",
"tdd"
] |
Testing GUI code: should I use a mocking library? | 79,454 | <p>Recently I've been experimenting with TDD while developing a GUI application in Python. I find it very reassuring to have tests that verify the functionality of my code, but it's been tricky to follow some of the recommened practices of TDD. Namely, writing tests first has been hard. And I'm finding it difficult to make my tests readable (due to extensive use of a mocking library).</p>
<p>I chose a mocking library called <a href="http://labix.org/mocker" rel="nofollow">mocker</a>. I use it a lot since much of the code I'm testing makes calls to (a) other methods in my application that depend on system state or (b) ObjC/Cocoa objects that cannot exist without an event loop, etc.</p>
<p>Anyway, I've got a lot of tests that look like this:</p>
<pre><code>def test_current_window_controller():
def test(config):
ac = AppController()
m = Mocker()
ac.iter_window_controllers = iwc = m.replace(ac.iter_window_controllers)
expect(iwc()).result(iter(config))
with m:
result = ac.current_window_controller()
assert result == (config[0] if config else None)
yield test, []
yield test, [0]
yield test, [1, 0]
</code></pre>
<p>Notice that this is actually three tests; all use the same parameterized test function. Here's the code that is being tested:</p>
<pre><code>def current_window_controller(self):
try:
# iter_window_controllers() iterates in z-order starting
# with the controller of the top-most window
# assumption: the top-most window is the "current" one
wc = self.iter_window_controllers().next()
except StopIteration:
return None
return wc
</code></pre>
<p>One of the things I've noticed with using mocker is that it's easier to write the application code first and then go back and write the tests second, since most of the time I'm mocking many method calls and the syntax to write the mocked calls is much more verbose (thus harder to write) than the application code. It's easier to write the app code and then model the test code off of that.</p>
<p>I find that with this testing method (and a bit of discipline) I can easily write code with 100% test coverage.</p>
<p>I'm wondering if these tests are good tests? Will I regret doing it this way down the road when I finally discover the secret to writing good tests?</p>
<p>Am I violating the core principles of TDD so much that my testing is in vain?</p>
| 5 | 2008-09-17T02:52:58Z | 80,028 | <p><strong>If you are writing your tests after you've written your code and making them pass, you are not doing TDD</strong> (nor are you getting any benefits of Test-First or Test-Driven development.. check out SO questions for definitive books on TDD)</p>
<blockquote>
<p>One of the things I've noticed with
using mocker is that it's easier to
write the application code first and
then go back and write the tests
second, since most of the time I'm
mocking many method calls and the
syntax to write the mocked calls is
much more verbose (thus harder to
write) than the application code. It's
easier to write the app code and then
model the test code off of that.</p>
</blockquote>
<p>Of course, its easier because you are just testing that the sky is orange after you made it orange by painting it with a specific kind of brush.
This is retrofitting tests (for self-assurance). Mocks are good but you should know how and when to use them - Like the saying goes 'When you have a hammer everything looks like a nail' It's also easy to write a whole load of unreadable and not-as-helpful-as-can-be tests. The time spent understanding what the test is about is time lost that can be used to fix broken ones. </p>
<p>And the point is: </p>
<ul>
<li>Read <a href="http://martinfowler.com/articles/mocksArentStubs.html#ClassicalAndMockistTesting">Mocks aren't stubs - Martin Fowler</a> if you haven't already. Google out some documented instances of good <a href="http://martinfowler.com/eaaDev/ModelViewPresenter.html">ModelViewPresenter</a> patterned GUIs (Fake/Mock out the UIs if necessary). </li>
<li>Study your options and choose wisely. I'll play the guy with the halo on your left shoulder in white saying 'Don't do it.' Read this question as to <a href="http://stackoverflow.com/questions/59195/how-are-mocks-meant-to-be-used">my reasons</a> - St. Justin is on your right shoulder. I believe he has also something to say:) </li>
</ul>
| 7 | 2008-09-17T04:33:46Z | [
"python",
"unit-testing",
"user-interface",
"tdd"
] |
Testing GUI code: should I use a mocking library? | 79,454 | <p>Recently I've been experimenting with TDD while developing a GUI application in Python. I find it very reassuring to have tests that verify the functionality of my code, but it's been tricky to follow some of the recommened practices of TDD. Namely, writing tests first has been hard. And I'm finding it difficult to make my tests readable (due to extensive use of a mocking library).</p>
<p>I chose a mocking library called <a href="http://labix.org/mocker" rel="nofollow">mocker</a>. I use it a lot since much of the code I'm testing makes calls to (a) other methods in my application that depend on system state or (b) ObjC/Cocoa objects that cannot exist without an event loop, etc.</p>
<p>Anyway, I've got a lot of tests that look like this:</p>
<pre><code>def test_current_window_controller():
def test(config):
ac = AppController()
m = Mocker()
ac.iter_window_controllers = iwc = m.replace(ac.iter_window_controllers)
expect(iwc()).result(iter(config))
with m:
result = ac.current_window_controller()
assert result == (config[0] if config else None)
yield test, []
yield test, [0]
yield test, [1, 0]
</code></pre>
<p>Notice that this is actually three tests; all use the same parameterized test function. Here's the code that is being tested:</p>
<pre><code>def current_window_controller(self):
try:
# iter_window_controllers() iterates in z-order starting
# with the controller of the top-most window
# assumption: the top-most window is the "current" one
wc = self.iter_window_controllers().next()
except StopIteration:
return None
return wc
</code></pre>
<p>One of the things I've noticed with using mocker is that it's easier to write the application code first and then go back and write the tests second, since most of the time I'm mocking many method calls and the syntax to write the mocked calls is much more verbose (thus harder to write) than the application code. It's easier to write the app code and then model the test code off of that.</p>
<p>I find that with this testing method (and a bit of discipline) I can easily write code with 100% test coverage.</p>
<p>I'm wondering if these tests are good tests? Will I regret doing it this way down the road when I finally discover the secret to writing good tests?</p>
<p>Am I violating the core principles of TDD so much that my testing is in vain?</p>
| 5 | 2008-09-17T02:52:58Z | 82,049 | <p><strong>Please remember that TDD is not a panaceum.</strong> It's hard, it's supposed to be hard, and it's especially hard to write mocking tests "in advance".</p>
<p>So I would say - do what works for you. Even it's not "certified TDD". I do basically the same thing.</p>
<p>You may want to provide your own API for GUI that would sit between controller code and GUI library code. That could be easier to mock, or you can even add some testing hooks to it.</p>
<p>Last but not least, your code doesn't look too unreadable to me. Code using mocks is generally harder to understand. Fortunately in Python mocking is much easier and cleaner than i n other languages.</p>
| -3 | 2008-09-17T11:08:17Z | [
"python",
"unit-testing",
"user-interface",
"tdd"
] |
How do I get started processing email related to website activity? | 79,602 | <p>I am writing a web application that requires user interaction via email. I'm curious if there is a best practice or recommended source for learning about processing email. I am writing my application in Python, but I'm not sure what mail server to use or how to format the message or subject line to account for automated processing. I'm also looking for guidance on processing bouncebacks. </p>
<p>Thanks!</p>
| 1 | 2008-09-17T03:19:29Z | 79,670 | <p>There are some pretty serious concerns here for how to send email automatically, and here are a few:</p>
<p>Use an email library. Python includes one called 'email'. This is your friend, it will stop you from doing anything tragically wrong. Read an example from <a href="http://docs.python.org/lib/node161.html" rel="nofollow">the Python Manual</a>.</p>
<p>Some points that will stop you from getting blocked by spam filters:</p>
<p>Always send from a valid email address. You must be able to send email to this address and have it received (it can go into /dev/null after it's received, but it must be possible to /deliver/ there). This will stop spam filters that do Sender Address Verification from blocking your mail.</p>
<p>The email address you send from on the server.sendmail(fromaddr, [toaddr]) line will be where bounces go. The From: line in the email is a totally different address, and that's where mail will go when the user hits 'Reply:'. Use this to your advantage, bounces can go to one place, while reply goes to another.</p>
<p>Send email to a local mail server, I recommend postfix. This local server will receive your mail and be responsible for sending it to your upstream server. Once it has been delivered to the local server, treat it as 'sent' from a programmatic point of view.</p>
<p>If you have a site that is on a static ip in a datacenter of good reputation, don't be afraid to simply relay the mail directly to the internet. If you're in a datacenter full of script kiddies and spammers, you will need to relay this mail via a public MTA of good reputation, hopefully you will be able to work this out without a hassle.</p>
<p>Don't send an email in only HTML. Always send it in Plain and HTML, or just Plain. Be nice, I use a text only email client, and you don't want to annoy me.</p>
<p>Verify that you're not running SPF on your email domain, or get it configured to allow your server to send the mail. Do this by doing a TXT lookup on your domain.</p>
<pre><code>$ dig google.com txt
...snip...
;; ANSWER SECTION:
google.com. 300 IN TXT "v=spf1 include:_netblocks.google.com ~all"
</code></pre>
<p>As you can see from that result, there's an SPF record there. If you don't have SPF, there won't be a TXT record. Read more about <a href="http://en.wikipedia.org/wiki/Sender_Policy_Framework" rel="nofollow">SPF on wikipedia</a>.</p>
<p>Hope that helps.</p>
| 3 | 2008-09-17T03:31:07Z | [
"python",
"email"
] |
How do I get started processing email related to website activity? | 79,602 | <p>I am writing a web application that requires user interaction via email. I'm curious if there is a best practice or recommended source for learning about processing email. I am writing my application in Python, but I'm not sure what mail server to use or how to format the message or subject line to account for automated processing. I'm also looking for guidance on processing bouncebacks. </p>
<p>Thanks!</p>
| 1 | 2008-09-17T03:19:29Z | 79,743 | <p>Some general information with regards to automated mail processing...</p>
<p>First, the mail server "brand" itself isn't that important for broadcasting or receiving emails. All of them support the standard smtp / pop3 communications protocol. Most even have IMAP support and have some level of spam filtering. That said, try to use a current generation email server.</p>
<p>Second, be aware that in an effort to reduce spam a lot of the receiving mail servers out there will simply throw a message away instead of responding back that a mail account doesn't exist. Which means you may not receive those.</p>
<p>Bear in mind that getting past spam filters is an art. A number of isp's watch for duplicate messages, messages that <em>look</em> like spam based on keywords or other content, etc. This is sometimes independent of the quantity of messages sent; I've seen messages with as few as 50 copies get blocked by AOL even though they were legitimate emails. So, testing is your friend and look into <a href="http://en.wikipedia.org/wiki/Anti-spam_techniques_(e-mail)" rel="nofollow">this article on wikipedia</a> on anti-spam techniques. Then make sure your not doing that crap.</p>
<p>**</p>
<p>As far as processing the messages, just remember it's a queued system. Connect to the server via POP3 to retrieve messages, open it, do some action, delete the message or archive it, and move on.</p>
<p>With regards to bouncebacks, let the mail server do most of the work. You should be able to configure it to notify a certain email account on the server in the event that it is unable to deliver a message. You can check that account periodically and process the Non Delivery Reports as necessary.</p>
| 2 | 2008-09-17T03:44:00Z | [
"python",
"email"
] |
Unittest causing sys.exit() | 79,754 | <p>No matter what I do sys.exit() is called by unittest, even the most trivial examples. I can't tell if my install is messed up or what is going on.</p>
<pre><code>IDLE 1.2.2 ==== No Subprocess ====
>>> import unittest
>>>
>>> class Test(unittest.TestCase):
def testA(self):
a = 1
self.assertEqual(a,1)
>>> unittest.main()
option -n not recognized
Usage: idle.pyw [options] [test] [...]
Options:
-h, --help Show this message
-v, --verbose Verbose output
-q, --quiet Minimal output
Examples:
idle.pyw - run default set of tests
idle.pyw MyTestSuite - run suite 'MyTestSuite'
idle.pyw MyTestCase.testSomething - run MyTestCase.testSomething
idle.pyw MyTestCase - run all 'test*' test methods
in MyTestCase
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
unittest.main()
File "E:\Python25\lib\unittest.py", line 767, in __init__
self.parseArgs(argv)
File "E:\Python25\lib\unittest.py", line 796, in parseArgs
self.usageExit(msg)
File "E:\Python25\lib\unittest.py", line 773, in usageExit
sys.exit(2)
SystemExit: 2
>>>
</code></pre>
| 11 | 2008-09-17T03:46:55Z | 79,826 | <p>Don't try to run <code>unittest.main()</code> from IDLE. It's trying to access <code>sys.argv</code>, and it's getting the args that IDLE was started with. Either run your tests in a different way from IDLE, or call <code>unittest.main()</code> in its own Python process.</p>
| 10 | 2008-09-17T03:58:24Z | [
"python",
"unit-testing"
] |
Unittest causing sys.exit() | 79,754 | <p>No matter what I do sys.exit() is called by unittest, even the most trivial examples. I can't tell if my install is messed up or what is going on.</p>
<pre><code>IDLE 1.2.2 ==== No Subprocess ====
>>> import unittest
>>>
>>> class Test(unittest.TestCase):
def testA(self):
a = 1
self.assertEqual(a,1)
>>> unittest.main()
option -n not recognized
Usage: idle.pyw [options] [test] [...]
Options:
-h, --help Show this message
-v, --verbose Verbose output
-q, --quiet Minimal output
Examples:
idle.pyw - run default set of tests
idle.pyw MyTestSuite - run suite 'MyTestSuite'
idle.pyw MyTestCase.testSomething - run MyTestCase.testSomething
idle.pyw MyTestCase - run all 'test*' test methods
in MyTestCase
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
unittest.main()
File "E:\Python25\lib\unittest.py", line 767, in __init__
self.parseArgs(argv)
File "E:\Python25\lib\unittest.py", line 796, in parseArgs
self.usageExit(msg)
File "E:\Python25\lib\unittest.py", line 773, in usageExit
sys.exit(2)
SystemExit: 2
>>>
</code></pre>
| 11 | 2008-09-17T03:46:55Z | 79,833 | <p>Your example is exiting on my install too. I can make it execute the tests and stay within Python by changing</p>
<pre><code>unittest.main()
</code></pre>
<p>to</p>
<pre><code>unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromTestCase(Test))
</code></pre>
<p>More information is available <a href="http://docs.python.org/library/unittest.html#basic-example" rel="nofollow">here</a> in the Python Library Reference.</p>
| 10 | 2008-09-17T03:59:27Z | [
"python",
"unit-testing"
] |
Unittest causing sys.exit() | 79,754 | <p>No matter what I do sys.exit() is called by unittest, even the most trivial examples. I can't tell if my install is messed up or what is going on.</p>
<pre><code>IDLE 1.2.2 ==== No Subprocess ====
>>> import unittest
>>>
>>> class Test(unittest.TestCase):
def testA(self):
a = 1
self.assertEqual(a,1)
>>> unittest.main()
option -n not recognized
Usage: idle.pyw [options] [test] [...]
Options:
-h, --help Show this message
-v, --verbose Verbose output
-q, --quiet Minimal output
Examples:
idle.pyw - run default set of tests
idle.pyw MyTestSuite - run suite 'MyTestSuite'
idle.pyw MyTestCase.testSomething - run MyTestCase.testSomething
idle.pyw MyTestCase - run all 'test*' test methods
in MyTestCase
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
unittest.main()
File "E:\Python25\lib\unittest.py", line 767, in __init__
self.parseArgs(argv)
File "E:\Python25\lib\unittest.py", line 796, in parseArgs
self.usageExit(msg)
File "E:\Python25\lib\unittest.py", line 773, in usageExit
sys.exit(2)
SystemExit: 2
>>>
</code></pre>
| 11 | 2008-09-17T03:46:55Z | 79,932 | <p>Pop open the source code to <code>unittest.py</code>. <code>unittest.main()</code> is hard-coded to call <code>sys.exit()</code> after running all tests. Use <code>TextTestRunner</code> to run test suites from the prompt.</p>
| 5 | 2008-09-17T04:19:45Z | [
"python",
"unit-testing"
] |
Unittest causing sys.exit() | 79,754 | <p>No matter what I do sys.exit() is called by unittest, even the most trivial examples. I can't tell if my install is messed up or what is going on.</p>
<pre><code>IDLE 1.2.2 ==== No Subprocess ====
>>> import unittest
>>>
>>> class Test(unittest.TestCase):
def testA(self):
a = 1
self.assertEqual(a,1)
>>> unittest.main()
option -n not recognized
Usage: idle.pyw [options] [test] [...]
Options:
-h, --help Show this message
-v, --verbose Verbose output
-q, --quiet Minimal output
Examples:
idle.pyw - run default set of tests
idle.pyw MyTestSuite - run suite 'MyTestSuite'
idle.pyw MyTestCase.testSomething - run MyTestCase.testSomething
idle.pyw MyTestCase - run all 'test*' test methods
in MyTestCase
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
unittest.main()
File "E:\Python25\lib\unittest.py", line 767, in __init__
self.parseArgs(argv)
File "E:\Python25\lib\unittest.py", line 796, in parseArgs
self.usageExit(msg)
File "E:\Python25\lib\unittest.py", line 773, in usageExit
sys.exit(2)
SystemExit: 2
>>>
</code></pre>
| 11 | 2008-09-17T03:46:55Z | 407,950 | <pre><code>try:
sys.exit()
except SystemExit:
print('Simple as that, but you should really use a TestRunner instead')
</code></pre>
| 1 | 2009-01-02T20:34:33Z | [
"python",
"unit-testing"
] |
Unittest causing sys.exit() | 79,754 | <p>No matter what I do sys.exit() is called by unittest, even the most trivial examples. I can't tell if my install is messed up or what is going on.</p>
<pre><code>IDLE 1.2.2 ==== No Subprocess ====
>>> import unittest
>>>
>>> class Test(unittest.TestCase):
def testA(self):
a = 1
self.assertEqual(a,1)
>>> unittest.main()
option -n not recognized
Usage: idle.pyw [options] [test] [...]
Options:
-h, --help Show this message
-v, --verbose Verbose output
-q, --quiet Minimal output
Examples:
idle.pyw - run default set of tests
idle.pyw MyTestSuite - run suite 'MyTestSuite'
idle.pyw MyTestCase.testSomething - run MyTestCase.testSomething
idle.pyw MyTestCase - run all 'test*' test methods
in MyTestCase
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
unittest.main()
File "E:\Python25\lib\unittest.py", line 767, in __init__
self.parseArgs(argv)
File "E:\Python25\lib\unittest.py", line 796, in parseArgs
self.usageExit(msg)
File "E:\Python25\lib\unittest.py", line 773, in usageExit
sys.exit(2)
SystemExit: 2
>>>
</code></pre>
| 11 | 2008-09-17T03:46:55Z | 3,215,505 | <p>In new Python 2.7 release, <a href="http://docs.python.org/library/unittest.html#unittest.main" rel="nofollow">unittest.main()</a> has a new argument.</p>
<p>If 'exit' is set to <code>False</code>, <code>sys.exit()</code> is not called during the execution of <code>unittest.main()</code>.</p>
| 17 | 2010-07-09T18:30:28Z | [
"python",
"unit-testing"
] |
Unittest causing sys.exit() | 79,754 | <p>No matter what I do sys.exit() is called by unittest, even the most trivial examples. I can't tell if my install is messed up or what is going on.</p>
<pre><code>IDLE 1.2.2 ==== No Subprocess ====
>>> import unittest
>>>
>>> class Test(unittest.TestCase):
def testA(self):
a = 1
self.assertEqual(a,1)
>>> unittest.main()
option -n not recognized
Usage: idle.pyw [options] [test] [...]
Options:
-h, --help Show this message
-v, --verbose Verbose output
-q, --quiet Minimal output
Examples:
idle.pyw - run default set of tests
idle.pyw MyTestSuite - run suite 'MyTestSuite'
idle.pyw MyTestCase.testSomething - run MyTestCase.testSomething
idle.pyw MyTestCase - run all 'test*' test methods
in MyTestCase
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
unittest.main()
File "E:\Python25\lib\unittest.py", line 767, in __init__
self.parseArgs(argv)
File "E:\Python25\lib\unittest.py", line 796, in parseArgs
self.usageExit(msg)
File "E:\Python25\lib\unittest.py", line 773, in usageExit
sys.exit(2)
SystemExit: 2
>>>
</code></pre>
| 11 | 2008-09-17T03:46:55Z | 21,262,077 | <p>It's nice to be able to demonstrate that your tests work when first trying out the unittest module, and to know that you won't exit your Python shell. However, these solutions are version dependent.</p>
<h2>Python 2.6</h2>
<p>I'm using Python 2.6 at work, <code>import</code>ing <code>unittest2 as unittest</code> (which is the <code>unittest</code> module supposedly found in Python 2.7). </p>
<p>The <code>unittest.main(exit=False)</code> doesn't work in Python 2.6's unittest2, while JoeSkora's solution does, and to reiterate it:</p>
<pre><code>unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromTestCase(Test))
</code></pre>
<p>To break this down into its components and default arguments, with correct semantic names for the various composed objects:</p>
<pre><code>import sys # sys.stderr is used in below default args
test_loader = unittest.TestLoader()
loaded_test_suite = test_loader.loadTestsFromTestCase(Test)
# Default args:
text_test_runner = unittest.TextTestRunner(stream=sys.stderr,
descriptions=True,
verbosity=1)
text_test_runner.run(loaded_test_suite)
</code></pre>
<h2>Python 2.7 and 3</h2>
<p>In Python 2.7 and higher, the following should work.</p>
<pre><code>unittest.main(exit=False)
</code></pre>
| 3 | 2014-01-21T15:18:13Z | [
"python",
"unit-testing"
] |
How do I convert local time to UTC in Python? | 79,797 | <p>How do I convert a datetime <em>string in local time</em> to a <em>string in UTC time</em>?</p>
<p>I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.</p>
<p><strong>Clarification</strong>: For example, if I have <code>2008-09-17 14:02:00</code> in my local timezone (<code>+10</code>), I'd like to generate a string with the equivalent <code>UTC</code> time: <code>2008-09-17 04:02:00</code>.</p>
<p>Also, from <a href="http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/">http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/</a>, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.</p>
| 147 | 2008-09-17T03:52:42Z | 79,808 | <pre><code>def local_to_utc(t):
secs = time.mktime(t)
return time.gmtime(secs)
def utc_to_local(t):
secs = calendar.timegm(t)
return time.localtime(secs)
</code></pre>
<p>Source: <a href="http://feihonghsu.blogspot.com/2008/02/converting-from-local-time-to-utc.html">http://feihonghsu.blogspot.com/2008/02/converting-from-local-time-to-utc.html</a></p>
<p>Example usage from <a href="http://stackoverflow.com/users/8171/bd808">bd808</a>: If your source is a <code>datetime.datetime</code> object <code>t</code>, call as:</p>
<pre><code>local_to_utc(t.timetuple())
</code></pre>
| 20 | 2008-09-17T03:54:39Z | [
"python",
"datetime",
"utc"
] |
How do I convert local time to UTC in Python? | 79,797 | <p>How do I convert a datetime <em>string in local time</em> to a <em>string in UTC time</em>?</p>
<p>I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.</p>
<p><strong>Clarification</strong>: For example, if I have <code>2008-09-17 14:02:00</code> in my local timezone (<code>+10</code>), I'd like to generate a string with the equivalent <code>UTC</code> time: <code>2008-09-17 04:02:00</code>.</p>
<p>Also, from <a href="http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/">http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/</a>, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.</p>
| 147 | 2008-09-17T03:52:42Z | 79,877 | <p>First, parse the string into a naive datetime object. This is an instance of <code>datetime.datetime</code> with no attached timezone information. See documentation for <code>datetime.strptime</code> for information on parsing the date string.</p>
<p>Use the <a href="http://pytz.sourceforge.net/"><code>pytz</code></a> module, which comes with a full list of time zones + UTC. Figure out what the local timezone is, construct a timezone object from it, and manipulate and attach it to the naive datetime.</p>
<p>Finally, use <code>datetime.astimezone()</code> method to convert the datetime to UTC.</p>
<p>Source code, using local timezone "America/Los_Angeles", for the string "2001-2-3 10:11:12":</p>
<pre><code>import pytz, datetime
local = pytz.timezone ("America/Los_Angeles")
naive = datetime.datetime.strptime ("2001-2-3 10:11:12", "%Y-%m-%d %H:%M:%S")
local_dt = local.localize(naive, is_dst=None)
utc_dt = local_dt.astimezone (pytz.utc)
</code></pre>
<p>From there, you can use the <code>strftime()</code> method to format the UTC datetime as needed:</p>
<pre><code>utc_dt.strftime ("%Y-%m-%d %H:%M:%S")
</code></pre>
| 137 | 2008-09-17T04:07:28Z | [
"python",
"datetime",
"utc"
] |
How do I convert local time to UTC in Python? | 79,797 | <p>How do I convert a datetime <em>string in local time</em> to a <em>string in UTC time</em>?</p>
<p>I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.</p>
<p><strong>Clarification</strong>: For example, if I have <code>2008-09-17 14:02:00</code> in my local timezone (<code>+10</code>), I'd like to generate a string with the equivalent <code>UTC</code> time: <code>2008-09-17 04:02:00</code>.</p>
<p>Also, from <a href="http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/">http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/</a>, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.</p>
| 147 | 2008-09-17T03:52:42Z | 79,913 | <p>Thanks @rofly, the full conversion from string to string is as follows:</p>
<pre><code>time.strftime("%Y-%m-%d %H:%M:%S",
time.gmtime(time.mktime(time.strptime("2008-09-17 14:04:00",
"%Y-%m-%d %H:%M:%S"))))
</code></pre>
<p>My summary of the <code>time</code>/<code>calendar</code> functions:</p>
<p><code>time.strptime</code><br>
string --> tuple (no timezone applied, so matches string)</p>
<p><code>time.mktime</code><br>
local time tuple --> seconds since epoch (always local time)</p>
<p><code>time.gmtime</code><br>
seconds since epoch --> tuple in UTC</p>
<p>and </p>
<p><code>calendar.timegm</code><br>
tuple in UTC --> seconds since epoch</p>
<p><code>time.localtime</code><br>
seconds since epoch --> tuple in local timezone</p>
| 51 | 2008-09-17T04:15:39Z | [
"python",
"datetime",
"utc"
] |
How do I convert local time to UTC in Python? | 79,797 | <p>How do I convert a datetime <em>string in local time</em> to a <em>string in UTC time</em>?</p>
<p>I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.</p>
<p><strong>Clarification</strong>: For example, if I have <code>2008-09-17 14:02:00</code> in my local timezone (<code>+10</code>), I'd like to generate a string with the equivalent <code>UTC</code> time: <code>2008-09-17 04:02:00</code>.</p>
<p>Also, from <a href="http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/">http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/</a>, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.</p>
| 147 | 2008-09-17T03:52:42Z | 1,464,261 | <p>How about - </p>
<pre><code>time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(seconds))
</code></pre>
<p>if seconds is <code>None</code> then it converts the local time to UTC time else converts the passed in time to UTC.</p>
| 2 | 2009-09-23T06:28:23Z | [
"python",
"datetime",
"utc"
] |
How do I convert local time to UTC in Python? | 79,797 | <p>How do I convert a datetime <em>string in local time</em> to a <em>string in UTC time</em>?</p>
<p>I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.</p>
<p><strong>Clarification</strong>: For example, if I have <code>2008-09-17 14:02:00</code> in my local timezone (<code>+10</code>), I'd like to generate a string with the equivalent <code>UTC</code> time: <code>2008-09-17 04:02:00</code>.</p>
<p>Also, from <a href="http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/">http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/</a>, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.</p>
| 147 | 2008-09-17T03:52:42Z | 2,175,170 | <p>The datetime module's <a href="http://docs.python.org/library/datetime.html#datetime.datetime.utcnow" rel="nofollow">utcnow()</a> function can be used to obtain the current UTC time.</p>
<pre><code>>>> import datetime
>>> utc_datetime = datetime.datetime.utcnow()
>>> utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
'2010-02-01 06:59:19'
</code></pre>
<p>As the link mentioned above by Tom: <a href="http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/" rel="nofollow">http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/</a> says:</p>
<blockquote>
<p>UTC is a timezone without daylight saving time and still a timezone
without configuration changes in the past.</p>
<p><em>Always measure and store time in UTC</em>. </p>
<p>If you need to record where the time was taken, store that separately.
<strong><em>Do not</strong> store the local time + timezone information!</em></p>
</blockquote>
<p><strong>NOTE</strong> - If any of your data is in a region that uses DST, use <code>pytz</code> and take a look at John Millikin's answer.</p>
<p>If you want to obtain the UTC time from a given string and your lucky enough to be in a region in the world that either doesn't use DST, or you have data that is only offset from UTC without DST applied:</p>
<p>--> using local time as the basis for the offset value:</p>
<pre><code>>>> # Obtain the UTC Offset for the current system:
>>> UTC_OFFSET_TIMEDELTA = datetime.datetime.utcnow() - datetime.datetime.now()
>>> local_datetime = datetime.datetime.strptime("2008-09-17 14:04:00", "%Y-%m-%d %H:%M:%S")
>>> result_utc_datetime = local_datetime + UTC_OFFSET_TIMEDELTA
>>> result_utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
'2008-09-17 04:04:00'
</code></pre>
<p>--> Or, from a known offset, using datetime.timedelta():</p>
<pre><code>>>> UTC_OFFSET = 10
>>> result_utc_datetime = local_datetime - datetime.timedelta(hours=UTC_OFFSET)
>>> result_utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
'2008-09-17 04:04:00'
</code></pre>
| 60 | 2010-02-01T07:00:27Z | [
"python",
"datetime",
"utc"
] |
How do I convert local time to UTC in Python? | 79,797 | <p>How do I convert a datetime <em>string in local time</em> to a <em>string in UTC time</em>?</p>
<p>I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.</p>
<p><strong>Clarification</strong>: For example, if I have <code>2008-09-17 14:02:00</code> in my local timezone (<code>+10</code>), I'd like to generate a string with the equivalent <code>UTC</code> time: <code>2008-09-17 04:02:00</code>.</p>
<p>Also, from <a href="http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/">http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/</a>, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.</p>
| 147 | 2008-09-17T03:52:42Z | 2,347,991 | <p>if you prefer datetime.datetime:</p>
<pre><code>dt = datetime.strptime("2008-09-17 14:04:00","%Y-%m-%d %H:%M:%S")
utc_struct_time = time.gmtime(time.mktime(dt.timetuple()))
utc_dt = datetime.fromtimestamp(time.mktime(utc_struct_time))
print dt.strftime("%Y-%m-%d %H:%M:%S")
</code></pre>
| 4 | 2010-02-27T16:12:25Z | [
"python",
"datetime",
"utc"
] |
How do I convert local time to UTC in Python? | 79,797 | <p>How do I convert a datetime <em>string in local time</em> to a <em>string in UTC time</em>?</p>
<p>I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.</p>
<p><strong>Clarification</strong>: For example, if I have <code>2008-09-17 14:02:00</code> in my local timezone (<code>+10</code>), I'd like to generate a string with the equivalent <code>UTC</code> time: <code>2008-09-17 04:02:00</code>.</p>
<p>Also, from <a href="http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/">http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/</a>, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.</p>
| 147 | 2008-09-17T03:52:42Z | 4,113,872 | <p>in this case ... pytz is best lib</p>
<pre><code>import pytz
utc = pytz.utc
yourdate = datetime.datetime.now()
yourdateutc = yourdate.astimezone(utc).replace(tzinfo=None)
</code></pre>
| -1 | 2010-11-06T16:02:06Z | [
"python",
"datetime",
"utc"
] |
How do I convert local time to UTC in Python? | 79,797 | <p>How do I convert a datetime <em>string in local time</em> to a <em>string in UTC time</em>?</p>
<p>I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.</p>
<p><strong>Clarification</strong>: For example, if I have <code>2008-09-17 14:02:00</code> in my local timezone (<code>+10</code>), I'd like to generate a string with the equivalent <code>UTC</code> time: <code>2008-09-17 04:02:00</code>.</p>
<p>Also, from <a href="http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/">http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/</a>, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.</p>
| 147 | 2008-09-17T03:52:42Z | 4,894,920 | <pre><code>import time
import datetime
def Local2UTC(LocalTime):
EpochSecond = time.mktime(LocalTime.timetuple())
utcTime = datetime.datetime.utcfromtimestamp(EpochSecond)
return utcTime
>>> LocalTime = datetime.datetime.now()
>>> UTCTime = Local2UTC(LocalTime)
>>> LocalTime.ctime()
'Thu Feb 3 22:33:46 2011'
>>> UTCTime.ctime()
'Fri Feb 4 05:33:46 2011'
</code></pre>
| 4 | 2011-02-04T05:38:34Z | [
"python",
"datetime",
"utc"
] |
How do I convert local time to UTC in Python? | 79,797 | <p>How do I convert a datetime <em>string in local time</em> to a <em>string in UTC time</em>?</p>
<p>I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.</p>
<p><strong>Clarification</strong>: For example, if I have <code>2008-09-17 14:02:00</code> in my local timezone (<code>+10</code>), I'd like to generate a string with the equivalent <code>UTC</code> time: <code>2008-09-17 04:02:00</code>.</p>
<p>Also, from <a href="http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/">http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/</a>, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.</p>
| 147 | 2008-09-17T03:52:42Z | 8,068,619 | <p>For getting around day-light saving, etc.</p>
<p>None of the above answers particularly helped me. The code below works for GMT.</p>
<pre><code>def get_utc_from_local(date_time, local_tz=None):
assert date_time.__class__.__name__ == 'datetime'
if local_tz is None:
local_tz = pytz.timezone(settings.TIME_ZONE) # Django eg, "Europe/London"
local_time = local_tz.normalize(local_tz.localize(date_time))
return local_time.astimezone(pytz.utc)
import pytz
from datetime import datetime
summer_11_am = datetime(2011, 7, 1, 11)
get_utc_from_local(summer_11_am)
>>>datetime.datetime(2011, 7, 1, 10, 0, tzinfo=<UTC>)
winter_11_am = datetime(2011, 11, 11, 11)
get_utc_from_local(winter_11_am)
>>>datetime.datetime(2011, 11, 11, 11, 0, tzinfo=<UTC>)
</code></pre>
| 2 | 2011-11-09T16:59:57Z | [
"python",
"datetime",
"utc"
] |
How do I convert local time to UTC in Python? | 79,797 | <p>How do I convert a datetime <em>string in local time</em> to a <em>string in UTC time</em>?</p>
<p>I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.</p>
<p><strong>Clarification</strong>: For example, if I have <code>2008-09-17 14:02:00</code> in my local timezone (<code>+10</code>), I'd like to generate a string with the equivalent <code>UTC</code> time: <code>2008-09-17 04:02:00</code>.</p>
<p>Also, from <a href="http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/">http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/</a>, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.</p>
| 147 | 2008-09-17T03:52:42Z | 8,563,126 | <p>I'm having good luck with <a href="http://labix.org/python-dateutil">dateutil</a> (which is widely recommended on SO for other related questions):</p>
<pre><code>from datetime import *
from dateutil import *
from dateutil.tz import *
# METHOD 1: Hardcode zones:
utc_zone = tz.gettz('UTC')
local_zone = tz.gettz('America/Chicago')
# METHOD 2: Auto-detect zones:
utc_zone = tz.tzutc()
local_zone = tz.tzlocal()
# Convert time string to datetime
local_time = datetime.strptime("2008-09-17 14:02:00", '%Y-%m-%d %H:%M:%S')
# Tell the datetime object that it's in local time zone since
# datetime objects are 'naive' by default
local_time = local_time.replace(tzinfo=local_zone)
# Convert time to UTC
utc_time = local_time.astimezone(utc_zone)
# Generate UTC time string
utc_string = utc_time.strftime('%Y-%m-%d %H:%M:%S')
</code></pre>
<p>(Code was derived from this answer to <a href="http://stackoverflow.com/a/4771733/165673">Convert UTC datetime string to local datetime</a>)</p>
| 11 | 2011-12-19T14:58:01Z | [
"python",
"datetime",
"utc"
] |
How do I convert local time to UTC in Python? | 79,797 | <p>How do I convert a datetime <em>string in local time</em> to a <em>string in UTC time</em>?</p>
<p>I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.</p>
<p><strong>Clarification</strong>: For example, if I have <code>2008-09-17 14:02:00</code> in my local timezone (<code>+10</code>), I'd like to generate a string with the equivalent <code>UTC</code> time: <code>2008-09-17 04:02:00</code>.</p>
<p>Also, from <a href="http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/">http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/</a>, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.</p>
| 147 | 2008-09-17T03:52:42Z | 10,040,725 | <p>One more example with pytz, but includes localize(), which saved my day.</p>
<pre><code>import pytz, datetime
utc = pytz.utc
fmt = '%Y-%m-%d %H:%M:%S'
amsterdam = pytz.timezone('Europe/Amsterdam')
dt = datetime.datetime.strptime("2012-04-06 10:00:00", fmt)
am_dt = amsterdam.localize(dt)
print am_dt.astimezone(utc).strftime(fmt)
'2012-04-06 08:00:00'
</code></pre>
| 14 | 2012-04-06T07:54:41Z | [
"python",
"datetime",
"utc"
] |
How do I convert local time to UTC in Python? | 79,797 | <p>How do I convert a datetime <em>string in local time</em> to a <em>string in UTC time</em>?</p>
<p>I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.</p>
<p><strong>Clarification</strong>: For example, if I have <code>2008-09-17 14:02:00</code> in my local timezone (<code>+10</code>), I'd like to generate a string with the equivalent <code>UTC</code> time: <code>2008-09-17 04:02:00</code>.</p>
<p>Also, from <a href="http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/">http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/</a>, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.</p>
| 147 | 2008-09-17T03:52:42Z | 12,059,267 | <p>You can do it with:</p>
<pre><code>>>> from time import strftime, gmtime, localtime
>>> strftime('%H:%M:%S', gmtime()) #UTC time
>>> strftime('%H:%M:%S', localtime()) # localtime
</code></pre>
| 2 | 2012-08-21T16:30:50Z | [
"python",
"datetime",
"utc"
] |
How do I convert local time to UTC in Python? | 79,797 | <p>How do I convert a datetime <em>string in local time</em> to a <em>string in UTC time</em>?</p>
<p>I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.</p>
<p><strong>Clarification</strong>: For example, if I have <code>2008-09-17 14:02:00</code> in my local timezone (<code>+10</code>), I'd like to generate a string with the equivalent <code>UTC</code> time: <code>2008-09-17 04:02:00</code>.</p>
<p>Also, from <a href="http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/">http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/</a>, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.</p>
| 147 | 2008-09-17T03:52:42Z | 12,186,921 | <p>I've had the most success with <a href="https://dateutil.readthedocs.org/en/latest/relativedelta.html" rel="nofollow">python-dateutil</a>:</p>
<pre><code>from dateutil import tz
def datetime_to_utc(date):
"""Returns date in UTC w/o tzinfo"""
return date.astimezone(tz.gettz('UTC')).replace(tzinfo=None) if date.tzinfo else date
</code></pre>
| 5 | 2012-08-29T21:40:03Z | [
"python",
"datetime",
"utc"
] |
How do I convert local time to UTC in Python? | 79,797 | <p>How do I convert a datetime <em>string in local time</em> to a <em>string in UTC time</em>?</p>
<p>I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.</p>
<p><strong>Clarification</strong>: For example, if I have <code>2008-09-17 14:02:00</code> in my local timezone (<code>+10</code>), I'd like to generate a string with the equivalent <code>UTC</code> time: <code>2008-09-17 04:02:00</code>.</p>
<p>Also, from <a href="http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/">http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/</a>, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.</p>
| 147 | 2008-09-17T03:52:42Z | 13,084,428 | <p>Here's a summary of common Python time conversions</p>
<ul>
<li>struct_time (UTC) â POSIX:<br><code>calendar.timegm(struct_time)</code></li>
<li>Naïve datetime (local) â POSIX:<br><code>calendar.timegm(stz.localize(dt, is_dst=None).utctimetuple())</code></li>
<li>Naïve datetime (UTC) â POSIX:<br><code>calendar.timegm(dt.utctimetuple())</code></li>
<li>Aware datetime â POSIX:<br><code>calendar.timegm(dt.utctimetuple())</code></li>
<li>POSIX â struct_time (UTC):<br><code>time.gmtime(t)</code></li>
<li>Naïve datetime (local) â struct_time (UTC):<br><code>stz.localize(dt, is_dst=None).utctimetuple()</code></li>
<li>Naïve datetime (UTC) â struct_time (UTC):<br><code>dt.utctimetuple()</code></li>
<li>Aware datetime â struct_time (UTC):<br><code>dt.utctimetuple()</code></li>
<li>POSIX â Naïve datetime (local):<br><code>datetime.fromtimestamp(t, None)</code></li>
<li>struct_time (UTC) â Naïve datetime (local):<br><code>datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz).replace(tzinfo=None)</code></li>
<li>Naïve datetime (UTC) â Naïve datetime (local):<br><code>dt.replace(tzinfo=UTC).astimezone(tz).replace(tzinfo=None)</code></li>
<li>Aware datetime â Naïve datetime (local):<br><code>dt.astimezone(tz).replace(tzinfo=None)</code></li>
<li>POSIX â Naïve datetime (UTC):<br><code>datetime.utcfromtimestamp(t)</code></li>
<li>struct_time (UTC) â Naïve datetime (UTC):<br><code>datetime.datetime(struct_time[:6])</code></li>
<li>Naïve datetime (local) â Naïve datetime (UTC):<br><code>stz.localize(dt, is_dst=None).astimezone(UTC).replace(tzinfo=None)</code></li>
<li>Aware datetime â Naïve datetime (UTC):<br><code>dt.astimezone(UTC).replace(tzinfo=None)</code></li>
<li>POSIX â Aware datetime:<br><code>datetime.fromtimestamp(t, tz)</code></li>
<li>struct_time (UTC) â Aware datetime:<br><code>datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz)</code></li>
<li>Naïve datetime (local) â Aware datetime:<br><code>stz.localize(dt, is_dst=None)</code></li>
<li>Naïve datetime (UTC) â Aware datetime:<br><code>dt.replace(tzinfo=UTC)</code></li>
</ul>
<p>Source: <a href="http://taaviburns.ca/presentations/what_you_need_to_know_about_datetimes/">taaviburns.ca</a></p>
| 9 | 2012-10-26T09:38:42Z | [
"python",
"datetime",
"utc"
] |
How do you design data models for Bigtable/Datastore (GAE)? | 79,850 | <p>Since the Google App Engine Datastore is based on <a href="http://research.google.com/archive/bigtable.html">Bigtable</a> and we know that's not a relational database, how do you design a <strong><em>database schema</em>/*data model*</strong> for applications that use this type of database system?</p>
| 17 | 2008-09-17T04:02:53Z | 80,420 | <p>As GAE builds on how data is managed in Django there is a lot of info on how to address similar questions in the Django documentation (for example see <a href="http://www.djangobook.com/en/1.0/chapter05/" rel="nofollow">here</a>, scroll down to 'Your first model').</p>
<p>In short you design you db model as a regular object model and let GAE sort out all of the object-relational mappings. </p>
| -2 | 2008-09-17T06:01:53Z | [
"python",
"database",
"google-app-engine",
"bigtable"
] |
How do you design data models for Bigtable/Datastore (GAE)? | 79,850 | <p>Since the Google App Engine Datastore is based on <a href="http://research.google.com/archive/bigtable.html">Bigtable</a> and we know that's not a relational database, how do you design a <strong><em>database schema</em>/*data model*</strong> for applications that use this type of database system?</p>
| 17 | 2008-09-17T04:02:53Z | 80,425 | <p>Designing a bigtable schema is an open process, and basically requires you to think about:</p>
<ul>
<li>The access patterns you will be using and how often each will be used</li>
<li>The relationships between your types</li>
<li>What indices you are going to need</li>
<li>The write patterns you will be using (in order to effectively spread load)</li>
</ul>
<p>GAE's datastore automatically denormalizes your data. That is, each index contains a (mostly) complete copy of the data, and thus every index adds significantly to time taken to perform a write, and the storage space used.</p>
<p>If this were not the case, designing a Datastore schema would be a lot more work: You would have to think carefully about the primary key for each type, and consider the effect of your decision on the locality of data. For example, when rendering a blog post you would probably need to display the comments to go along with it, so each comment's key would probably begin with the associated post's key.</p>
<p>With Datastore, this is not such a big deal: The query you use will look something like "Select * FROM Comment WHERE post_id = N." (If you want to page the comments, you would also have a limit clause, and a possible suffix of " AND comment_id > last_comment_id".) Once you add such a query, Datastore will build the index for you, and your reads will be magically fast.</p>
<p>Something to keep in mind is that each additional index creates some additional cost: it is best if you can use as few access patterns as possible, since it will reduce the number of indices GAE will construct, and thus the total storage required by your data.</p>
<p>Reading over this answer, I find it a little vague. Maybe a hands-on design question would help to scope this down? :-)</p>
| 18 | 2008-09-17T06:02:38Z | [
"python",
"database",
"google-app-engine",
"bigtable"
] |
How do you design data models for Bigtable/Datastore (GAE)? | 79,850 | <p>Since the Google App Engine Datastore is based on <a href="http://research.google.com/archive/bigtable.html">Bigtable</a> and we know that's not a relational database, how do you design a <strong><em>database schema</em>/*data model*</strong> for applications that use this type of database system?</p>
| 17 | 2008-09-17T04:02:53Z | 196,660 | <p>You can use www.web2py.com. You build the model and the application once and it works on GAE but also witl SQLite, MySQL, Posgres, Oracle, MSSQL, FireBird</p>
| 1 | 2008-10-13T03:49:29Z | [
"python",
"database",
"google-app-engine",
"bigtable"
] |
Split a string by spaces -- preserving quoted substrings -- in Python | 79,968 | <p>I have a string which is like this:</p>
<pre><code>this is "a test"
</code></pre>
<p>I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:</p>
<pre><code>['this','is','a test']
</code></pre>
<p>PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen.</p>
| 163 | 2008-09-17T04:25:15Z | 79,985 | <p>You want split, from the <a href="https://docs.python.org/2/library/shlex.html">shlex</a> module.</p>
<pre><code>>>> import shlex
>>> shlex.split('this is "a test"')
['this', 'is', 'a test']
</code></pre>
<p>This should do exactly what you want.</p>
| 253 | 2008-09-17T04:27:32Z | [
"python",
"regex"
] |
Split a string by spaces -- preserving quoted substrings -- in Python | 79,968 | <p>I have a string which is like this:</p>
<pre><code>this is "a test"
</code></pre>
<p>I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:</p>
<pre><code>['this','is','a test']
</code></pre>
<p>PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen.</p>
| 163 | 2008-09-17T04:25:15Z | 79,989 | <p>Have a look at the <code>shlex</code> module, particularly <code>shlex.split</code>.</p>
<blockquote>
<p><code>>>> import shlex</code></p>
<p><code>>>> shlex.split('This is "a test"')</code></p>
<p><code>['This', 'is', 'a test']</code></p>
</blockquote>
| 45 | 2008-09-17T04:27:59Z | [
"python",
"regex"
] |
Split a string by spaces -- preserving quoted substrings -- in Python | 79,968 | <p>I have a string which is like this:</p>
<pre><code>this is "a test"
</code></pre>
<p>I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:</p>
<pre><code>['this','is','a test']
</code></pre>
<p>PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen.</p>
| 163 | 2008-09-17T04:25:15Z | 80,015 | <p>Try this:</p>
<pre><code> def adamsplit(s):
result = []
inquotes = False
for substring in s.split('"'):
if not inquotes:
result.extend(substring.split())
else:
result.append(substring)
inquotes = not inquotes
return result
</code></pre>
<p>Some test strings:</p>
<pre><code>'This is "a test"' -> ['This', 'is', 'a test']
'"This is \'a test\'"' -> ["This is 'a test'"]
</code></pre>
| -2 | 2008-09-17T04:31:38Z | [
"python",
"regex"
] |
Split a string by spaces -- preserving quoted substrings -- in Python | 79,968 | <p>I have a string which is like this:</p>
<pre><code>this is "a test"
</code></pre>
<p>I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:</p>
<pre><code>['this','is','a test']
</code></pre>
<p>PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen.</p>
| 163 | 2008-09-17T04:25:15Z | 80,361 | <p>If you don't care about sub strings than a simple</p>
<pre><code>>>> 'a short sized string with spaces '.split()
</code></pre>
<p>Performance:</p>
<pre><code>>>> s = " ('a short sized string with spaces '*100).split() "
>>> t = timeit.Timer(stmt=s)
>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
171.39 usec/pass
</code></pre>
<p>Or string module</p>
<pre><code>>>> from string import split as stringsplit;
>>> stringsplit('a short sized string with spaces '*100)
</code></pre>
<p>Performance: String module seems to perform better than string methods</p>
<pre><code>>>> s = "stringsplit('a short sized string with spaces '*100)"
>>> t = timeit.Timer(s, "from string import split as stringsplit")
>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
154.88 usec/pass
</code></pre>
<p>Or you can use RE engine</p>
<pre><code>>>> from re import split as resplit
>>> regex = '\s+'
>>> medstring = 'a short sized string with spaces '*100
>>> resplit(regex, medstring)
</code></pre>
<p>Performance</p>
<pre><code>>>> s = "resplit(regex, medstring)"
>>> t = timeit.Timer(s, "from re import split as resplit; regex='\s+'; medstring='a short sized string with spaces '*100")
>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
540.21 usec/pass
</code></pre>
<p>For very long strings you should not load the entire string into memory and instead either split the lines or use an iterative loop</p>
| -1 | 2008-09-17T05:46:57Z | [
"python",
"regex"
] |
Split a string by spaces -- preserving quoted substrings -- in Python | 79,968 | <p>I have a string which is like this:</p>
<pre><code>this is "a test"
</code></pre>
<p>I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:</p>
<pre><code>['this','is','a test']
</code></pre>
<p>PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen.</p>
| 163 | 2008-09-17T04:25:15Z | 80,449 | <p>Since this question is tagged with regex, I decided to try a regex approach. I first replace all the spaces in the quotes parts with \x00, then split by spaces, then replace the \x00 back to spaces in each part.</p>
<p>Both versions do the same thing, but splitter is a bit more readable then splitter2.</p>
<pre><code>import re
s = 'this is "a test" some text "another test"'
def splitter(s):
def replacer(m):
return m.group(0).replace(" ", "\x00")
parts = re.sub('".+?"', replacer, s).split()
parts = [p.replace("\x00", " ") for p in parts]
return parts
def splitter2(s):
return [p.replace("\x00", " ") for p in re.sub('".+?"', lambda m: m.group(0).replace(" ", "\x00"), s).split()]
print splitter2(s)
</code></pre>
| 8 | 2008-09-17T06:08:38Z | [
"python",
"regex"
] |
Split a string by spaces -- preserving quoted substrings -- in Python | 79,968 | <p>I have a string which is like this:</p>
<pre><code>this is "a test"
</code></pre>
<p>I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:</p>
<pre><code>['this','is','a test']
</code></pre>
<p>PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen.</p>
| 163 | 2008-09-17T04:25:15Z | 524,796 | <p>I see regex approaches here that look complex and/or wrong. This surprises me, because regex syntax can easily describe "whitespace or thing-surrounded-by-quotes", and most regex engines (including Python's) can split on a regex. So if you're going to use regexes, why not just say exactly what you mean?:</p>
<pre><code>test = 'this is "a test"' # or "this is 'a test'"
# pieces = [p for p in re.split("( |[\\\"'].*[\\\"'])", test) if p.strip()]
# From comments, use this:
pieces = [p for p in re.split("( |\\\".*?\\\"|'.*?')", test) if p.strip()]
</code></pre>
<p>Explanation:</p>
<pre><code>[\\\"'] = double-quote or single-quote
.* = anything
( |X) = space or X
.strip() = remove space and empty-string separators
</code></pre>
<p>shlex probably provides more features, though.</p>
| 26 | 2009-02-07T23:17:26Z | [
"python",
"regex"
] |
Split a string by spaces -- preserving quoted substrings -- in Python | 79,968 | <p>I have a string which is like this:</p>
<pre><code>this is "a test"
</code></pre>
<p>I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:</p>
<pre><code>['this','is','a test']
</code></pre>
<p>PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen.</p>
| 163 | 2008-09-17T04:25:15Z | 525,011 | <p>Depending on your use case, you may also want to check out the csv module:</p>
<pre><code>import csv
lines = ['this is "a string"', 'and more "stuff"']
for row in csv.reader(lines, delimiter=" "):
print row
</code></pre>
<p>Output: </p>
<pre><code>['this', 'is', 'a string']
['and', 'more', 'stuff']
</code></pre>
| 17 | 2009-02-08T02:18:46Z | [
"python",
"regex"
] |
Split a string by spaces -- preserving quoted substrings -- in Python | 79,968 | <p>I have a string which is like this:</p>
<pre><code>this is "a test"
</code></pre>
<p>I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:</p>
<pre><code>['this','is','a test']
</code></pre>
<p>PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen.</p>
| 163 | 2008-09-17T04:25:15Z | 2,159,337 | <p>Hmm, can't seem to find the "Reply" button... anyway, this answer is based on the approach by Kate, but correctly splits strings with substrings containing escaped quotes and also removes the start and end quotes of the substrings:</p>
<pre><code> [i.strip('"').strip("'") for i in re.split(r'(\s+|(?<!\\)".*?(?<!\\)"|(?<!\\)\'.*?(?<!\\)\')', string) if i.strip()]
</code></pre>
<p>This works on strings like <code>'This is " a \\\"test\\\"\\\'s substring"'</code> (the insane markup is unfortunately necessary to keep Python from removing the escapes).</p>
<p>If the resulting escapes in the strings in the returned list are not wanted, you can use this slightly altered version of the function:</p>
<pre><code>[i.strip('"').strip("'").decode('string_escape') for i in re.split(r'(\s+|(?<!\\)".*?(?<!\\)"|(?<!\\)\'.*?(?<!\\)\')', string) if i.strip()]
</code></pre>
| 1 | 2010-01-29T01:36:23Z | [
"python",
"regex"
] |
Split a string by spaces -- preserving quoted substrings -- in Python | 79,968 | <p>I have a string which is like this:</p>
<pre><code>this is "a test"
</code></pre>
<p>I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:</p>
<pre><code>['this','is','a test']
</code></pre>
<p>PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen.</p>
| 163 | 2008-09-17T04:25:15Z | 11,194,593 | <p>To get around the unicode issues in some Python 2 versions, I suggest:</p>
<pre><code>from shlex import split as _split
split = lambda a: [b.decode('utf-8') for b in _split(a.encode('utf-8'))]
</code></pre>
| 2 | 2012-06-25T17:51:17Z | [
"python",
"regex"
] |
Split a string by spaces -- preserving quoted substrings -- in Python | 79,968 | <p>I have a string which is like this:</p>
<pre><code>this is "a test"
</code></pre>
<p>I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:</p>
<pre><code>['this','is','a test']
</code></pre>
<p>PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen.</p>
| 163 | 2008-09-17T04:25:15Z | 11,644,046 | <p>The unicode issues with shlex discussed above (top answer) appear to be resolved (indirectly) in 2.7.2+ as per
<a href="http://bugs.python.org/issue6988#msg146200" rel="nofollow">http://bugs.python.org/issue6988#msg146200</a></p>
<p>(separate answer because I can't comment)</p>
| 1 | 2012-07-25T06:42:53Z | [
"python",
"regex"
] |
Split a string by spaces -- preserving quoted substrings -- in Python | 79,968 | <p>I have a string which is like this:</p>
<pre><code>this is "a test"
</code></pre>
<p>I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:</p>
<pre><code>['this','is','a test']
</code></pre>
<p>PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen.</p>
| 163 | 2008-09-17T04:25:15Z | 23,155,180 | <p>I use shlex.split to process 70,000,000 lines of squid log, it's so slow. So I switched to re.</p>
<p>Please try this, if you have performance problem with shlex.</p>
<pre><code>import re
def line_split(line):
return re.findall(r'[^"\s]\S*|".+?"', line)
</code></pre>
| 3 | 2014-04-18T13:29:10Z | [
"python",
"regex"
] |
Split a string by spaces -- preserving quoted substrings -- in Python | 79,968 | <p>I have a string which is like this:</p>
<pre><code>this is "a test"
</code></pre>
<p>I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:</p>
<pre><code>['this','is','a test']
</code></pre>
<p>PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen.</p>
| 163 | 2008-09-17T04:25:15Z | 32,480,710 | <p>I suggest:</p>
<p>test string:</p>
<pre><code>s = 'abc "ad" \'fg\' "kk\'rdt\'" zzz"34"zzz "" \'\''
</code></pre>
<p>to capture also "" and '':</p>
<pre><code>import re
re.findall(r'"[^"]*"|\'[^\']*\'|[^"\'\s]+',s)
</code></pre>
<p>result:</p>
<pre><code>['abc', '"ad"', "'fg'", '"kk\'rdt\'"', 'zzz', '"34"', 'zzz', '""', "''"]
</code></pre>
<p>to ignore empty "" and '':</p>
<pre><code>import re
re.findall(r'"[^"]+"|\'[^\']+\'|[^"\'\s]+',s)
</code></pre>
<p>result:</p>
<pre><code>['abc', '"ad"', "'fg'", '"kk\'rdt\'"', 'zzz', '"34"', 'zzz']
</code></pre>
| 0 | 2015-09-09T13:19:59Z | [
"python",
"regex"
] |
Btrieve without Pervasive? | 80,215 | <p>Is there any library available to query Btrieve databases without buying something from Pervasive? I'm looking to code in C# or Python.</p>
| 2 | 2008-09-17T05:15:02Z | 80,596 | <p>As far as I know that is not possible. It is not an open source database, so writing drivers for it is really hard.</p>
| 1 | 2008-09-17T06:45:50Z | [
"c#",
"python",
"btrieve"
] |
Btrieve without Pervasive? | 80,215 | <p>Is there any library available to query Btrieve databases without buying something from Pervasive? I'm looking to code in C# or Python.</p>
| 2 | 2008-09-17T05:15:02Z | 275,524 | <p>If you download one of the trial versions, you can get/install the odbc client and connect that way.</p>
<p>In our version of pervasive (older version) on the server where the database is installed, you can also find this client install.</p>
| 2 | 2008-11-09T02:28:52Z | [
"c#",
"python",
"btrieve"
] |
Btrieve without Pervasive? | 80,215 | <p>Is there any library available to query Btrieve databases without buying something from Pervasive? I'm looking to code in C# or Python.</p>
| 2 | 2008-09-17T05:15:02Z | 718,654 | <p>This depends a lot on the version of Btrieve. I've been working with btrieve for a long time and have found that the best API for the old 6.15 version was in pascal. That having been said there was definately a C api around as well.</p>
<p>Pervasive have recently released a 6.15 ultimate patch. Using this and the C api should allow you to work effectively with older btrieve databases. It is possible for instance to build new modules for python using C. </p>
| 0 | 2009-04-05T09:39:25Z | [
"c#",
"python",
"btrieve"
] |
PubSub lib for c# | 80,347 | <p>Is there a c# library which provides similar functionality to the <a href="http://wiki.wxpython.org/PubSub" rel="nofollow">Python PubSub</a> library? I think it's kind of an Observer Pattern which allows me to subscribe for messages of a given topic instead of using events.</p>
| 1 | 2008-09-17T05:44:30Z | 80,362 | <p>These may be a bit heavy for you depending on your needs but:
<a href="http://www.nservicebus.com/" rel="nofollow">http://www.nservicebus.com/</a>
<a href="http://blog.phatboyg.com/masstransit/" rel="nofollow">http://blog.phatboyg.com/masstransit/</a></p>
| 3 | 2008-09-17T05:47:09Z | [
"c#",
"python",
"design-patterns"
] |
PubSub lib for c# | 80,347 | <p>Is there a c# library which provides similar functionality to the <a href="http://wiki.wxpython.org/PubSub" rel="nofollow">Python PubSub</a> library? I think it's kind of an Observer Pattern which allows me to subscribe for messages of a given topic instead of using events.</p>
| 1 | 2008-09-17T05:44:30Z | 80,864 | <p>Again, my be overkill, but the <a href="http://ose.sf.net" rel="nofollow">OSE</a> library allows thins kind of thing.</p>
| 0 | 2008-09-17T07:42:21Z | [
"c#",
"python",
"design-patterns"
] |
PubSub lib for c# | 80,347 | <p>Is there a c# library which provides similar functionality to the <a href="http://wiki.wxpython.org/PubSub" rel="nofollow">Python PubSub</a> library? I think it's kind of an Observer Pattern which allows me to subscribe for messages of a given topic instead of using events.</p>
| 1 | 2008-09-17T05:44:30Z | 467,248 | <p>Note, if you have events for message notification, there are many options for dependancy injection / inversion of control. See <a href="http://www.springframework.net/" rel="nofollow">Spring.Net</a> and <a href="http://www.castleproject.org/container/" rel="nofollow">Castle Windsor</a> as two popular frameworks.</p>
| 1 | 2009-01-21T22:15:14Z | [
"c#",
"python",
"design-patterns"
] |
PubSub lib for c# | 80,347 | <p>Is there a c# library which provides similar functionality to the <a href="http://wiki.wxpython.org/PubSub" rel="nofollow">Python PubSub</a> library? I think it's kind of an Observer Pattern which allows me to subscribe for messages of a given topic instead of using events.</p>
| 1 | 2008-09-17T05:44:30Z | 29,311,041 | <p>Looks like there are several offerings on NuGet: <a href="https://www.nuget.org/packages?q=pubsub" rel="nofollow">https://www.nuget.org/packages?q=pubsub</a></p>
| 0 | 2015-03-27T22:13:05Z | [
"c#",
"python",
"design-patterns"
] |
Asychronous Programming in Python Twisted | 80,617 | <p>I'm having trouble developing a reverse proxy in Twisted. It works, but it seems overly complex and convoluted. So much of it feels like voodoo...</p>
<p>Are there any <em>simple, solid</em> examples of asynchronous program structure on the web or in books? A sort of best practices guide? When I complete my program I'd like to be able to still see the structure in some way, not be looking at a bowl of spaghetti.</p>
| 29 | 2008-09-17T06:51:35Z | 81,106 | <p>If you aren't looking to use twisted there was a great guide I used a while back. Here is the <a href="http://www.nightmare.com/pythonwin/async_sockets.html" rel="nofollow">link to it</a>.</p>
| 0 | 2008-09-17T08:25:06Z | [
"python",
"asynchronous",
"twisted"
] |
Asychronous Programming in Python Twisted | 80,617 | <p>I'm having trouble developing a reverse proxy in Twisted. It works, but it seems overly complex and convoluted. So much of it feels like voodoo...</p>
<p>Are there any <em>simple, solid</em> examples of asynchronous program structure on the web or in books? A sort of best practices guide? When I complete my program I'd like to be able to still see the structure in some way, not be looking at a bowl of spaghetti.</p>
| 29 | 2008-09-17T06:51:35Z | 81,456 | <p>Twisted contains a <a href="http://twistedmatrix.com/projects/core/documentation/howto/index.html">large number of examples</a>. One in particular, the <a href="http://twistedmatrix.com/projects/core/documentation/howto/tutorial/intro.html">"evolution of Finger" tutorial</a>, contains a thorough explanation of how an asynchronous program grows from a very small kernel up to a complex system with lots of moving parts. Another one that might be of interest to you is the tutorial about simply <a href="http://twistedmatrix.com/projects/core/documentation/howto/servers.html">writing servers</a>.</p>
<p>The key thing to keep in mind about Twisted, or even other asynchronous networking libraries (such as <a href="http://www.python.org/doc/current/lib/module-asyncore.html">asyncore</a>, <a href="http://mina.apache.org/">MINA</a>, or <a href="http://www.cs.wustl.edu/~schmidt/ACE-overview.html">ACE</a>), is that your code only gets invoked when something happens. The part that I've heard most often sound like "voodoo" is the management of callbacks: for example, <code>Deferred</code>. If you're used to writing code that runs in a straight line, and only calls functions which return immediately with results, the idea of waiting for something to call you back might be confusing. But there's nothing magical, no "voodoo" about callbacks. At the lowest level, the reactor is just sitting around and waiting for one of a small number of things to happen:</p>
<ol>
<li>Data arrives on a connection (it will call <code>dataReceived</code> on a Protocol)</li>
<li>Time has passed (it will call a function registered with <code>callLater</code>).</li>
<li>A connection has been accepted (it will call <code>buildProtocol</code> on a factory registered with a <code>listenXXX</code> or <code>connectXXX</code> function).</li>
<li>A connection has been dropped (it will call <code>connectionLost</code> on the appropriate Protocol)</li>
</ol>
<p>Every asynchronous program starts by hooking up a few of these events and then kicking off the reactor to wait for them to happen. Of course, events that happen lead to more events that get hooked up or disconnected, and so your program goes on its merry way. Beyond that, there's nothing special about asynchronous program structure that are interesting or special; event handlers and callbacks are just objects, and your code is run in the usual way.</p>
<p>Here's a simple "event-driven engine" that shows you just how simple this process is.</p>
<pre><code># Engine
import time
class SimplestReactor(object):
def __init__(self):
self.events = []
self.stopped = False
def do(self, something):
self.events.append(something)
def run(self):
while not self.stopped:
time.sleep(0.1)
if self.events:
thisTurn = self.events.pop(0)
thisTurn()
def stop(self):
self.stopped = True
reactor = SimplestReactor()
# Application
def thing1():
print 'Doing thing 1'
reactor.do(thing2)
reactor.do(thing3)
def thing2():
print 'Doing thing 2'
def thing3():
print 'Doing thing 3: and stopping'
reactor.stop()
reactor.do(thing1)
print 'Running'
reactor.run()
print 'Done!'
</code></pre>
<p>At the core of libraries like Twisted, the function in the main loop is not <code>sleep</code>, but an operating system call like <code>select()</code> or <code>poll()</code>, as exposed by a module like <a href="http://docs.python.org/lib/module-select.html">the Python select module</a>. I say "like" <code>select</code>, because this is an API that varies a lot between platforms, and almost every GUI toolkit has its own version. Twisted currently provides an abstract interface to 14 different variations on this theme. The common thing that such an API provides is provide a way to say "Here are a list of events that I'm waiting for. Go to sleep until one of them happens, then wake up and tell me which one of them it was."</p>
| 63 | 2008-09-17T09:29:45Z | [
"python",
"asynchronous",
"twisted"
] |
How to skip sys.exitfunc when unhandled exceptions occur | 80,993 | <p>As you can see, even after the program should have died it speaks from the grave. Is there a way to "deregister" the exitfunction in case of exceptions?</p>
<pre><code>import atexit
def helloworld():
print("Hello World!")
atexit.register(helloworld)
raise Exception("Good bye cruel world!")
</code></pre>
<p>outputs</p>
<pre><code>Traceback (most recent call last):
File "test.py", line 8, in <module>
raise Exception("Good bye cruel world!")
Exception: Good bye cruel world!
Hello World!
</code></pre>
| 4 | 2008-09-17T08:05:18Z | 81,051 | <p>If you call</p>
<pre><code>import os
os._exit(0)
</code></pre>
<p>the exit handlers will not be called, yours or those registered by other modules in the application.</p>
| 0 | 2008-09-17T08:15:58Z | [
"python",
"exception",
"atexit"
] |
How to skip sys.exitfunc when unhandled exceptions occur | 80,993 | <p>As you can see, even after the program should have died it speaks from the grave. Is there a way to "deregister" the exitfunction in case of exceptions?</p>
<pre><code>import atexit
def helloworld():
print("Hello World!")
atexit.register(helloworld)
raise Exception("Good bye cruel world!")
</code></pre>
<p>outputs</p>
<pre><code>Traceback (most recent call last):
File "test.py", line 8, in <module>
raise Exception("Good bye cruel world!")
Exception: Good bye cruel world!
Hello World!
</code></pre>
| 4 | 2008-09-17T08:05:18Z | 81,087 | <p>I don't really know why you want to do that, but you can install an excepthook that will be called by Python whenever an uncatched exception is raised, and in it clear the array of registered function in the <code>atexit</code> module.</p>
<p>Something like that :</p>
<pre><code>import sys
import atexit
def clear_atexit_excepthook(exctype, value, traceback):
atexit._exithandlers[:] = []
sys.__excepthook__(exctype, value, traceback)
def helloworld():
print "Hello world!"
sys.excepthook = clear_atexit_excepthook
atexit.register(helloworld)
raise Exception("Good bye cruel world!")
</code></pre>
<p>Beware that it may behave incorrectly if the exception is raised from an <code>atexit</code> registered function (but then the behaviour would have been strange even if this hook was not used).</p>
| 5 | 2008-09-17T08:21:20Z | [
"python",
"exception",
"atexit"
] |
How to skip sys.exitfunc when unhandled exceptions occur | 80,993 | <p>As you can see, even after the program should have died it speaks from the grave. Is there a way to "deregister" the exitfunction in case of exceptions?</p>
<pre><code>import atexit
def helloworld():
print("Hello World!")
atexit.register(helloworld)
raise Exception("Good bye cruel world!")
</code></pre>
<p>outputs</p>
<pre><code>Traceback (most recent call last):
File "test.py", line 8, in <module>
raise Exception("Good bye cruel world!")
Exception: Good bye cruel world!
Hello World!
</code></pre>
| 4 | 2008-09-17T08:05:18Z | 81,107 | <p>In addition to calling os._exit() to avoid the registered exit handler you also need to catch the unhandled exception:</p>
<pre><code>import atexit
import os
def helloworld():
print "Hello World!"
atexit.register(helloworld)
try:
raise Exception("Good bye cruel world!")
except Exception, e:
print 'caught unhandled exception', str(e)
os._exit(1)
</code></pre>
| 0 | 2008-09-17T08:25:14Z | [
"python",
"exception",
"atexit"
] |
PythonWin's python interactive shell calling constructors twice? | 81,191 | <p>While answering <a href="http://stackoverflow.com/questions/68645/python-static-variable#81002">http://stackoverflow.com/questions/68645/python-static-variable#81002</a> </p>
<p>I noticed that PythonWin PyWin32 build 209.2 interpreter seems to evaluate twice?</p>
<pre><code>PythonWin 2.5 (r25:51908, Mar 9 2007, 17:40:28) [MSC v.1310 32 bit (Intel)] on win32.
Portions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin' for further copyright information.
>>> class X:
... l = []
... def __init__(self):
... self.__class__.l.append(1)
...
>>> X().l
[1, 1]
>>>
</code></pre>
<p>while the python interpreter does the right thing</p>
<pre><code>C:\>python
ActivePython 2.5.0.0 (ActiveState Software Inc.) based on
Python 2.5 (r25:51908, Mar 9 2007, 17:40:28) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class X:
... l = []
... def __init__(self):
... self.__class__.l.append(1)
...
>>> X().l
[1]
>>>
</code></pre>
| 2 | 2008-09-17T08:42:07Z | 81,274 | <p>My guess is as follows. The PythonWin editor offers autocomplete for an object, i.e. when you type <code>myobject.</code> it offers a little popup of all the availble method names. So I think when you type <code>X().</code> it's creating an instance of <code>X</code> in the background and doing a <code>dir</code> or similar to find out the attributes of the object.</p>
<p>So the constructor is only being run <em>once for each object</em> but to give you the interactivity it's creating objects silently in the background without telling you about it.</p>
| 3 | 2008-09-17T08:57:41Z | [
"python",
"activestate"
] |
PythonWin's python interactive shell calling constructors twice? | 81,191 | <p>While answering <a href="http://stackoverflow.com/questions/68645/python-static-variable#81002">http://stackoverflow.com/questions/68645/python-static-variable#81002</a> </p>
<p>I noticed that PythonWin PyWin32 build 209.2 interpreter seems to evaluate twice?</p>
<pre><code>PythonWin 2.5 (r25:51908, Mar 9 2007, 17:40:28) [MSC v.1310 32 bit (Intel)] on win32.
Portions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin' for further copyright information.
>>> class X:
... l = []
... def __init__(self):
... self.__class__.l.append(1)
...
>>> X().l
[1, 1]
>>>
</code></pre>
<p>while the python interpreter does the right thing</p>
<pre><code>C:\>python
ActivePython 2.5.0.0 (ActiveState Software Inc.) based on
Python 2.5 (r25:51908, Mar 9 2007, 17:40:28) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class X:
... l = []
... def __init__(self):
... self.__class__.l.append(1)
...
>>> X().l
[1]
>>>
</code></pre>
| 2 | 2008-09-17T08:42:07Z | 81,751 | <p>Two small additional points.</p>
<p>First, <code>self.__class__.l.append(1)</code> isn't really sensible.</p>
<p>Just say <code>self.l.append(1)</code>. Python searches the instance before it searches the class for the reference.</p>
<p>More importantly, class-level variables are rarely useful. Class-level constants are sometimes sensible, but even then, they're hard to justify. </p>
<p>In C++ and Java, class-level ('<code>static</code>') variables seem handy, but don't do much of value. They're hard to teach to n00bz -- often wasting lots of classroom time on minutia -- and they aren't very practical. If you want to know all instances of an X that was created, it's probably better to create an XFactory class that doesn't rely on class variables.</p>
<pre><code>class XFactory( object ):
def __init__( self ):
self.listOfX= []
def makeX( self, *args, **kw ):
newX= X(*args,**kw)
self.listOfX.append(newX)
return newX
</code></pre>
<p>No class-level variable anomalies. And, it doesn't conflate the X's with the collection of X's. In the long run, I find it confusing when a class is both some thing and also some collection of things.</p>
<p>Simpler is better than Complex.</p>
| 1 | 2008-09-17T10:18:30Z | [
"python",
"activestate"
] |
PythonWin's python interactive shell calling constructors twice? | 81,191 | <p>While answering <a href="http://stackoverflow.com/questions/68645/python-static-variable#81002">http://stackoverflow.com/questions/68645/python-static-variable#81002</a> </p>
<p>I noticed that PythonWin PyWin32 build 209.2 interpreter seems to evaluate twice?</p>
<pre><code>PythonWin 2.5 (r25:51908, Mar 9 2007, 17:40:28) [MSC v.1310 32 bit (Intel)] on win32.
Portions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin' for further copyright information.
>>> class X:
... l = []
... def __init__(self):
... self.__class__.l.append(1)
...
>>> X().l
[1, 1]
>>>
</code></pre>
<p>while the python interpreter does the right thing</p>
<pre><code>C:\>python
ActivePython 2.5.0.0 (ActiveState Software Inc.) based on
Python 2.5 (r25:51908, Mar 9 2007, 17:40:28) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class X:
... l = []
... def __init__(self):
... self.__class__.l.append(1)
...
>>> X().l
[1]
>>>
</code></pre>
| 2 | 2008-09-17T08:42:07Z | 84,248 | <p>Dave Webb is correct, and you can see this by adding a print statement:</p>
<pre><code>>>> class X:
... l = []
... def __init__(self):
... print 'inited'
... self.__class__.l.append(1)
...
</code></pre>
<p>Then as soon as you type the period in <code>X().</code> it prints <code>inited</code> prior to offering you the completion popup.</p>
| 2 | 2008-09-17T15:08:22Z | [
"python",
"activestate"
] |
Upload files in Google App Engine | 81,451 | <p>I am planning to create a web app that allows users to downgrade their visual studio project files. However, It seems Google App Engine accepts files uploading and flat file storing on the Google Server through <code>db.TextProperty</code> and <code>db.BlobProperty</code>.</p>
<p>I'll be glad anyone can provide code sample (both the client and the server side) on how this can be done.</p>
| 73 | 2008-09-17T09:28:53Z | 81,479 | <p>You can not store files as there is not a traditional file system. You can only store them in their own DataStore (in a field defined as a <a href="http://code.google.com/appengine/docs/datastore/typesandpropertyclasses.html" rel="nofollow">BlobProperty</a>)</p>
<p>There is an example in the previous link:</p>
<pre><code>class MyModel(db.Model):
blob = db.BlobProperty()
obj = MyModel()
obj.blob = db.Blob( file_contents )
</code></pre>
| 1 | 2008-09-17T09:32:32Z | [
"python",
"google-app-engine"
] |
Upload files in Google App Engine | 81,451 | <p>I am planning to create a web app that allows users to downgrade their visual studio project files. However, It seems Google App Engine accepts files uploading and flat file storing on the Google Server through <code>db.TextProperty</code> and <code>db.BlobProperty</code>.</p>
<p>I'll be glad anyone can provide code sample (both the client and the server side) on how this can be done.</p>
| 73 | 2008-09-17T09:28:53Z | 81,489 | <p>There's no flat file storing in Google App Engine. Everything has to go in to the <a href="http://code.google.com/appengine/docs/datastore/" rel="nofollow">Datastore</a> which is a bit like a relational database but not quite.</p>
<p>You could store the files as <a href="http://code.google.com/appengine/docs/datastore/typesandpropertyclasses.html#TextProperty" rel="nofollow">TextProperty</a> or <a href="http://code.google.com/appengine/docs/datastore/typesandpropertyclasses.html#BlobProperty" rel="nofollow">BlobProperty</a> attributes.</p>
<p>There is a 1MB limit on DataStore entries which may or may not be a problem.</p>
| 0 | 2008-09-17T09:33:52Z | [
"python",
"google-app-engine"
] |
Upload files in Google App Engine | 81,451 | <p>I am planning to create a web app that allows users to downgrade their visual studio project files. However, It seems Google App Engine accepts files uploading and flat file storing on the Google Server through <code>db.TextProperty</code> and <code>db.BlobProperty</code>.</p>
<p>I'll be glad anyone can provide code sample (both the client and the server side) on how this can be done.</p>
| 73 | 2008-09-17T09:28:53Z | 143,798 | <p>There is a thread in Google Groups about it:</p>
<p><a href="http://groups.google.com/group/google-appengine/browse_thread/thread/f9d0f22d8de8c025/bba32165e308dd13?lnk=gst&q=uploading+files#bba32165e308dd13">Uploading Files</a></p>
<p>With a lot of useful code, that discussion helped me very much in uploading files.</p>
| 10 | 2008-09-27T15:20:58Z | [
"python",
"google-app-engine"
] |
Upload files in Google App Engine | 81,451 | <p>I am planning to create a web app that allows users to downgrade their visual studio project files. However, It seems Google App Engine accepts files uploading and flat file storing on the Google Server through <code>db.TextProperty</code> and <code>db.BlobProperty</code>.</p>
<p>I'll be glad anyone can provide code sample (both the client and the server side) on how this can be done.</p>
| 73 | 2008-09-17T09:28:53Z | 173,918 | <p>In fact, this question is answered in the App Egnine documentation. See an example on <a href="http://code.google.com/appengine/docs/images/usingimages.html#Uploading">Uploading User Images</a>.</p>
<p>HTML code, inside <form></form>:</p>
<pre><input type="file" name="img"/></pre>
<p>Python code:</p>
<pre>class Guestbook(webapp.RequestHandler):
def post(self):
greeting = Greeting()
if users.get_current_user():
greeting.author = users.get_current_user()
greeting.content = self.request.get("content")
avatar = self.request.get("img")
greeting.avatar = db.Blob(avatar)
greeting.put()
self.redirect('/')</pre>
| 48 | 2008-10-06T11:15:22Z | [
"python",
"google-app-engine"
] |
Upload files in Google App Engine | 81,451 | <p>I am planning to create a web app that allows users to downgrade their visual studio project files. However, It seems Google App Engine accepts files uploading and flat file storing on the Google Server through <code>db.TextProperty</code> and <code>db.BlobProperty</code>.</p>
<p>I'll be glad anyone can provide code sample (both the client and the server side) on how this can be done.</p>
| 73 | 2008-09-17T09:28:53Z | 534,354 | <p>If your still having a problem, check you are using enctype in the form tag</p>
<p>No:</p>
<pre><code><form encoding="multipart/form-data" action="/upload">
</code></pre>
<p>Yes:</p>
<pre><code><form enctype="multipart/form-data" action="/upload">
</code></pre>
| 3 | 2009-02-10T21:47:22Z | [
"python",
"google-app-engine"
] |
Upload files in Google App Engine | 81,451 | <p>I am planning to create a web app that allows users to downgrade their visual studio project files. However, It seems Google App Engine accepts files uploading and flat file storing on the Google Server through <code>db.TextProperty</code> and <code>db.BlobProperty</code>.</p>
<p>I'll be glad anyone can provide code sample (both the client and the server side) on how this can be done.</p>
| 73 | 2008-09-17T09:28:53Z | 1,240,820 | <p>Personally I found the tutorial described <a href="http://shogi-software.blogspot.com/2009/04/google-app-engine-and-file-upload.html" rel="nofollow">here</a> useful when using the Java run time with GAE. For some reason, when I tried to upload a file using</p>
<pre><code><form action="/testservelet" method="get" enctype="multipart/form-data">
<div>
Myfile:<input type="file" name="file" size="50"/>
</div>
<div>
<input type="submit" value="Upload file">
</div>
</form>
</code></pre>
<p>I found that my HttpServlet class for some reason wouldn't accept the form with the 'enctype' attribute. Removing it works, however, this means I can't upload any files.</p>
| 1 | 2009-08-06T19:19:13Z | [
"python",
"google-app-engine"
] |
Upload files in Google App Engine | 81,451 | <p>I am planning to create a web app that allows users to downgrade their visual studio project files. However, It seems Google App Engine accepts files uploading and flat file storing on the Google Server through <code>db.TextProperty</code> and <code>db.BlobProperty</code>.</p>
<p>I'll be glad anyone can provide code sample (both the client and the server side) on how this can be done.</p>
| 73 | 2008-09-17T09:28:53Z | 1,987,486 | <p>Google has released a service for storing large files. Have a look at <a href="http://code.google.com/appengine/docs/python/blobstore/" rel="nofollow">blobstore API documentation</a>. If your files are > 1MB, you should use it.</p>
| 6 | 2009-12-31T23:33:53Z | [
"python",
"google-app-engine"
] |
Upload files in Google App Engine | 81,451 | <p>I am planning to create a web app that allows users to downgrade their visual studio project files. However, It seems Google App Engine accepts files uploading and flat file storing on the Google Server through <code>db.TextProperty</code> and <code>db.BlobProperty</code>.</p>
<p>I'll be glad anyone can provide code sample (both the client and the server side) on how this can be done.</p>
| 73 | 2008-09-17T09:28:53Z | 3,050,807 | <p>I try it today, It works as following:</p>
<p>my sdk version is 1.3.x</p>
<p>html page:</p>
<pre><code><form enctype="multipart/form-data" action="/upload" method="post" >
<input type="file" name="myfile" />
<input type="submit" />
</form>
</code></pre>
<p>Server Code:</p>
<pre><code>file_contents = self.request.POST.get('myfile').file.read()
</code></pre>
| 6 | 2010-06-16T04:55:55Z | [
"python",
"google-app-engine"
] |
Upload files in Google App Engine | 81,451 | <p>I am planning to create a web app that allows users to downgrade their visual studio project files. However, It seems Google App Engine accepts files uploading and flat file storing on the Google Server through <code>db.TextProperty</code> and <code>db.BlobProperty</code>.</p>
<p>I'll be glad anyone can provide code sample (both the client and the server side) on how this can be done.</p>
| 73 | 2008-09-17T09:28:53Z | 3,545,032 | <p>I have observed some strange behavior when uploading files on App Engine. When you submit the following form:</p>
<pre><code><form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="img" />
...
</form>
</code></pre>
<p>And then you extract the <code>img</code> from the request like this:</p>
<pre><code>img_contents = self.request.get('img')
</code></pre>
<p>The <code>img_contents</code> variable is a <code>str()</code> in Google Chrome, but it's unicode in Firefox. And as you now, the <code>db.Blob()</code> constructor takes a string and will throw an error if you pass in a unicode string. </p>
<p>Does anyone know how this can be fixed?</p>
<p>Also, what I find absolutely strange is that when I copy and paste the Guestbook application (with avatars), it works perfectly. I do everything exactly the same way in my code, but it just won't work. I'm very close to pulling my hair out.</p>
| 0 | 2010-08-23T05:53:11Z | [
"python",
"google-app-engine"
] |
Upload files in Google App Engine | 81,451 | <p>I am planning to create a web app that allows users to downgrade their visual studio project files. However, It seems Google App Engine accepts files uploading and flat file storing on the Google Server through <code>db.TextProperty</code> and <code>db.BlobProperty</code>.</p>
<p>I'll be glad anyone can provide code sample (both the client and the server side) on how this can be done.</p>
| 73 | 2008-09-17T09:28:53Z | 4,787,543 | <p>Here is a complete, working file. I pulled the original from the Google site and modified it to make it slightly more real world.</p>
<p>A few things to notice:</p>
<ol>
<li>This code uses the <a href="http://code.google.com/appengine/docs/python/blobstore/">BlobStore API</a></li>
<li><p>The purpose of this line in the
ServeHandler class is to "fix" the
key so that it gets rid of any name
mangling that may have occurred in
the browser (I didn't observe any in
Chrome)</p>
<pre><code>blob_key = str(urllib.unquote(blob_key))
</code></pre></li>
<li><p>The "save_as" clause at the end of this is important. It will make sure that the file name does not get mangled when it is sent to your browser. Get rid of it to observe what happens.</p>
<pre><code>self.send_blob(blobstore.BlobInfo.get(blob_key), save_as=True)
</code></pre></li>
</ol>
<p>Good Luck!</p>
<pre><code>import os
import urllib
from google.appengine.ext import blobstore
from google.appengine.ext import webapp
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
class MainHandler(webapp.RequestHandler):
def get(self):
upload_url = blobstore.create_upload_url('/upload')
self.response.out.write('<html><body>')
self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url)
self.response.out.write("""Upload File: <input type="file" name="file"><br> <input type="submit" name="submit" value="Submit"> </form></body></html>""")
for b in blobstore.BlobInfo.all():
self.response.out.write('<li><a href="/serve/%s' % str(b.key()) + '">' + str(b.filename) + '</a>')
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload_files = self.get_uploads('file')
blob_info = upload_files[0]
self.redirect('/')
class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
def get(self, blob_key):
blob_key = str(urllib.unquote(blob_key))
if not blobstore.get(blob_key):
self.error(404)
else:
self.send_blob(blobstore.BlobInfo.get(blob_key), save_as=True)
def main():
application = webapp.WSGIApplication(
[('/', MainHandler),
('/upload', UploadHandler),
('/serve/([^/]+)?', ServeHandler),
], debug=True)
run_wsgi_app(application)
if __name__ == '__main__':
main()
</code></pre>
| 39 | 2011-01-24T21:46:46Z | [
"python",
"google-app-engine"
] |
Upload files in Google App Engine | 81,451 | <p>I am planning to create a web app that allows users to downgrade their visual studio project files. However, It seems Google App Engine accepts files uploading and flat file storing on the Google Server through <code>db.TextProperty</code> and <code>db.BlobProperty</code>.</p>
<p>I'll be glad anyone can provide code sample (both the client and the server side) on how this can be done.</p>
| 73 | 2008-09-17T09:28:53Z | 11,814,685 | <p>There is a way of using <strong>flat file system</strong>( Atleast in usage perspective)</p>
<p>There is this <a href="http://code.google.com/p/gaevfs/" rel="nofollow"><strong>Google App Engine Virtual FileSystem project</strong></a>. that is implemented with the help of datastore and memcache APIs to emulate an ordinary filesystem. Using this library you can use in you project a <strong>similar filesystem access(read and write)</strong>.</p>
| 0 | 2012-08-05T07:27:45Z | [
"python",
"google-app-engine"
] |
PyQt and PyCairo | 82,180 | <p>I know it's possible to place a PyCairo surface inside a Gtk Drawing Area. But I think Qt is a lot better to work with, so I've been wondering if there's anyway to place a PyCairo surface inside some Qt component?</p>
| 2 | 2008-09-17T11:28:23Z | 82,258 | <p>Qt's own OpenGL based surfaces (using QPainter) are known to be much faster than Cairo. Might you explain why you want specifically Cairo in Qt?</p>
<p>For the basics of using QPainter see <a href="http://www.informit.com/articles/article.aspx?p=1174421" rel="nofollow">this excerpt</a> from the book "C++ GUI Programming with Qt4", and while it's C++ code, the PyQt implementation will be parallel.</p>
<p>As for joining Cairo with Qt... <a href="http://arstechnica.com/news.ars/post/20080818-nokia-helps-port-firefox-to-qt.html" rel="nofollow">This article in ArsTechnica</a> sheds some light - it seems nothing that could help you exists currently (iow., nobody tried such marriage).</p>
| 3 | 2008-09-17T11:44:49Z | [
"python",
"qt",
"gtk",
"pyqt"
] |
PyQt and PyCairo | 82,180 | <p>I know it's possible to place a PyCairo surface inside a Gtk Drawing Area. But I think Qt is a lot better to work with, so I've been wondering if there's anyway to place a PyCairo surface inside some Qt component?</p>
| 2 | 2008-09-17T11:28:23Z | 453,179 | <p>For plotting with you should also consider matplotlib, which provides a higher level API and integrates well with PyQT.</p>
| 0 | 2009-01-17T11:38:54Z | [
"python",
"qt",
"gtk",
"pyqt"
] |
Python + DNS : Cannot get RRSIG records: No Answer | 82,607 | <p>I get DNS records from a Python program, using <a href="http://www.dnspython.org/" rel="nofollow">DNS
Python</a></p>
<p>I can get various DNSSEC-related records:</p>
<pre><code>>>> import dns.resolver
>>> myresolver = dns.resolver.Resolver()
>>> myresolver.use_edns(1, 0, 1400)
>>> print myresolver.query('sources.org', 'DNSKEY')
<dns.resolver.Answer object at 0xb78ed78c>
>>> print myresolver.query('ripe.net', 'NSEC')
<dns.resolver.Answer object at 0x8271c0c>
</code></pre>
<p>But no RRSIG records:</p>
<pre><code>>>> print myresolver.query('sources.org', 'RRSIG')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 664, in query
answer = Answer(qname, rdtype, rdclass, response)
File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 121, in __init__
raise NoAnswer
</code></pre>
<p>I tried several signed domains like absolight.fr or ripe.net.</p>
<p>Trying with dig, I see that there are indeed RRSIG records.</p>
<p>Checking with tcpdump, I can see that DNS Python sends the correct
query and receives correct replies (here, eight records):</p>
<pre><code>16:09:39.342532 IP 192.134.4.69.53381 > 192.134.4.162.53: 22330+ [1au] RRSIG? sources.org. (40)
16:09:39.343229 IP 192.134.4.162.53 > 192.134.4.69.53381: 22330 8/5/6 RRSIG[|domain]
</code></pre>
<p>DNS Python 1.6.0 -
Python 2.5.2 (r252:60911, Aug 8 2008, 09:22:44)
[GCC 4.3.1] on linux2</p>
| 1 | 2008-09-17T12:32:01Z | 82,868 | <p>If you try this, what happens?</p>
<blockquote>
<blockquote>
<blockquote>
<p>print myresolver.query('sources.org', 'ANY', 'RRSIG')</p>
</blockquote>
</blockquote>
</blockquote>
| 0 | 2008-09-17T12:59:30Z | [
"python",
"dns",
"dnspython"
] |
Python + DNS : Cannot get RRSIG records: No Answer | 82,607 | <p>I get DNS records from a Python program, using <a href="http://www.dnspython.org/" rel="nofollow">DNS
Python</a></p>
<p>I can get various DNSSEC-related records:</p>
<pre><code>>>> import dns.resolver
>>> myresolver = dns.resolver.Resolver()
>>> myresolver.use_edns(1, 0, 1400)
>>> print myresolver.query('sources.org', 'DNSKEY')
<dns.resolver.Answer object at 0xb78ed78c>
>>> print myresolver.query('ripe.net', 'NSEC')
<dns.resolver.Answer object at 0x8271c0c>
</code></pre>
<p>But no RRSIG records:</p>
<pre><code>>>> print myresolver.query('sources.org', 'RRSIG')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 664, in query
answer = Answer(qname, rdtype, rdclass, response)
File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 121, in __init__
raise NoAnswer
</code></pre>
<p>I tried several signed domains like absolight.fr or ripe.net.</p>
<p>Trying with dig, I see that there are indeed RRSIG records.</p>
<p>Checking with tcpdump, I can see that DNS Python sends the correct
query and receives correct replies (here, eight records):</p>
<pre><code>16:09:39.342532 IP 192.134.4.69.53381 > 192.134.4.162.53: 22330+ [1au] RRSIG? sources.org. (40)
16:09:39.343229 IP 192.134.4.162.53 > 192.134.4.69.53381: 22330 8/5/6 RRSIG[|domain]
</code></pre>
<p>DNS Python 1.6.0 -
Python 2.5.2 (r252:60911, Aug 8 2008, 09:22:44)
[GCC 4.3.1] on linux2</p>
| 1 | 2008-09-17T12:32:01Z | 84,448 | <p>You probably mean RRSIG ANY (otherwise, the order is wrong, the class needs to be after the type)</p>
<pre><code>>>> print myresolver.query('sources.org', 'RRSIG', 'ANY')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 664, in query
answer = Answer(qname, rdtype, rdclass, response)
File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 121, in __init__
raise NoAnswer
dns.resolver.NoAnswer
</code></pre>
| 1 | 2008-09-17T15:25:29Z | [
"python",
"dns",
"dnspython"
] |
Python + DNS : Cannot get RRSIG records: No Answer | 82,607 | <p>I get DNS records from a Python program, using <a href="http://www.dnspython.org/" rel="nofollow">DNS
Python</a></p>
<p>I can get various DNSSEC-related records:</p>
<pre><code>>>> import dns.resolver
>>> myresolver = dns.resolver.Resolver()
>>> myresolver.use_edns(1, 0, 1400)
>>> print myresolver.query('sources.org', 'DNSKEY')
<dns.resolver.Answer object at 0xb78ed78c>
>>> print myresolver.query('ripe.net', 'NSEC')
<dns.resolver.Answer object at 0x8271c0c>
</code></pre>
<p>But no RRSIG records:</p>
<pre><code>>>> print myresolver.query('sources.org', 'RRSIG')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 664, in query
answer = Answer(qname, rdtype, rdclass, response)
File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 121, in __init__
raise NoAnswer
</code></pre>
<p>I tried several signed domains like absolight.fr or ripe.net.</p>
<p>Trying with dig, I see that there are indeed RRSIG records.</p>
<p>Checking with tcpdump, I can see that DNS Python sends the correct
query and receives correct replies (here, eight records):</p>
<pre><code>16:09:39.342532 IP 192.134.4.69.53381 > 192.134.4.162.53: 22330+ [1au] RRSIG? sources.org. (40)
16:09:39.343229 IP 192.134.4.162.53 > 192.134.4.69.53381: 22330 8/5/6 RRSIG[|domain]
</code></pre>
<p>DNS Python 1.6.0 -
Python 2.5.2 (r252:60911, Aug 8 2008, 09:22:44)
[GCC 4.3.1] on linux2</p>
| 1 | 2008-09-17T12:32:01Z | 114,923 | <p>This looks like a probable bug in the Python DNS library, although I don't read Python well enough to find it.</p>
<p>Note that in any case your EDNS0 buffer size parameter is not large enough to handle the RRSIG records for sources.org, so your client and server would have to fail over to TCP/IP.</p>
| 0 | 2008-09-22T13:42:59Z | [
"python",
"dns",
"dnspython"
] |
Python + DNS : Cannot get RRSIG records: No Answer | 82,607 | <p>I get DNS records from a Python program, using <a href="http://www.dnspython.org/" rel="nofollow">DNS
Python</a></p>
<p>I can get various DNSSEC-related records:</p>
<pre><code>>>> import dns.resolver
>>> myresolver = dns.resolver.Resolver()
>>> myresolver.use_edns(1, 0, 1400)
>>> print myresolver.query('sources.org', 'DNSKEY')
<dns.resolver.Answer object at 0xb78ed78c>
>>> print myresolver.query('ripe.net', 'NSEC')
<dns.resolver.Answer object at 0x8271c0c>
</code></pre>
<p>But no RRSIG records:</p>
<pre><code>>>> print myresolver.query('sources.org', 'RRSIG')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 664, in query
answer = Answer(qname, rdtype, rdclass, response)
File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 121, in __init__
raise NoAnswer
</code></pre>
<p>I tried several signed domains like absolight.fr or ripe.net.</p>
<p>Trying with dig, I see that there are indeed RRSIG records.</p>
<p>Checking with tcpdump, I can see that DNS Python sends the correct
query and receives correct replies (here, eight records):</p>
<pre><code>16:09:39.342532 IP 192.134.4.69.53381 > 192.134.4.162.53: 22330+ [1au] RRSIG? sources.org. (40)
16:09:39.343229 IP 192.134.4.162.53 > 192.134.4.69.53381: 22330 8/5/6 RRSIG[|domain]
</code></pre>
<p>DNS Python 1.6.0 -
Python 2.5.2 (r252:60911, Aug 8 2008, 09:22:44)
[GCC 4.3.1] on linux2</p>
| 1 | 2008-09-17T12:32:01Z | 37,234,210 | <p>You may want to use <code>raise_on_no_answer=False</code> and you will get the correct response:</p>
<pre><code>resolver.query(hostname, dnsrecord, raise_on_no_answer=False)
</code></pre>
| 0 | 2016-05-15T03:23:10Z | [
"python",
"dns",
"dnspython"
] |
Is there any list of blog engines, written in Django? | 82,653 | <p>Is there any list of blog engines, written in Django?</p>
| 17 | 2008-09-17T12:37:48Z | 82,690 | <p><b>Byteflow</b> is a blog engine, written on Python, using Django</p>
| 3 | 2008-09-17T12:40:53Z | [
"python",
"django"
] |
Is there any list of blog engines, written in Django? | 82,653 | <p>Is there any list of blog engines, written in Django?</p>
| 17 | 2008-09-17T12:37:48Z | 82,717 | <p>James Bennett has an <a href="http://www.b-list.org/weblog/2007/nov/29/django-blog" rel="nofollow">interesting take</a> on this question:</p>
<blockquote>
<p>âwhere can I find a good Django-powered blogging applicationâ is probably at the top of the frequently-asked questions list both on django-users and in the IRC; part of this is simply that, right now, there is no âdefinitiveâ Django blogging application; there are a bunch of them available if you go looking, but youâre not likely to get anyone to recommend one of them as âtheâ Django blogging app (unless the person doing the recommending happens to be the author of one of them). </p>
</blockquote>
<p>The <a href="http://www.b-list.org/weblog/2007/nov/29/django-blog" rel="nofollow">blog entry</a> also has a list.</p>
| 4 | 2008-09-17T12:43:37Z | [
"python",
"django"
] |
Is there any list of blog engines, written in Django? | 82,653 | <p>Is there any list of blog engines, written in Django?</p>
| 17 | 2008-09-17T12:37:48Z | 82,739 | <p>EDIT: Original link went dead so here's an updated link with extracts of the list sorted with the most recently updated source at the top.</p>
<p><a href="http://blog.montylounge.com/2010/02/10/eleven-django-blog-engines-you-should-know/">Eleven Django blog engines you should know</a></p>
<p>by Monty Lounge Industries</p>
<blockquote>
<ul>
<li><a href="http://github.com/eldarion/biblion">Biblion</a></li>
<li><a href="http://bitbucket.org/codekoala/django-articles/">Django-article</a></li>
<li><a href="http://github.com/flother/flother">Flother</a></li>
<li><a href="http://github.com/nathanborror/django-basic-apps">Basic-Blog</a></li>
<li><a href="http://github.com/gregnewman/hello-newman">Hello-Newman</a></li>
<li><a href="http://getbanjo.com/download/">Banjo</a></li>
<li><a href="http://code.google.com/p/djangotechblog/">djangotechblog</a></li>
<li><a href="http://github.com/f4nt/django-yaba/">Django-YABA</a></li>
<li><a href="http://github.com/paltman/shiftingbits/">Shifting Bits</a> (this is now just a <a href="http://github.com/eldarion/biblion">biblion</a> blog)</li>
<li><a href="http://github.com/mightylemon/mightylemon">Mighty Lemon</a></li>
<li><a href="http://code.google.com/p/coltrane-blog/">Coltrane</a></li>
</ul>
</blockquote>
| 20 | 2008-09-17T12:45:14Z | [
"python",
"django"
] |
Is there any list of blog engines, written in Django? | 82,653 | <p>Is there any list of blog engines, written in Django?</p>
| 17 | 2008-09-17T12:37:48Z | 82,753 | <p>Django's powerful admin interface and easy ORM makes it a 30 minute job to build a blog that propably fits your needs; Why look for a 3rd party product when you can make it yourself very quickly?</p>
| 3 | 2008-09-17T12:46:38Z | [
"python",
"django"
] |
Is there any list of blog engines, written in Django? | 82,653 | <p>Is there any list of blog engines, written in Django?</p>
| 17 | 2008-09-17T12:37:48Z | 141,214 | <p>Nathan Borror has a great package of 'basic apps' that has a blog. These are well written, well documented apps that you should try out, get ideas from, etc.</p>
<p><a href="http://code.google.com/p/django-basic-apps/" rel="nofollow">http://code.google.com/p/django-basic-apps/</a></p>
| 1 | 2008-09-26T18:46:29Z | [
"python",
"django"
] |
Is there any list of blog engines, written in Django? | 82,653 | <p>Is there any list of blog engines, written in Django?</p>
| 17 | 2008-09-17T12:37:48Z | 2,001,335 | <p>The book <a href="http://rads.stackoverflow.com/amzn/click/1430219386" rel="nofollow">Practical Django Projects</a> provides a tutorial on how to create a Django blogging app.</p>
| 3 | 2010-01-04T18:41:48Z | [
"python",
"django"
] |
Is there any list of blog engines, written in Django? | 82,653 | <p>Is there any list of blog engines, written in Django?</p>
| 17 | 2008-09-17T12:37:48Z | 21,028,758 | <p>You should check <code>django-blogango</code>. <a href="http://agiliq.com/blog" rel="nofollow">http://agiliq.com/blog</a> is run using this blogging engine.</p>
<p><a href="https://github.com/agiliq/django-blogango" rel="nofollow">https://github.com/agiliq/django-blogango</a></p>
| 1 | 2014-01-09T18:55:06Z | [
"python",
"django"
] |
How do I check whether a file exists using Python? | 82,831 | <p>How do I check whether a file exists, without using the <a href="https://docs.python.org/3.6/reference/compound_stmts.html#try"><code>try</code></a> statement?</p>
| 2,729 | 2008-09-17T12:55:00Z | 82,836 | <pre><code>import os.path
if os.path.isfile(filename):
</code></pre>
| 211 | 2008-09-17T12:55:48Z | [
"python",
"file",
"filesystems"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.