title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How can you profile a Python script?
582,336
<p>Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to <code>__main__</code>.</p> <p>What is a good way to profile how long a python program takes to run?</p>
702
2009-02-24T16:01:26Z
583,452
<p>In Virtaal's <a href="https://translate.svn.sourceforge.net/svnroot/translate/src/trunk/virtaal/devsupport/profiling.py">source</a> there's a very useful class and decorator that can make it profiling (even for specific methods/functions) very easy. The output can then be viewed very comfortably in KCacheGrind.</p>
10
2009-02-24T20:31:10Z
[ "python", "performance", "profiling", "time-complexity" ]
How can you profile a Python script?
582,336
<p>Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to <code>__main__</code>.</p> <p>What is a good way to profile how long a python program takes to run?</p>
702
2009-02-24T16:01:26Z
1,922,945
<p>It's worth pointing out that using the profiler only works (by default) on the main thread, and you won't get any information from other threads if you use them. This can be a bit of a gotcha as it is completely unmentioned in the <a href="http://docs.python.org/library/profile.html">profiler documentation</a>.</p> <p>If you also want to profile threads, you'll want to look at the <a href="http://docs.python.org/library/threading.html#threading.setprofile"><code>threading.setprofile()</code> function</a> in the docs.</p> <p>You could also create your own <code>threading.Thread</code> subclass to do it:</p> <pre><code>class ProfiledThread(threading.Thread): # Overrides threading.Thread.run() def run(self): profiler = cProfile.Profile() try: return profiler.runcall(threading.Thread.run, self) finally: profiler.dump_stats('myprofile-%d.profile' % (self.ident,)) </code></pre> <p>and use that <code>ProfiledThread</code> class instead of the standard one. It might give you more flexibility, but I'm not sure it's worth it, especially if you are using third-party code which wouldn't use your class.</p>
140
2009-12-17T16:30:34Z
[ "python", "performance", "profiling", "time-complexity" ]
How can you profile a Python script?
582,336
<p>Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to <code>__main__</code>.</p> <p>What is a good way to profile how long a python program takes to run?</p>
702
2009-02-24T16:01:26Z
7,693,928
<p>The python wiki is a great page for profiling resources: <a href="http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Profiling_Code">http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Profiling_Code</a></p> <p>as is the python docs: <a href="http://docs.python.org/library/profile.html">http://docs.python.org/library/profile.html</a></p> <p>as shown by Chris Lawlor cProfile is a great tool and can easily be used to print to the screen:</p> <pre><code>python -m cProfile -s time mine.py &lt;args&gt; </code></pre> <p>or to file:</p> <pre><code>python -m cProfile -o output.file mine.py &lt;args&gt; </code></pre> <p>PS> If you are using Ubuntu, make sure to install python-profile</p> <pre><code>sudo apt-get install python-profiler </code></pre> <p>If you output to file you can get nice visualizations using the following tools</p> <p>PyCallGraph : a tool to create call graph images <br> install:<br></p> <pre><code> sudo pip install pycallgraph </code></pre> <p>run:</p> <pre><code> pycallgraph mine.py args </code></pre> <p>view:</p> <pre><code> gimp pycallgraph.png </code></pre> <p><em>You can use whatever you like to view the png file, I used gimp</em><br> Unfortunately I often get </p> <p>dot: graph is too large for cairo-renderer bitmaps. Scaling by 0.257079 to fit</p> <p>which makes my images unusably small. So I generally create svg files:</p> <pre><code>pycallgraph -f svg -o pycallgraph.svg mine.py &lt;args&gt; </code></pre> <p>PS> make sure to install graphviz (which provides the dot program):</p> <pre><code>sudo pip install graphviz </code></pre> <p>Alternative Graphing using gprof2dot via @maxy / @quodlibetor :</p> <pre><code>sudo pip install gprof2dot python -m cProfile -o profile.pstats mine.py gprof2dot -f pstats profile.pstats | dot -Tsvg -o mine.svg </code></pre>
103
2011-10-08T00:04:12Z
[ "python", "performance", "profiling", "time-complexity" ]
How can you profile a Python script?
582,336
<p>Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to <code>__main__</code>.</p> <p>What is a good way to profile how long a python program takes to run?</p>
702
2009-02-24T16:01:26Z
7,838,845
<p>A nice profiling module is the line_profiler (called using the script kernprof.py). It can be downloaded <a href="http://packages.python.org/line_profiler/">here</a>.</p> <p>My understanding is that cProfile only gives information about total time spent in each function. So individual lines of code are not timed. This is an issue in scientific computing since often one single line can take a lot of time. Also, as I remember, cProfile didn't catch the time I was spending in say numpy.dot.</p>
19
2011-10-20T16:05:34Z
[ "python", "performance", "profiling", "time-complexity" ]
How can you profile a Python script?
582,336
<p>Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to <code>__main__</code>.</p> <p>What is a good way to profile how long a python program takes to run?</p>
702
2009-02-24T16:01:26Z
8,065,384
<p>Following Joe Shaw's answer about multi-threaded code not to work as expected, I figured that the <code>runcall</code> method in cProfile is merely doing <code>self.enable()</code> and <code>self.disable()</code> calls around the profiled function call, so you can simply do that yourself and have whatever code you want in-between with minimal interference with existing code.</p>
8
2011-11-09T12:59:04Z
[ "python", "performance", "profiling", "time-complexity" ]
How can you profile a Python script?
582,336
<p>Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to <code>__main__</code>.</p> <p>What is a good way to profile how long a python program takes to run?</p>
702
2009-02-24T16:01:26Z
11,822,995
<p>A while ago I made <a href="http://pycallgraph.slowchop.com/"><code>pycallgraph</code></a> which generates a visualisation from your Python code. <strong>Edit:</strong> I've updated the example to work with the latest release.</p> <p>After a <code>pip install pycallgraph</code> and installing <a href="http://www.graphviz.org/">GraphViz</a> you can run it from the command line:</p> <pre><code>pycallgraph graphviz -- ./mypythonscript.py </code></pre> <p>Or, you can profile particular parts of your code:</p> <pre><code>from pycallgraph import PyCallGraph from pycallgraph.output import GraphvizOutput with PyCallGraph(output=GraphvizOutput()): code_to_profile() </code></pre> <p>Either of these will generate a <code>pycallgraph.png</code> file similar to the image below:</p> <p><img src="http://i.stack.imgur.com/aiNEA.png" alt="enter image description here"></p>
275
2012-08-06T05:37:07Z
[ "python", "performance", "profiling", "time-complexity" ]
How can you profile a Python script?
582,336
<p>Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to <code>__main__</code>.</p> <p>What is a good way to profile how long a python program takes to run?</p>
702
2009-02-24T16:01:26Z
12,874,474
<blockquote> <p>Ever want to know what the hell that python script is doing? Enter the Inspect Shell. Inspect Shell lets you print/alter globals and run functions without interrupting the running script. Now with auto-complete and command history (only on linux).</p> <p>Inspect Shell is not a pdb-style debugger.</p> </blockquote> <p><a href="https://github.com/amoffat/Inspect-Shell" rel="nofollow">https://github.com/amoffat/Inspect-Shell</a></p> <p>You could use that (and your wristwatch).</p>
3
2012-10-13T15:21:22Z
[ "python", "performance", "profiling", "time-complexity" ]
How can you profile a Python script?
582,336
<p>Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to <code>__main__</code>.</p> <p>What is a good way to profile how long a python program takes to run?</p>
702
2009-02-24T16:01:26Z
13,830,132
<p>@Maxy's comment on <a href="http://stackoverflow.com/a/7693928/25616">this answer</a> helped me out enough that I think it deserves its own answer: I already had cProfile-generated .pstats files and I didn't want to re-run things with pycallgraph, so I used <a href="http://code.google.com/p/jrfonseca/wiki/Gprof2Dot">gprof2dot</a>, and got pretty svgs:</p> <pre><code>$ sudo apt-get install graphviz $ git clone https://github.com/jrfonseca/gprof2dot $ ln -s "$PWD"/gprof2dot/gprof2dot.py ~/bin $ cd $PROJECT_DIR $ gprof2dot.py -f pstats profile.pstats | dot -Tsvg -o callgraph.svg </code></pre> <p>and BLAM!</p> <p>It uses dot (the same thing that pycallgraph uses) so output looks similar. I get the impression that gprof2dot loses less information though:</p> <p><img src="http://i.stack.imgur.com/JjSvt.png" alt="gprof2dot example output"></p>
83
2012-12-11T23:16:39Z
[ "python", "performance", "profiling", "time-complexity" ]
How can you profile a Python script?
582,336
<p>Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to <code>__main__</code>.</p> <p>What is a good way to profile how long a python program takes to run?</p>
702
2009-02-24T16:01:26Z
21,885,286
<p>My way is to use yappi (<a href="https://code.google.com/p/yappi/">https://code.google.com/p/yappi/</a>). It's especially useful combined with an RPC server where (even just for debugging) you register method to start, stop and print profiling information, e.g. in this way: </p> <pre><code>@staticmethod def startProfiler(): yappi.start() @staticmethod def stopProfiler(): yappi.stop() @staticmethod def printProfiler(): stats = yappi.get_stats(yappi.SORTTYPE_TTOT, yappi.SORTORDER_DESC, 20) statPrint = '\n' namesArr = [len(str(stat[0])) for stat in stats.func_stats] log.debug("namesArr %s", str(namesArr)) maxNameLen = max(namesArr) log.debug("maxNameLen: %s", maxNameLen) for stat in stats.func_stats: nameAppendSpaces = [' ' for i in range(maxNameLen - len(stat[0]))] log.debug('nameAppendSpaces: %s', nameAppendSpaces) blankSpace = '' for space in nameAppendSpaces: blankSpace += space log.debug("adding spaces: %s", len(nameAppendSpaces)) statPrint = statPrint + str(stat[0]) + blankSpace + " " + str(stat[1]).ljust(8) + "\t" + str( round(stat[2], 2)).ljust(8 - len(str(stat[2]))) + "\t" + str(round(stat[3], 2)) + "\n" log.log(1000, "\nname" + ''.ljust(maxNameLen - 4) + " ncall \tttot \ttsub") log.log(1000, statPrint) </code></pre> <p>Then when your program work you can start profiler at any time by calling the <code>startProfiler</code> RPC method and dump profiling information to a log file by calling <code>printProfiler</code> (or modify the rpc method to return it to the caller) and get such output:</p> <pre><code>2014-02-19 16:32:24,128-|SVR-MAIN |-(Thread-3 )-Level 1000: name ncall ttot tsub 2014-02-19 16:32:24,128-|SVR-MAIN |-(Thread-3 )-Level 1000: C:\Python27\lib\sched.py.run:80 22 0.11 0.05 M:\02_documents\_repos\09_aheadRepos\apps\ahdModbusSrv\pyAheadRpcSrv\xmlRpc.py.iterFnc:293 22 0.11 0.0 M:\02_documents\_repos\09_aheadRepos\apps\ahdModbusSrv\serverMain.py.makeIteration:515 22 0.11 0.0 M:\02_documents\_repos\09_aheadRepos\apps\ahdModbusSrv\pyAheadRpcSrv\PicklingXMLRPC.py._dispatch:66 1 0.0 0.0 C:\Python27\lib\BaseHTTPServer.py.date_time_string:464 1 0.0 0.0 c:\users\zasiec~1\appdata\local\temp\easy_install-hwcsr1\psutil-1.1.2-py2.7-win32.egg.tmp\psutil\_psmswindows.py._get_raw_meminfo:243 4 0.0 0.0 C:\Python27\lib\SimpleXMLRPCServer.py.decode_request_content:537 1 0.0 0.0 c:\users\zasiec~1\appdata\local\temp\easy_install-hwcsr1\psutil-1.1.2-py2.7-win32.egg.tmp\psutil\_psmswindows.py.get_system_cpu_times:148 4 0.0 0.0 &lt;string&gt;.__new__:8 220 0.0 0.0 C:\Python27\lib\socket.py.close:276 4 0.0 0.0 C:\Python27\lib\threading.py.__init__:558 1 0.0 0.0 &lt;string&gt;.__new__:8 4 0.0 0.0 C:\Python27\lib\threading.py.notify:372 1 0.0 0.0 C:\Python27\lib\rfc822.py.getheader:285 4 0.0 0.0 C:\Python27\lib\BaseHTTPServer.py.handle_one_request:301 1 0.0 0.0 C:\Python27\lib\xmlrpclib.py.end:816 3 0.0 0.0 C:\Python27\lib\SimpleXMLRPCServer.py.do_POST:467 1 0.0 0.0 C:\Python27\lib\SimpleXMLRPCServer.py.is_rpc_path_valid:460 1 0.0 0.0 C:\Python27\lib\SocketServer.py.close_request:475 1 0.0 0.0 c:\users\zasiec~1\appdata\local\temp\easy_install-hwcsr1\psutil-1.1.2-py2.7-win32.egg.tmp\psutil\__init__.py.cpu_times:1066 4 0.0 0.0 </code></pre> <p>It may not be very useful for short scripts but helps to optimize server-type processes especially given the <code>printProfiler</code> method can be called multiple times over time to profile and compare e.g. different program usage scenarios. </p>
6
2014-02-19T15:38:58Z
[ "python", "performance", "profiling", "time-complexity" ]
How can you profile a Python script?
582,336
<p>Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to <code>__main__</code>.</p> <p>What is a good way to profile how long a python program takes to run?</p>
702
2009-02-24T16:01:26Z
28,660,109
<p>Also worth mentioning is the GUI cProfile dump viewer <a href="http://www.vrplumber.com/programming/runsnakerun/">RunSnakeRun</a>. It allows you to sort and select, thereby zooming in on the relevant parts of the program. The sizes of the rectangles in the picture is proportional to the time taken. If you mouse over a rectangle it highlights that call in the table and everywhere on the map. When you double-click on a rectangle it zooms in on that portion. It will show you who calls that portion and what that portion calls.</p> <p>The descriptive information is very helpful. It shows you the code for that bit which can be helpful when you are dealing with built-in library calls. It tells you what file and what line to find the code.</p> <p>Also want to point at that the OP said 'profiling' but it appears he meant 'timing'. Keep in mind programs will run slower when profiled.</p> <p><img src="http://i.stack.imgur.com/2GahD.png" alt="enter image description here"></p>
18
2015-02-22T16:18:05Z
[ "python", "performance", "profiling", "time-complexity" ]
How can you profile a Python script?
582,336
<p>Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to <code>__main__</code>.</p> <p>What is a good way to profile how long a python program takes to run?</p>
702
2009-02-24T16:01:26Z
28,808,860
<h1>pprofile</h1> <p><code>line_profiler</code> (already presented here) also inspired <a href="https://github.com/vpelletier/pprofile" rel="nofollow"><code>pprofile</code></a>, which is described as:</p> <blockquote> <p>Line-granularity, thread-aware deterministic and statistic pure-python profiler</p> </blockquote> <p>It provides line-granularity as <code>line_profiler</code>, is pure Python, can be used as a standalone command or a module, and can even generate callgrind-format files that can be easily analyzed with <code>[k|q]cachegrind</code>.</p> <h1>vprof</h1> <p>There is also <a href="https://github.com/nvdv/vprof" rel="nofollow">vprof</a>, a Python package described as:</p> <blockquote> <p>[...] providing rich and interactive visualizations for various Python program characteristics such as running time and memory usage.</p> </blockquote> <p><a href="http://i.stack.imgur.com/uafO3.png" rel="nofollow"><img src="http://i.stack.imgur.com/uafO3.png" alt="heatmap"></a></p>
11
2015-03-02T11:36:47Z
[ "python", "performance", "profiling", "time-complexity" ]
How can you profile a Python script?
582,336
<p>Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to <code>__main__</code>.</p> <p>What is a good way to profile how long a python program takes to run?</p>
702
2009-02-24T16:01:26Z
29,183,471
<p>To add on to <a href="http://stackoverflow.com/a/582337/1070617">http://stackoverflow.com/a/582337/1070617</a>,</p> <p>I wrote this module that allows you to use cProfile and view its output easily. More here: <a href="https://github.com/ymichael/cprofilev" rel="nofollow">https://github.com/ymichael/cprofilev</a></p> <pre><code>$ python -m cprofilev /your/python/program # Go to http://localhost:4000 to view collected statistics. </code></pre> <p>Also see: <a href="http://ymichael.com/2014/03/08/profiling-python-with-cprofile.html" rel="nofollow">http://ymichael.com/2014/03/08/profiling-python-with-cprofile.html</a> on how to make sense of the collected statistics.</p>
3
2015-03-21T13:50:12Z
[ "python", "performance", "profiling", "time-complexity" ]
How can you profile a Python script?
582,336
<p>Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to <code>__main__</code>.</p> <p>What is a good way to profile how long a python program takes to run?</p>
702
2009-02-24T16:01:26Z
29,344,687
<p>cProfile is great for quick profiling but most of the time it was ending for me with the errors. Function runctx solves this problem by initializing correctly the environment and variables, hope it can be useful for someone:</p> <pre><code>import cProfile cProfile.runctx('foo()', None, locals()) </code></pre>
7
2015-03-30T11:11:13Z
[ "python", "performance", "profiling", "time-complexity" ]
How can you profile a Python script?
582,336
<p>Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to <code>__main__</code>.</p> <p>What is a good way to profile how long a python program takes to run?</p>
702
2009-02-24T16:01:26Z
29,931,325
<p>A new tool to handle profiling in Python is PyVmMonitor: <a href="http://www.pyvmmonitor.com/" rel="nofollow">http://www.pyvmmonitor.com/</a></p> <p>It has some unique features such as</p> <ul> <li>Attach profiler to a running (CPython) program</li> <li>On demand profiling with Yappi integration</li> <li>Profile on a different machine</li> <li>Multiple processes support (multiprocessing, django...)</li> <li>Live sampling/CPU view (with time range selection)</li> <li>Deterministic profiling through cProfile/profile integration</li> <li>Analyze existing PStats results</li> <li>Open DOT files</li> <li>Programatic API access</li> <li>Group samples by method or line</li> <li>PyDev integration</li> <li>PyCharm integration</li> </ul> <p>Note: it's commercial, but free for open source.</p>
2
2015-04-28T22:50:08Z
[ "python", "performance", "profiling", "time-complexity" ]
How can you profile a Python script?
582,336
<p>Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to <code>__main__</code>.</p> <p>What is a good way to profile how long a python program takes to run?</p>
702
2009-02-24T16:01:26Z
32,139,774
<p>There's a lot of great answers but they either use command line or some external program for profiling and/or sorting the results.</p> <p>I really missed some way I could use in my IDE (eclipse-PyDev) without touching the command line or installing anything. So here it is.</p> <h1>Profiling without command line</h1> <pre><code>def count(): from math import sqrt for x in range(10**5): sqrt(x) if __name__ == '__main__': import cProfile, pstats cProfile.run("count()", "{}.profile".format(__file__)) s = pstats.Stats("{}.profile".format(__file__)) s.strip_dirs() s.sort_stats("time").print_stats(10) </code></pre> <p>See <a href="https://docs.python.org/3.4/library/profile.html">docs</a> or other answers for more info.</p>
7
2015-08-21T11:59:43Z
[ "python", "performance", "profiling", "time-complexity" ]
How can you profile a Python script?
582,336
<p>Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to <code>__main__</code>.</p> <p>What is a good way to profile how long a python program takes to run?</p>
702
2009-02-24T16:01:26Z
35,351,674
<p>There's also a statistical profiler called <a href="https://pypi.python.org/pypi/statprof/" rel="nofollow"><code>statprof</code></a>. It's a sampling profiler, so it adds minimal overhead to your code and gives line-based (not just function-based) timings. It's more suited to soft real-time applications like games, but may be have less precision than cProfile.</p> <p>The <a href="https://pypi.python.org/pypi/statprof/" rel="nofollow">version in pypi</a> is a bit old, so can install it with <code>pip</code> by specifying <a href="https://github.com/bos/statprof.py" rel="nofollow">the git repository</a>:</p> <pre><code>pip install git+git://github.com/bos/statprof.py@1a33eba91899afe17a8b752c6dfdec6f05dd0c01 </code></pre> <p>You can run it like this:</p> <pre><code>import statprof with statprof.profile(): my_questionable_function() </code></pre> <p>See also <a href="http://stackoverflow.com/a/10333592/320036">http://stackoverflow.com/a/10333592/320036</a></p>
1
2016-02-11T22:50:49Z
[ "python", "performance", "profiling", "time-complexity" ]
How can you profile a Python script?
582,336
<p>Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to <code>__main__</code>.</p> <p>What is a good way to profile how long a python program takes to run?</p>
702
2009-02-24T16:01:26Z
37,157,132
<p>I think that <a href="https://docs.python.org/2/library/profile.html" rel="nofollow"><code>cProfile</code></a> is great for profiling, while <a href="https://kcachegrind.github.io/html/Home.html" rel="nofollow"><code>kcachegrind</code></a> is great for visualizing the results. The <a href="https://pypi.python.org/pypi/pyprof2calltree" rel="nofollow"><code>pyprof2calltree</code></a> in between handles the file conversion.</p> <pre><code>python -m cProfile -o script.profile script.py pyprof2calltree -i script.profile -o script.calltree kcachegrind script.calltree </code></pre> <p>To install the required tools (on Ubuntu, at least):</p> <pre><code>apt-get install kcachegrind pip install pyprof2calltree </code></pre>
4
2016-05-11T08:32:50Z
[ "python", "performance", "profiling", "time-complexity" ]
How can you profile a Python script?
582,336
<p>Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to <code>__main__</code>.</p> <p>What is a good way to profile how long a python program takes to run?</p>
702
2009-02-24T16:01:26Z
37,431,235
<p>I ran into a handy tool called <a href="https://jiffyclub.github.io/snakeviz/" rel="nofollow">SnakeViz</a> when researching this topic. SnakeViz is a web-based profiling visualization tool. It is very easy to install and use. The usual way I use it is to generate a stat file with <code>%prun</code> and then do analysis in SnakeViz.</p> <p>The main viz technique used is <strong>Sunburst chart</strong> as shown below, in which the hierarchy of function calls is arranged as layers of arcs and time info encoded in their angular widths.</p> <p>The best thing is you can interact with the chart. For example, to zoom in one can click on an arc, and the arc and its descendants will be enlarged as a new sunburst to display more details.</p> <p><a href="http://i.stack.imgur.com/kCmSY.png" rel="nofollow"><img src="http://i.stack.imgur.com/kCmSY.png" alt="enter image description here"></a></p>
3
2016-05-25T08:06:13Z
[ "python", "performance", "profiling", "time-complexity" ]
py2exe + sqlalchemy + sqlite problem
582,449
<p>I am playing around with getting some basic stuff to work in Python before i go into full speed dev mode. Here are the specifics:</p> <pre><code>Python 2.5.4 PyQt4 4.4.3 SqlAlchemy 0.5.2 py2exe 0.6.9 setuptools 0.6c9 pysqlite 2.5.1 </code></pre> <p>setup.py:</p> <pre><code>from distutils.core import setup import py2exe setup(windows=[{"script" : "main.py"}], options={"py2exe" : {"includes" : ["sip", "PyQt4.QtSql","sqlite3"],"packages":["sqlite3",]}}) </code></pre> <p>py2exe appears to generate the .exe file correctly, but when i execute dist/main.exe i get this in the main.exe.log</p> <pre><code>Traceback (most recent call last): File "main.py", line 18, in &lt;module&gt; File "main.py", line 14, in main File "db\manager.pyc", line 12, in __init__ File "sqlalchemy\engine\__init__.pyc", line 223, in create_engine File "sqlalchemy\engine\strategies.pyc", line 48, in create File "sqlalchemy\engine\url.pyc", line 91, in get_dialect ImportError: No module named sqlite </code></pre> <p>I've been googling my heart out, but can't seem to find any solutions to this. If i can't get this to work now, my hopes of using Python for this project will be dashed and i will start over using Ruby... (not that there is anything wrong with Ruby, i just wanted to use this project as a good way to teach myself Python)</p>
19
2009-02-24T16:28:11Z
582,520
<p>you need to include the sqlalchemy.databases.sqlite package</p> <pre><code>setup( windows=[{"script" : "main.py"}], options={"py2exe" : { "includes": ["sip", "PyQt4.QtSql"], "packages": ["sqlalchemy.databases.sqlite"] }}) </code></pre>
29
2009-02-24T16:49:55Z
[ "python", "sqlite", "sqlalchemy", "py2exe" ]
py2exe + sqlalchemy + sqlite problem
582,449
<p>I am playing around with getting some basic stuff to work in Python before i go into full speed dev mode. Here are the specifics:</p> <pre><code>Python 2.5.4 PyQt4 4.4.3 SqlAlchemy 0.5.2 py2exe 0.6.9 setuptools 0.6c9 pysqlite 2.5.1 </code></pre> <p>setup.py:</p> <pre><code>from distutils.core import setup import py2exe setup(windows=[{"script" : "main.py"}], options={"py2exe" : {"includes" : ["sip", "PyQt4.QtSql","sqlite3"],"packages":["sqlite3",]}}) </code></pre> <p>py2exe appears to generate the .exe file correctly, but when i execute dist/main.exe i get this in the main.exe.log</p> <pre><code>Traceback (most recent call last): File "main.py", line 18, in &lt;module&gt; File "main.py", line 14, in main File "db\manager.pyc", line 12, in __init__ File "sqlalchemy\engine\__init__.pyc", line 223, in create_engine File "sqlalchemy\engine\strategies.pyc", line 48, in create File "sqlalchemy\engine\url.pyc", line 91, in get_dialect ImportError: No module named sqlite </code></pre> <p>I've been googling my heart out, but can't seem to find any solutions to this. If i can't get this to work now, my hopes of using Python for this project will be dashed and i will start over using Ruby... (not that there is anything wrong with Ruby, i just wanted to use this project as a good way to teach myself Python)</p>
19
2009-02-24T16:28:11Z
5,103,508
<p>you need change to sqlalchemy.dialects.sqlite package</p> <p>setup( windows=[{"script" : "main.py"}], options={"py2exe" : { "includes": ["sip", "PyQt4.QtSql"], "packages": ["sqlalchemy.dialects.sqlite"] }})</p>
5
2011-02-24T10:43:19Z
[ "python", "sqlite", "sqlalchemy", "py2exe" ]
How to import classes defined in __init__.py
582,723
<p>I am trying to organize some modules for my own use. I have something like this:</p> <pre><code>lib/ __init__.py settings.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py </code></pre> <p>In <code>lib/__init__.py</code>, I want to define some classes to be used if I import lib. However, I can't seem to figure it out without separating the classes into files, and import them in<code> __init__.py</code>. </p> <p>Rather than say:</p> <pre><code> lib/ __init__.py settings.py helperclass.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py from lib.settings import Values from lib.helperclass import Helper </code></pre> <p>I want something like this:</p> <pre><code> lib/ __init__.py #Helper defined in this file settings.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py from lib.settings import Values from lib import Helper </code></pre> <p>Is it possible, or do I have to separate the class into another file?</p> <h2>EDIT</h2> <p>OK, if I import lib from another script, I can access the Helper class. How can I access the Helper class from settings.py?</p> <p>The example <a href="http://docs.python.org/tutorial/modules.html">here</a> describes Intra-Package References. I quote "submodules often need to refer to each other". In my case, the lib.settings.py needs the Helper and lib.foo.someobject need access to Helper, so where should I define the Helper class?</p>
46
2009-02-24T17:35:55Z
582,752
<p>Edit, since i misunderstood the question:</p> <p>Just put the <code>Helper</code> class in <code>__init__.py</code>. Thats perfectly pythonic. It just feels strange coming from languages like Java.</p>
4
2009-02-24T17:42:24Z
[ "python", "packages" ]
How to import classes defined in __init__.py
582,723
<p>I am trying to organize some modules for my own use. I have something like this:</p> <pre><code>lib/ __init__.py settings.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py </code></pre> <p>In <code>lib/__init__.py</code>, I want to define some classes to be used if I import lib. However, I can't seem to figure it out without separating the classes into files, and import them in<code> __init__.py</code>. </p> <p>Rather than say:</p> <pre><code> lib/ __init__.py settings.py helperclass.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py from lib.settings import Values from lib.helperclass import Helper </code></pre> <p>I want something like this:</p> <pre><code> lib/ __init__.py #Helper defined in this file settings.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py from lib.settings import Values from lib import Helper </code></pre> <p>Is it possible, or do I have to separate the class into another file?</p> <h2>EDIT</h2> <p>OK, if I import lib from another script, I can access the Helper class. How can I access the Helper class from settings.py?</p> <p>The example <a href="http://docs.python.org/tutorial/modules.html">here</a> describes Intra-Package References. I quote "submodules often need to refer to each other". In my case, the lib.settings.py needs the Helper and lib.foo.someobject need access to Helper, so where should I define the Helper class?</p>
46
2009-02-24T17:35:55Z
582,753
<p>You just put them in __init__.py.</p> <p>So with test/classes.py being:</p> <pre><code>class A(object): pass class B(object): pass </code></pre> <p>... and test/__init__.py being:</p> <pre><code>from classes import * class Helper(object): pass </code></pre> <p>You can import test and have access to A, B and Helper</p> <pre><code>&gt;&gt;&gt; import test &gt;&gt;&gt; test.A &lt;class 'test.classes.A'&gt; &gt;&gt;&gt; test.B &lt;class 'test.classes.B'&gt; &gt;&gt;&gt; test.Helper &lt;class 'test.Helper'&gt; </code></pre>
3
2009-02-24T17:42:59Z
[ "python", "packages" ]
How to import classes defined in __init__.py
582,723
<p>I am trying to organize some modules for my own use. I have something like this:</p> <pre><code>lib/ __init__.py settings.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py </code></pre> <p>In <code>lib/__init__.py</code>, I want to define some classes to be used if I import lib. However, I can't seem to figure it out without separating the classes into files, and import them in<code> __init__.py</code>. </p> <p>Rather than say:</p> <pre><code> lib/ __init__.py settings.py helperclass.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py from lib.settings import Values from lib.helperclass import Helper </code></pre> <p>I want something like this:</p> <pre><code> lib/ __init__.py #Helper defined in this file settings.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py from lib.settings import Values from lib import Helper </code></pre> <p>Is it possible, or do I have to separate the class into another file?</p> <h2>EDIT</h2> <p>OK, if I import lib from another script, I can access the Helper class. How can I access the Helper class from settings.py?</p> <p>The example <a href="http://docs.python.org/tutorial/modules.html">here</a> describes Intra-Package References. I quote "submodules often need to refer to each other". In my case, the lib.settings.py needs the Helper and lib.foo.someobject need access to Helper, so where should I define the Helper class?</p>
46
2009-02-24T17:35:55Z
582,777
<p>Yes, it is possible. You might also want to define <code>__all__</code> in <code>__init__.py</code> files. It's a list of modules that will be imported when you do </p> <pre><code>from lib import * </code></pre>
1
2009-02-24T17:49:28Z
[ "python", "packages" ]
How to import classes defined in __init__.py
582,723
<p>I am trying to organize some modules for my own use. I have something like this:</p> <pre><code>lib/ __init__.py settings.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py </code></pre> <p>In <code>lib/__init__.py</code>, I want to define some classes to be used if I import lib. However, I can't seem to figure it out without separating the classes into files, and import them in<code> __init__.py</code>. </p> <p>Rather than say:</p> <pre><code> lib/ __init__.py settings.py helperclass.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py from lib.settings import Values from lib.helperclass import Helper </code></pre> <p>I want something like this:</p> <pre><code> lib/ __init__.py #Helper defined in this file settings.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py from lib.settings import Values from lib import Helper </code></pre> <p>Is it possible, or do I have to separate the class into another file?</p> <h2>EDIT</h2> <p>OK, if I import lib from another script, I can access the Helper class. How can I access the Helper class from settings.py?</p> <p>The example <a href="http://docs.python.org/tutorial/modules.html">here</a> describes Intra-Package References. I quote "submodules often need to refer to each other". In my case, the lib.settings.py needs the Helper and lib.foo.someobject need access to Helper, so where should I define the Helper class?</p>
46
2009-02-24T17:35:55Z
583,065
<ol> <li><p>'<code>lib/</code>'s parent directory must be in <code>sys.path</code>. </p></li> <li><p>Your '<code>lib/__init__.py</code>' might look like this:</p> <pre><code>from . import settings # or just 'import settings' on old Python versions class Helper(object): pass </code></pre></li> </ol> <p>Then the following example should work:</p> <pre><code>from lib.settings import Values from lib import Helper </code></pre> <h3>Answer to the edited version of the question:</h3> <p><code>__init__.py</code> defines how your package looks from outside. If you need to use <code>Helper</code> in <code>settings.py</code> then define <code>Helper</code> in a different file e.g., '<code>lib/helper.py</code>'.</p> <pre> . | `-- import_submodule.py `-- lib |-- __init__.py |-- foo | |-- __init__.py | `-- someobject.py |-- helper.py `-- settings.py 2 directories, 6 files </pre> <p>The command:</p> <pre><code>$ python import_submodule.py </code></pre> <p>Output:</p> <pre><code>settings helper Helper in lib.settings someobject Helper in lib.foo.someobject # ./import_submodule.py import fnmatch, os from lib.settings import Values from lib import Helper print for root, dirs, files in os.walk('.'): for f in fnmatch.filter(files, '*.py'): print "# %s/%s" % (os.path.basename(root), f) print open(os.path.join(root, f)).read() print # lib/helper.py print 'helper' class Helper(object): def __init__(self, module_name): print "Helper in", module_name # lib/settings.py print "settings" import helper class Values(object): pass helper.Helper(__name__) # lib/__init__.py #from __future__ import absolute_import import settings, foo.someobject, helper Helper = helper.Helper # foo/someobject.py print "someobject" from .. import helper helper.Helper(__name__) # foo/__init__.py import someobject </code></pre>
36
2009-02-24T18:52:35Z
[ "python", "packages" ]
How to import classes defined in __init__.py
582,723
<p>I am trying to organize some modules for my own use. I have something like this:</p> <pre><code>lib/ __init__.py settings.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py </code></pre> <p>In <code>lib/__init__.py</code>, I want to define some classes to be used if I import lib. However, I can't seem to figure it out without separating the classes into files, and import them in<code> __init__.py</code>. </p> <p>Rather than say:</p> <pre><code> lib/ __init__.py settings.py helperclass.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py from lib.settings import Values from lib.helperclass import Helper </code></pre> <p>I want something like this:</p> <pre><code> lib/ __init__.py #Helper defined in this file settings.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py from lib.settings import Values from lib import Helper </code></pre> <p>Is it possible, or do I have to separate the class into another file?</p> <h2>EDIT</h2> <p>OK, if I import lib from another script, I can access the Helper class. How can I access the Helper class from settings.py?</p> <p>The example <a href="http://docs.python.org/tutorial/modules.html">here</a> describes Intra-Package References. I quote "submodules often need to refer to each other". In my case, the lib.settings.py needs the Helper and lib.foo.someobject need access to Helper, so where should I define the Helper class?</p>
46
2009-02-24T17:35:55Z
4,595,071
<p>Maybe this could work:</p> <pre><code>import __init__ as lib </code></pre>
-2
2011-01-04T15:09:22Z
[ "python", "packages" ]
How to import classes defined in __init__.py
582,723
<p>I am trying to organize some modules for my own use. I have something like this:</p> <pre><code>lib/ __init__.py settings.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py </code></pre> <p>In <code>lib/__init__.py</code>, I want to define some classes to be used if I import lib. However, I can't seem to figure it out without separating the classes into files, and import them in<code> __init__.py</code>. </p> <p>Rather than say:</p> <pre><code> lib/ __init__.py settings.py helperclass.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py from lib.settings import Values from lib.helperclass import Helper </code></pre> <p>I want something like this:</p> <pre><code> lib/ __init__.py #Helper defined in this file settings.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py from lib.settings import Values from lib import Helper </code></pre> <p>Is it possible, or do I have to separate the class into another file?</p> <h2>EDIT</h2> <p>OK, if I import lib from another script, I can access the Helper class. How can I access the Helper class from settings.py?</p> <p>The example <a href="http://docs.python.org/tutorial/modules.html">here</a> describes Intra-Package References. I quote "submodules often need to refer to each other". In my case, the lib.settings.py needs the Helper and lib.foo.someobject need access to Helper, so where should I define the Helper class?</p>
46
2009-02-24T17:35:55Z
24,011,827
<p>Add something like this to <code>lib/__init__.py</code></p> <p><code>from .helperclass import Helper</code></p> <p>now you can import it directly:</p> <p><code>from lib import Helper</code></p>
0
2014-06-03T09:39:20Z
[ "python", "packages" ]
How to import classes defined in __init__.py
582,723
<p>I am trying to organize some modules for my own use. I have something like this:</p> <pre><code>lib/ __init__.py settings.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py </code></pre> <p>In <code>lib/__init__.py</code>, I want to define some classes to be used if I import lib. However, I can't seem to figure it out without separating the classes into files, and import them in<code> __init__.py</code>. </p> <p>Rather than say:</p> <pre><code> lib/ __init__.py settings.py helperclass.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py from lib.settings import Values from lib.helperclass import Helper </code></pre> <p>I want something like this:</p> <pre><code> lib/ __init__.py #Helper defined in this file settings.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py from lib.settings import Values from lib import Helper </code></pre> <p>Is it possible, or do I have to separate the class into another file?</p> <h2>EDIT</h2> <p>OK, if I import lib from another script, I can access the Helper class. How can I access the Helper class from settings.py?</p> <p>The example <a href="http://docs.python.org/tutorial/modules.html">here</a> describes Intra-Package References. I quote "submodules often need to refer to each other". In my case, the lib.settings.py needs the Helper and lib.foo.someobject need access to Helper, so where should I define the Helper class?</p>
46
2009-02-24T17:35:55Z
31,141,079
<p>If <code>lib/__init__.py</code> defines the Helper class then in settings.py you can use:</p> <pre><code>from . import Helper </code></pre> <p>This works because . is the current directory, and acts as a synonym for the lib package from the point of view of the settings module. Note that it is not necessary to export Helper via <code>__all__</code>.</p> <p>(Confirmed with python 2.7.10, running on Windows.)</p>
0
2015-06-30T14:27:43Z
[ "python", "packages" ]
Run a linux system command as a superuser, using a python script
583,216
<p>I have got postfix installed on my machine and I am updating virtual_alias on the fly programmatically(using python)(on some action). Once I update the entry in the /etc/postfix/virtual_alias, I am running the command:<pre><code>sudo /usr/sbin/postmap /etc/postfix/virtual_alias 2>>/work/postfix_valias_errorfile</code></pre>But I am getting the error:<pre><code>sudo: sorry, you must have a tty to run sudo</code></pre></p> <p>I want to run the mentioned sudo command in a non-human way(meaning, I am running this system command from a python script.). So how do I get this command run programmatically?</p>
15
2009-02-24T19:32:21Z
583,236
<pre><code>import os os.popen("sudo -S /etc/init.d/postifx reload", 'w').write("yourpassword") </code></pre> <p>This of course is almost always not a good idea as the password is in plain text.</p>
1
2009-02-24T19:38:21Z
[ "python", "linux", "sysadmin", "sudo", "root" ]
Run a linux system command as a superuser, using a python script
583,216
<p>I have got postfix installed on my machine and I am updating virtual_alias on the fly programmatically(using python)(on some action). Once I update the entry in the /etc/postfix/virtual_alias, I am running the command:<pre><code>sudo /usr/sbin/postmap /etc/postfix/virtual_alias 2>>/work/postfix_valias_errorfile</code></pre>But I am getting the error:<pre><code>sudo: sorry, you must have a tty to run sudo</code></pre></p> <p>I want to run the mentioned sudo command in a non-human way(meaning, I am running this system command from a python script.). So how do I get this command run programmatically?</p>
15
2009-02-24T19:32:21Z
583,239
<p>You can either run your python script as root itself - then you won't need to add privilege to reload postfix.</p> <p>Or you can configure sudo to not need a password for <code>/etc/init.d/postfix</code>.</p> <p>sudo configuration (via visudo) allows NOPASSWD: to allow the command without a password. See <a href="http://www.sudo.ws/sudo/man/sudoers.html#nopasswd%5Fand%5Fpasswd">http://www.sudo.ws/sudo/man/sudoers.html#nopasswd_and_passwd</a></p> <pre><code>&lt;username&gt; ALL = NOPASSWD: /etc/init.d/postfix </code></pre> <p>or something similar.</p>
18
2009-02-24T19:39:15Z
[ "python", "linux", "sysadmin", "sudo", "root" ]
Run a linux system command as a superuser, using a python script
583,216
<p>I have got postfix installed on my machine and I am updating virtual_alias on the fly programmatically(using python)(on some action). Once I update the entry in the /etc/postfix/virtual_alias, I am running the command:<pre><code>sudo /usr/sbin/postmap /etc/postfix/virtual_alias 2>>/work/postfix_valias_errorfile</code></pre>But I am getting the error:<pre><code>sudo: sorry, you must have a tty to run sudo</code></pre></p> <p>I want to run the mentioned sudo command in a non-human way(meaning, I am running this system command from a python script.). So how do I get this command run programmatically?</p>
15
2009-02-24T19:32:21Z
583,257
<pre><code>#include &lt;unistd.h&gt; #include &lt;stdlib.h&gt; // gcc -o reload_postfix reload_postfix.c // chown root reload_postfix // chmod +s reload_postfix int main( int argc, char **argv ) { setuid( geteuid() ); system("/etc/init.d/postifx reload"); } </code></pre> <p>Wrap your command in setuid-ed program. This will let any user restart postfix. You can of course further restrict the execute permission to certain groups.</p>
4
2009-02-24T19:43:44Z
[ "python", "linux", "sysadmin", "sudo", "root" ]
Run a linux system command as a superuser, using a python script
583,216
<p>I have got postfix installed on my machine and I am updating virtual_alias on the fly programmatically(using python)(on some action). Once I update the entry in the /etc/postfix/virtual_alias, I am running the command:<pre><code>sudo /usr/sbin/postmap /etc/postfix/virtual_alias 2>>/work/postfix_valias_errorfile</code></pre>But I am getting the error:<pre><code>sudo: sorry, you must have a tty to run sudo</code></pre></p> <p>I want to run the mentioned sudo command in a non-human way(meaning, I am running this system command from a python script.). So how do I get this command run programmatically?</p>
15
2009-02-24T19:32:21Z
618,831
<p>To answer the error:"sudo: sorry, you must have a tty to run sudo", we have a setting called "Defaults requiretty" in sudoers file. I tried commenting it out and it worked :D.</p>
3
2009-03-06T13:20:55Z
[ "python", "linux", "sysadmin", "sudo", "root" ]
Run a linux system command as a superuser, using a python script
583,216
<p>I have got postfix installed on my machine and I am updating virtual_alias on the fly programmatically(using python)(on some action). Once I update the entry in the /etc/postfix/virtual_alias, I am running the command:<pre><code>sudo /usr/sbin/postmap /etc/postfix/virtual_alias 2>>/work/postfix_valias_errorfile</code></pre>But I am getting the error:<pre><code>sudo: sorry, you must have a tty to run sudo</code></pre></p> <p>I want to run the mentioned sudo command in a non-human way(meaning, I am running this system command from a python script.). So how do I get this command run programmatically?</p>
15
2009-02-24T19:32:21Z
14,925,876
<p>if you're gonna do this in python you should just do the following:</p> <p>write this command before the line that you call the shell command</p> <pre><code>os.setuid(os.geteuid()) </code></pre> <p>then, you call the shell command without "sudo" prefix</p>
0
2013-02-17T20:46:23Z
[ "python", "linux", "sysadmin", "sudo", "root" ]
What is the best way to print a table with delimiters in Python
583,557
<p>I want to print a table mixed with string and float values, as tab delimited output printout. Sure I can get the job done:</p> <pre><code>&gt;&gt;&gt; tab = [['a', 1], ['b', 2]] &gt;&gt;&gt; for row in tab: ... out = "" ... for col in row: ... out = out + str(col) + "\t" ... print out.rstrip() ... a 1 b 2 </code></pre> <p>But I have a feeling there is a better way to do it in Python, at least to print each row with specified delimiter, if not the whole table. Little googling (from <a href="http://skymind.com/~ocrow/python_string/" rel="nofollow">here</a>) and it is already shorter:</p> <pre><code>&gt;&gt;&gt; for row in tab: ... print "\t".join([str(col) for col in row]) ... a 1 b 2 </code></pre> <p>Is there still a better, or more Python-ish, way to do it?</p>
4
2009-02-24T20:56:53Z
583,607
<p>I don't think it's going to get much better than your second code snippet... maybe, if you really want,</p> <pre><code>print "\n".join("\t".join(str(col) for col in row) for row in tab) </code></pre>
4
2009-02-24T21:05:20Z
[ "python", "coding-style" ]
What is the best way to print a table with delimiters in Python
583,557
<p>I want to print a table mixed with string and float values, as tab delimited output printout. Sure I can get the job done:</p> <pre><code>&gt;&gt;&gt; tab = [['a', 1], ['b', 2]] &gt;&gt;&gt; for row in tab: ... out = "" ... for col in row: ... out = out + str(col) + "\t" ... print out.rstrip() ... a 1 b 2 </code></pre> <p>But I have a feeling there is a better way to do it in Python, at least to print each row with specified delimiter, if not the whole table. Little googling (from <a href="http://skymind.com/~ocrow/python_string/" rel="nofollow">here</a>) and it is already shorter:</p> <pre><code>&gt;&gt;&gt; for row in tab: ... print "\t".join([str(col) for col in row]) ... a 1 b 2 </code></pre> <p>Is there still a better, or more Python-ish, way to do it?</p>
4
2009-02-24T20:56:53Z
583,757
<p>Your shorter solution would work well as something quick and dirty. But if you need to handle large amounts of data, it'd be better to use <code>csv</code> module:</p> <pre><code>import sys, csv writer = csv.writer(sys.stdout, delimiter="\t") writer.writerows(data) </code></pre> <p>The benefit of this solution is that you may easily customize all aspects of output format: delimiter, quotation, column headers, escape sequences...</p>
17
2009-02-24T21:47:41Z
[ "python", "coding-style" ]
What is the best way to print a table with delimiters in Python
583,557
<p>I want to print a table mixed with string and float values, as tab delimited output printout. Sure I can get the job done:</p> <pre><code>&gt;&gt;&gt; tab = [['a', 1], ['b', 2]] &gt;&gt;&gt; for row in tab: ... out = "" ... for col in row: ... out = out + str(col) + "\t" ... print out.rstrip() ... a 1 b 2 </code></pre> <p>But I have a feeling there is a better way to do it in Python, at least to print each row with specified delimiter, if not the whole table. Little googling (from <a href="http://skymind.com/~ocrow/python_string/" rel="nofollow">here</a>) and it is already shorter:</p> <pre><code>&gt;&gt;&gt; for row in tab: ... print "\t".join([str(col) for col in row]) ... a 1 b 2 </code></pre> <p>Is there still a better, or more Python-ish, way to do it?</p>
4
2009-02-24T20:56:53Z
583,764
<pre><code>import sys import csv writer = csv.writer(sys.stdout, dialect=csv.excel_tab) tab = [['a', 1], ['b', 2]] writer.writerows(tab) </code></pre>
2
2009-02-24T21:49:38Z
[ "python", "coding-style" ]
What is the best way to print a table with delimiters in Python
583,557
<p>I want to print a table mixed with string and float values, as tab delimited output printout. Sure I can get the job done:</p> <pre><code>&gt;&gt;&gt; tab = [['a', 1], ['b', 2]] &gt;&gt;&gt; for row in tab: ... out = "" ... for col in row: ... out = out + str(col) + "\t" ... print out.rstrip() ... a 1 b 2 </code></pre> <p>But I have a feeling there is a better way to do it in Python, at least to print each row with specified delimiter, if not the whole table. Little googling (from <a href="http://skymind.com/~ocrow/python_string/" rel="nofollow">here</a>) and it is already shorter:</p> <pre><code>&gt;&gt;&gt; for row in tab: ... print "\t".join([str(col) for col in row]) ... a 1 b 2 </code></pre> <p>Is there still a better, or more Python-ish, way to do it?</p>
4
2009-02-24T20:56:53Z
583,880
<p>Please do not use concatanation because it creates a new string every time. cStringIO.StringIO will do this kind of job much more efficiently.</p>
0
2009-02-24T22:20:30Z
[ "python", "coding-style" ]
What is the best way to print a table with delimiters in Python
583,557
<p>I want to print a table mixed with string and float values, as tab delimited output printout. Sure I can get the job done:</p> <pre><code>&gt;&gt;&gt; tab = [['a', 1], ['b', 2]] &gt;&gt;&gt; for row in tab: ... out = "" ... for col in row: ... out = out + str(col) + "\t" ... print out.rstrip() ... a 1 b 2 </code></pre> <p>But I have a feeling there is a better way to do it in Python, at least to print each row with specified delimiter, if not the whole table. Little googling (from <a href="http://skymind.com/~ocrow/python_string/" rel="nofollow">here</a>) and it is already shorter:</p> <pre><code>&gt;&gt;&gt; for row in tab: ... print "\t".join([str(col) for col in row]) ... a 1 b 2 </code></pre> <p>Is there still a better, or more Python-ish, way to do it?</p>
4
2009-02-24T20:56:53Z
584,602
<p>It depends on <em>why</em> you want to output like that, but if you just want to visually reference the data you might want to try the <a href="http://docs.python.org/library/pprint.html" rel="nofollow">pprint</a> module.</p> <pre><code>&gt;&gt;&gt; import pprint &gt;&gt;&gt; for item in tab: ... pprint.pprint(item, indent=4, depth=2) ... ['a', 1] ['b', 2] &gt;&gt;&gt; &gt;&gt;&gt; pprint.pprint(tab, indent=4, width=1, depth=2) [ [ 'a', 1], [ 'b', 2]] &gt;&gt;&gt; </code></pre>
0
2009-02-25T03:30:35Z
[ "python", "coding-style" ]
Django development server shutdown error
583,740
<p>Hey all, Whenever i shut down my development server (./manage.py runserver) with CTRL+c i get following message:</p> <pre><code>[24/Feb/2009 22:05:23] "GET /home/ HTTP/1.1" 200 1571 [24/Feb/2009 22:05:24] "GET /contact HTTP/1.1" 301 0 [24/Feb/2009 22:05:24] "GET /contact/ HTTP/1.1" 200 2377 ^C Error in atexit._run_exitfuncs: Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/logging/__init__.py", line 1354, in shutdown h.flush() TypeError: flush() takes exactly 2 arguments (1 given) Error in sys.exitfunc: Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/logging/__init__.py", line 1354, in shutdown h.flush() TypeError: flush() takes exactly 2 arguments (1 given) </code></pre> <p>I recently moved the project to another directory, but everything else works fine, so i don't know if that has anything to do with it ...</p> <p>If i just start the development server and then shut it down immediately, i do not see the error. Only when i click around some in the browser and then shut down the server...</p> <p>Can anyone point me in the right direction to sort this one out plz? </p> <p>Thanks in advance.</p>
3
2009-02-24T21:44:19Z
586,081
<p>It appears that you are using the Mac's default python install. I know this has been reputed to have odd issues from time to time. I would recommend install MacPython and installing Django into that python instance. </p>
2
2009-02-25T13:59:20Z
[ "python", "django" ]
Is it possible to generate and return a ZIP file with App Engine?
583,791
<p>I have a small project that would be perfect for Google App Engine. Implementing it hinges on the ability to generate a ZIP file and return it.</p> <p>Due to the distributed nature of App Engine, from what I can tell, the ZIP file couldn't be created "in-memory" in the traditional sense. It would basically have to be generated and and sent in a single request/response cycle.</p> <p>Does the Python zip module even exist in the App Engine environment?</p>
19
2009-02-24T21:56:09Z
583,806
<p>From <a href="http://code.google.com/appengine/docs/whatisgoogleappengine.html" rel="nofollow">What is Google App Engine</a>:</p> <blockquote> <p>You can upload other third-party libraries with your application, as long as they are implemented in pure Python and do not require any unsupported standard library modules.</p> </blockquote> <p>So, even if it doesn't exist by default you can (potentially) include it yourself. (I say <em>potentially</em> because I don't know if the Python zip library requires any "unsupported standard library modules".</p>
2
2009-02-24T22:02:14Z
[ "python", "google-app-engine", "zip", "in-memory" ]
Is it possible to generate and return a ZIP file with App Engine?
583,791
<p>I have a small project that would be perfect for Google App Engine. Implementing it hinges on the ability to generate a ZIP file and return it.</p> <p>Due to the distributed nature of App Engine, from what I can tell, the ZIP file couldn't be created "in-memory" in the traditional sense. It would basically have to be generated and and sent in a single request/response cycle.</p> <p>Does the Python zip module even exist in the App Engine environment?</p>
19
2009-02-24T21:56:09Z
583,819
<p><a href="http://docs.python.org/library/zipfile.html">zipfile</a> is available at appengine and reworked <a href="http://www.tareandshare.com/2008/09/28/Zip-Google-App-Engine-GAE/">example</a> follows:</p> <pre><code>from contextlib import closing from zipfile import ZipFile, ZIP_DEFLATED from google.appengine.ext import webapp from google.appengine.api import urlfetch def addResource(zfile, url, fname): # get the contents contents = urlfetch.fetch(url).content # write the contents to the zip file zfile.writestr(fname, contents) class OutZipfile(webapp.RequestHandler): def get(self): # Set up headers for browser to correctly recognize ZIP file self.response.headers['Content-Type'] ='application/zip' self.response.headers['Content-Disposition'] = \ 'attachment; filename="outfile.zip"' # compress files and emit them directly to HTTP response stream with closing(ZipFile(self.response.out, "w", ZIP_DEFLATED)) as outfile: # repeat this for every URL that should be added to the zipfile addResource(outfile, 'https://www.google.com/intl/en/policies/privacy/', 'privacy.html') addResource(outfile, 'https://www.google.com/intl/en/policies/terms/', 'terms.html') </code></pre>
32
2009-02-24T22:06:10Z
[ "python", "google-app-engine", "zip", "in-memory" ]
Is it possible to generate and return a ZIP file with App Engine?
583,791
<p>I have a small project that would be perfect for Google App Engine. Implementing it hinges on the ability to generate a ZIP file and return it.</p> <p>Due to the distributed nature of App Engine, from what I can tell, the ZIP file couldn't be created "in-memory" in the traditional sense. It would basically have to be generated and and sent in a single request/response cycle.</p> <p>Does the Python zip module even exist in the App Engine environment?</p>
19
2009-02-24T21:56:09Z
2,386,804
<pre><code>import zipfile import StringIO text = u"ABCDEFGHIJKLMNOPQRSTUVWXYVabcdefghijklmnopqqstuvweyxáéöüï东 廣 広 广 國 国 国 界" zipstream=StringIO.StringIO() file = zipfile.ZipFile(file=zipstream,compression=zipfile.ZIP_DEFLATED,mode="w") file.writestr("data.txt.zip",text.encode("utf-8")) file.close() zipstream.seek(0) self.response.headers['Content-Type'] ='application/zip' self.response.headers['Content-Disposition'] = 'attachment; filename="data.txt.zip"' self.response.out.write(zipstream.getvalue()) </code></pre>
9
2010-03-05T12:54:24Z
[ "python", "google-app-engine", "zip", "in-memory" ]
How does one enable authentication across a Django site, and transparently preserving any POST or GET data?
583,857
<p>Suppose someone is editing a HTML form, and their session times out, how can one have Django re-authenticate that individual without losing the content the user had entered into the form?</p> <p>The snippet <a href="http://www.djangosnippets.org/snippets/136/" rel="nofollow">Django Snippets: Require login across entire site</a> suggests how to do site-wide authentication, but I expect it will lose the GET component of the string (namely because request.path does not include it), and definitely lose the POST data.</p> <p>How can one preserve the POST and GET across those inconvenient timeouts. I find that finessed web-sites tend to handle this intelligently, and I'd like to be able to do it in Django (as would others, I imagine!).</p> <p>Thoughts would be appreciated. Thank you.</p>
4
2009-02-24T22:14:28Z
583,923
<p>Add <code>onsubmit</code> handler to all your forms that would check session via JS and prompt use to login before proceeding. This way form submit would not really happen before user is logged in again.</p> <p>And make sure you verify that logged in user stays the same across sessions.</p>
2
2009-02-24T22:33:18Z
[ "python", "django", "authentication", "wsgi", "middleware" ]
How does one enable authentication across a Django site, and transparently preserving any POST or GET data?
583,857
<p>Suppose someone is editing a HTML form, and their session times out, how can one have Django re-authenticate that individual without losing the content the user had entered into the form?</p> <p>The snippet <a href="http://www.djangosnippets.org/snippets/136/" rel="nofollow">Django Snippets: Require login across entire site</a> suggests how to do site-wide authentication, but I expect it will lose the GET component of the string (namely because request.path does not include it), and definitely lose the POST data.</p> <p>How can one preserve the POST and GET across those inconvenient timeouts. I find that finessed web-sites tend to handle this intelligently, and I'd like to be able to do it in Django (as would others, I imagine!).</p> <p>Thoughts would be appreciated. Thank you.</p>
4
2009-02-24T22:14:28Z
584,135
<p>It is not exactly Django-specific but HTTP (The Stateless) specific... In the case system ends in issuing Redirect while handling POST (switching to GET from original POST) and risking loosing data one should store the data somewhere (db, memcached, etc.) and make the key under which they are stored be carried through authentication (or other) process. </p> <p>The simplest is Cookie as requires zero-care about the key. The more difficult but more bullet-proof (against read-oly Cookie jars) is key in URL user is redirected to and consecutive relay from request to request (like SESSION in solution from almost decade ago).</p> <p>Upon finishing the authentication (or other process) data (and process interrupted) can be picked from datastore by the key passed (either from Cookies, or from GET request variable).</p>
2
2009-02-24T23:35:57Z
[ "python", "django", "authentication", "wsgi", "middleware" ]
How does one enable authentication across a Django site, and transparently preserving any POST or GET data?
583,857
<p>Suppose someone is editing a HTML form, and their session times out, how can one have Django re-authenticate that individual without losing the content the user had entered into the form?</p> <p>The snippet <a href="http://www.djangosnippets.org/snippets/136/" rel="nofollow">Django Snippets: Require login across entire site</a> suggests how to do site-wide authentication, but I expect it will lose the GET component of the string (namely because request.path does not include it), and definitely lose the POST data.</p> <p>How can one preserve the POST and GET across those inconvenient timeouts. I find that finessed web-sites tend to handle this intelligently, and I'd like to be able to do it in Django (as would others, I imagine!).</p> <p>Thoughts would be appreciated. Thank you.</p>
4
2009-02-24T22:14:28Z
584,499
<p>I have two suggestions.</p> <h2>Redirect/Middleware</h2> <p>Since you're already using middleware to handle the login requirement, you could modify this middleware. Or possibly, create another middleware class that is called after the login middleware. These ideas are intertwined so it may make more sense to modify the existing one.</p> <ol> <li>If not logged in, capture the GET and POST data in the middleware, and store it in the session</li> <li>If the user is authenticated, check for the value(s) set in #1. If they exist, modify request.GET and request.POST to reflect it, and delete the session data.</li> </ol> <p>I think this should work cleanly, and many people would find it useful. It'd be a great post on <a href="http://djangosnippets.org" rel="nofollow">djangosnippets.org</a>.</p> <h2>Ajax technique</h2> <p>This is less practical if you already have your form handling in place, but could create a better user experience. If you POST asynchronously, your Javascript handler could recognize a "login required" response code, and then display a popup dialog requesting login. On completion, the user could resubmit the form.</p>
3
2009-02-25T02:23:22Z
[ "python", "django", "authentication", "wsgi", "middleware" ]
How does one enable authentication across a Django site, and transparently preserving any POST or GET data?
583,857
<p>Suppose someone is editing a HTML form, and their session times out, how can one have Django re-authenticate that individual without losing the content the user had entered into the form?</p> <p>The snippet <a href="http://www.djangosnippets.org/snippets/136/" rel="nofollow">Django Snippets: Require login across entire site</a> suggests how to do site-wide authentication, but I expect it will lose the GET component of the string (namely because request.path does not include it), and definitely lose the POST data.</p> <p>How can one preserve the POST and GET across those inconvenient timeouts. I find that finessed web-sites tend to handle this intelligently, and I'd like to be able to do it in Django (as would others, I imagine!).</p> <p>Thoughts would be appreciated. Thank you.</p>
4
2009-02-24T22:14:28Z
585,515
<p>I don't like sessions in general, though I suppose with an authenticated site you are already using them so maybe the answers above fit into your approach.</p> <p>Without sessions, I'd do something similar to Daniels answer, i.e. catch the original POST/GET in the middleware, but I'd change the redirect to include the posted info.</p> <p>This is easier on GETs and normally is just the full GETstring encoded in a redirect component of the login url.</p> <p>For POSTs you can either convert to the get method which works fine for smaller forms but for bigger forms that would make the url too long, I'd do a rePOST, posting the data to a login form possibly encoded and storing it in a single hidden (almost like a .net viewstate actually)</p> <p>Doing this in django is tricky as you can't do a redirect, so I'd use the middleware to manually call the login view, and write to HttpResponse from there. EDIT After some more looking into this, apparently the magic admin side fo django has something similar already implemented, as found by <a href="http://www.hoboes.com/Mimsy/?ART=625" rel="nofollow">Jerry Stratton</a></p> <p>Looks like a good option. I'll try it out and feedback.</p>
0
2009-02-25T10:41:24Z
[ "python", "django", "authentication", "wsgi", "middleware" ]
PyGTK widget opacity
583,906
<p>Is there any way to set a widget's opacity in PyGTK?<br /> I know there's a function for windows:</p> <pre><code>gtk.Window.set_opacity(0.85) </code></pre> <p>but there seems to be no equivalent for arbitrary widgets.<br /> Anyone have any ideas?</p> <p>Thanks in advance for your help.</p>
0
2009-02-24T22:29:50Z
583,965
<p><a href="http://www.pygtk.org/docs/pygtk/class-gdkwindow.html#method-gdkwindow--set-opacity" rel="nofollow">From pygtk reference</a>:</p> <blockquote> <p>For setting up per-pixel alpha, see <code>gtk.gdk.Screen.get_rgba_colormap()</code>. For making non-toplevel windows translucent, see <code>gtk.gdk.Window.set_composited()</code>.</p> </blockquote>
3
2009-02-24T22:44:52Z
[ "python", "user-interface", "gtk", "pygtk" ]
PyGTK widget opacity
583,906
<p>Is there any way to set a widget's opacity in PyGTK?<br /> I know there's a function for windows:</p> <pre><code>gtk.Window.set_opacity(0.85) </code></pre> <p>but there seems to be no equivalent for arbitrary widgets.<br /> Anyone have any ideas?</p> <p>Thanks in advance for your help.</p>
0
2009-02-24T22:29:50Z
583,984
<p>It might also be worth looking into <a href="http://www.k-3d.org/gtkglext/Main%5FPage" rel="nofollow">pygtkglext</a> for fancier widget stuff.</p>
0
2009-02-24T22:52:24Z
[ "python", "user-interface", "gtk", "pygtk" ]
How would I make the output of this for loop into a string, into a variable?
583,986
<p>In this loop, I'm trying to take user input and continually put it in a list till they write "stop". When the loop is broken, the for loop prints out all of the li's.</p> <p>How would I take the output of the for loop and make it a string so that I can load it into a variable?</p> <pre><code>x = ([]) while True: item = raw_input('Enter List Text (e.g. &lt;li&gt;&lt;a href="#"&gt;LIST TEXT&lt;/a&gt;&lt;/li&gt;) (Enter "stop" to end loop):\n') if item == 'stop': print 'Loop Stopped.' break else: item = make_link(item) x.append(item) print 'List Item Added\n' for i in range(len(x)): print '&lt;li&gt;' + x[i] + '&lt;/li&gt;\n' </code></pre> <p>I want it to end up like this:</p> <p>Code:</p> <pre><code>print list_output </code></pre> <p>Output:</p> <pre><code>&lt;li&gt;Blah&lt;/li&gt; &lt;li&gt;Blah&lt;/li&gt; &lt;li&gt;etc.&lt;/li&gt; </code></pre>
0
2009-02-24T22:52:33Z
584,002
<p>In python, strings support a <code>join</code> method (conceptually the opposite of <code>split</code>) that allows you to join elements of a list (technically, of an iterable) together using the string. One very common use case is <code>', '.join(&lt;list&gt;)</code> to copy the elements of the list into a comma separated string.</p> <p>In your case, you probably want something like this:</p> <pre><code>list_output = ''.join('&lt;li&gt;' + item + '&lt;/li&gt;\n' for item in x) </code></pre> <p>If you want the elements of the list separated by newlines, but <em>no newline at the end of the string</em>, you can do this:</p> <pre><code>list_output = '\n'.join('&lt;li&gt;' + item + '&lt;/li&gt;' for item in x) </code></pre> <p>If you want to get really crazy, this might be the most efficient (although I don't recommend it):</p> <pre><code>list_output = '&lt;li&gt;' + '&lt;/li&gt;\n&lt;li&gt;'.join(item for item in x) + '&lt;/li&gt;\n' </code></pre>
2
2009-02-24T22:57:15Z
[ "python" ]
How would I make the output of this for loop into a string, into a variable?
583,986
<p>In this loop, I'm trying to take user input and continually put it in a list till they write "stop". When the loop is broken, the for loop prints out all of the li's.</p> <p>How would I take the output of the for loop and make it a string so that I can load it into a variable?</p> <pre><code>x = ([]) while True: item = raw_input('Enter List Text (e.g. &lt;li&gt;&lt;a href="#"&gt;LIST TEXT&lt;/a&gt;&lt;/li&gt;) (Enter "stop" to end loop):\n') if item == 'stop': print 'Loop Stopped.' break else: item = make_link(item) x.append(item) print 'List Item Added\n' for i in range(len(x)): print '&lt;li&gt;' + x[i] + '&lt;/li&gt;\n' </code></pre> <p>I want it to end up like this:</p> <p>Code:</p> <pre><code>print list_output </code></pre> <p>Output:</p> <pre><code>&lt;li&gt;Blah&lt;/li&gt; &lt;li&gt;Blah&lt;/li&gt; &lt;li&gt;etc.&lt;/li&gt; </code></pre>
0
2009-02-24T22:52:33Z
584,010
<pre><code>s = "\n".join(['&lt;li&gt;' + i + '&lt;/li&gt;' for i in x]) </code></pre>
2
2009-02-24T22:58:37Z
[ "python" ]
How would I make the output of this for loop into a string, into a variable?
583,986
<p>In this loop, I'm trying to take user input and continually put it in a list till they write "stop". When the loop is broken, the for loop prints out all of the li's.</p> <p>How would I take the output of the for loop and make it a string so that I can load it into a variable?</p> <pre><code>x = ([]) while True: item = raw_input('Enter List Text (e.g. &lt;li&gt;&lt;a href="#"&gt;LIST TEXT&lt;/a&gt;&lt;/li&gt;) (Enter "stop" to end loop):\n') if item == 'stop': print 'Loop Stopped.' break else: item = make_link(item) x.append(item) print 'List Item Added\n' for i in range(len(x)): print '&lt;li&gt;' + x[i] + '&lt;/li&gt;\n' </code></pre> <p>I want it to end up like this:</p> <p>Code:</p> <pre><code>print list_output </code></pre> <p>Output:</p> <pre><code>&lt;li&gt;Blah&lt;/li&gt; &lt;li&gt;Blah&lt;/li&gt; &lt;li&gt;etc.&lt;/li&gt; </code></pre>
0
2009-02-24T22:52:33Z
584,016
<p>Replace your for loop at the bottom with the following:</p> <pre><code>list_output="" for aLine in x: list_output += '&lt;li&gt;'+aLine+'&lt;/li&gt;\n' </code></pre> <p>Note also that since x is a list, Python lets you iterate through the elements of the list instead of having to iterate on an index variable that is then used to lookup elements in the list.</p>
0
2009-02-24T22:59:51Z
[ "python" ]
How would I make the output of this for loop into a string, into a variable?
583,986
<p>In this loop, I'm trying to take user input and continually put it in a list till they write "stop". When the loop is broken, the for loop prints out all of the li's.</p> <p>How would I take the output of the for loop and make it a string so that I can load it into a variable?</p> <pre><code>x = ([]) while True: item = raw_input('Enter List Text (e.g. &lt;li&gt;&lt;a href="#"&gt;LIST TEXT&lt;/a&gt;&lt;/li&gt;) (Enter "stop" to end loop):\n') if item == 'stop': print 'Loop Stopped.' break else: item = make_link(item) x.append(item) print 'List Item Added\n' for i in range(len(x)): print '&lt;li&gt;' + x[i] + '&lt;/li&gt;\n' </code></pre> <p>I want it to end up like this:</p> <p>Code:</p> <pre><code>print list_output </code></pre> <p>Output:</p> <pre><code>&lt;li&gt;Blah&lt;/li&gt; &lt;li&gt;Blah&lt;/li&gt; &lt;li&gt;etc.&lt;/li&gt; </code></pre>
0
2009-02-24T22:52:33Z
584,037
<pre><code>list_output = "&lt;li&gt;%s&lt;/li&gt;\n" * len(x) % tuple(x) </code></pre>
1
2009-02-24T23:04:17Z
[ "python" ]
How would I make the output of this for loop into a string, into a variable?
583,986
<p>In this loop, I'm trying to take user input and continually put it in a list till they write "stop". When the loop is broken, the for loop prints out all of the li's.</p> <p>How would I take the output of the for loop and make it a string so that I can load it into a variable?</p> <pre><code>x = ([]) while True: item = raw_input('Enter List Text (e.g. &lt;li&gt;&lt;a href="#"&gt;LIST TEXT&lt;/a&gt;&lt;/li&gt;) (Enter "stop" to end loop):\n') if item == 'stop': print 'Loop Stopped.' break else: item = make_link(item) x.append(item) print 'List Item Added\n' for i in range(len(x)): print '&lt;li&gt;' + x[i] + '&lt;/li&gt;\n' </code></pre> <p>I want it to end up like this:</p> <p>Code:</p> <pre><code>print list_output </code></pre> <p>Output:</p> <pre><code>&lt;li&gt;Blah&lt;/li&gt; &lt;li&gt;Blah&lt;/li&gt; &lt;li&gt;etc.&lt;/li&gt; </code></pre>
0
2009-02-24T22:52:33Z
584,070
<p>I hate to be the person to answer a different question, but hand-coded HTML generation makes me feel ill. Even if you're doing nothing more than this super-simple list generation, I'd strongly recommend looking at a templating language like <a href="http://genshi.edgewall.org/" rel="nofollow">Genshi</a>.</p> <p>A Genshi version of your program (a little longer, but way, way nicer):</p> <pre><code>from genshi.template import MarkupTemplate TMPL = '''&lt;html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/"&gt; &lt;li py:for="item in items"&gt;$item&lt;/li&gt; &lt;/html&gt;''' make_link = lambda x: x item, x = None, [] while True: item = raw_input('Enter List Text (Enter "stop" to end loop):\n') if item == 'stop': break x.append(make_link(item)) print 'List Item Added\n' template = MarkupTemplate(TMPL) stream = template.generate(items = x) print stream.render() </code></pre>
2
2009-02-24T23:12:51Z
[ "python" ]
tkinter - set geometry without showing window
584,127
<p>I'm trying to line up some label and canvas widgets. To do so I need to know how wide my label boxes are. I'd like my widget to auto-adjust if the user changes the system font size, so I don't want to hard code 12 pixels per character. If I measure the label widget it's always 1 pixel wide. Until I call .update(), then I get the correct value. But .update() puts a window onscreen with my label, said window then goes away when I finally pack my final widgets. But this causes an unwelcome flash when I first put up the widget.</p> <p>So, how can I measure a label widget without .update()'ing it? Or how can I .update() a widget without having it display onscreen? I'm using Python if it matters.</p>
2
2009-02-24T23:32:56Z
585,800
<p>Withdraw the window before calling update. The command you want is wm_withdraw</p> <pre><code>root = Tk() root.wm_withdraw() &lt;your code here&gt; root.wm_deiconify() </code></pre> <p>However, if your real problem is lining up widgets you usually don't need to know the size of widgets. Use the grid geometry manager. Get out a piece of graph paper and lay your widgets out on it. Feel free to span as many squares as necessary for each widget. The design can then translate easily to a series of grid calls.</p>
1
2009-02-25T12:32:15Z
[ "python", "tkinter" ]
Problems on select module on Python 2.5
584,575
<p>I have an application in Python 2.5 that listens to a beanstalk queue. It works fine on all machines I tested so far, except from my newly acquired MacBook Pro. </p> <p>On that computer, when I try to run it I get this error:</p> <pre><code>Traceback (most recent call last): File "jobs.py", line 181, in &lt;module&gt; Jobs().start() File "jobs.py", line 154, in start self.jobQueue = Queue() File "src/utils/queue.py", line 16, in __init__ self.connection = serverconn.ServerConn(self.server, self.port) File "src/beanstalk/serverconn.py", line 25, in __init__ self.poller = select.poll() AttributeError: 'module' object has no attribute 'poll' </code></pre> <p>The serverconn.py has the following imports:</p> <pre><code>import socket, select </code></pre> <p>And when I try to run it from command line, it fails as well:</p> <pre><code>Python 2.5.1 (r251:54863, Jul 23 2008, 11:00:16) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import select &gt;&gt;&gt; select.poll() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'module' object has no attribute 'poll' </code></pre> <p>Do you have any idea on what can be happening?</p> <p>PS: Even though I am pretty confident it's not a source problem, if you need some background on the source that's failing, it's available at http://pastie.org/399342.</p> <p><em>Updated:</em> since the first answer I got speculates whether select.poll() is or not supported on Mac OS, but I have an iMac too and with the exact same OS version and it works fine:</p> <pre><code>2009-02-25 00:27:10,067 - Queue - DEBUG - Connecting to BeansTalk daemon @ localhost:11300 </code></pre>
3
2009-02-25T03:12:49Z
584,585
<p><a href="http://docs.python.org/library/select.html?highlight=select#select.poll" rel="nofollow"><strong>select.poll()</strong></a></p> <p>(<em>Not supported by all operating systems.</em>) Returns a polling object, which supports registering and unregistering file descriptors, and then polling them for I/O events; see section Polling Objects below for the methods supported by polling objects.</p> <p>My guess is that it's not supported on the macOS.</p>
0
2009-02-25T03:16:17Z
[ "python", "osx", "beanstalkd" ]
Problems on select module on Python 2.5
584,575
<p>I have an application in Python 2.5 that listens to a beanstalk queue. It works fine on all machines I tested so far, except from my newly acquired MacBook Pro. </p> <p>On that computer, when I try to run it I get this error:</p> <pre><code>Traceback (most recent call last): File "jobs.py", line 181, in &lt;module&gt; Jobs().start() File "jobs.py", line 154, in start self.jobQueue = Queue() File "src/utils/queue.py", line 16, in __init__ self.connection = serverconn.ServerConn(self.server, self.port) File "src/beanstalk/serverconn.py", line 25, in __init__ self.poller = select.poll() AttributeError: 'module' object has no attribute 'poll' </code></pre> <p>The serverconn.py has the following imports:</p> <pre><code>import socket, select </code></pre> <p>And when I try to run it from command line, it fails as well:</p> <pre><code>Python 2.5.1 (r251:54863, Jul 23 2008, 11:00:16) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import select &gt;&gt;&gt; select.poll() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'module' object has no attribute 'poll' </code></pre> <p>Do you have any idea on what can be happening?</p> <p>PS: Even though I am pretty confident it's not a source problem, if you need some background on the source that's failing, it's available at http://pastie.org/399342.</p> <p><em>Updated:</em> since the first answer I got speculates whether select.poll() is or not supported on Mac OS, but I have an iMac too and with the exact same OS version and it works fine:</p> <pre><code>2009-02-25 00:27:10,067 - Queue - DEBUG - Connecting to BeansTalk daemon @ localhost:11300 </code></pre>
3
2009-02-25T03:12:49Z
584,684
<p>I think your answer is here</p> <p><a href="http://atomized.org/2008/12/python-on-os-x-leopard-lacks-selectpoll/" rel="nofollow">http://atomized.org/2008/12/python-on-os-x-leopard-lacks-selectpoll/</a></p>
2
2009-02-25T04:07:01Z
[ "python", "osx", "beanstalkd" ]
Problems on select module on Python 2.5
584,575
<p>I have an application in Python 2.5 that listens to a beanstalk queue. It works fine on all machines I tested so far, except from my newly acquired MacBook Pro. </p> <p>On that computer, when I try to run it I get this error:</p> <pre><code>Traceback (most recent call last): File "jobs.py", line 181, in &lt;module&gt; Jobs().start() File "jobs.py", line 154, in start self.jobQueue = Queue() File "src/utils/queue.py", line 16, in __init__ self.connection = serverconn.ServerConn(self.server, self.port) File "src/beanstalk/serverconn.py", line 25, in __init__ self.poller = select.poll() AttributeError: 'module' object has no attribute 'poll' </code></pre> <p>The serverconn.py has the following imports:</p> <pre><code>import socket, select </code></pre> <p>And when I try to run it from command line, it fails as well:</p> <pre><code>Python 2.5.1 (r251:54863, Jul 23 2008, 11:00:16) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import select &gt;&gt;&gt; select.poll() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'module' object has no attribute 'poll' </code></pre> <p>Do you have any idea on what can be happening?</p> <p>PS: Even though I am pretty confident it's not a source problem, if you need some background on the source that's failing, it's available at http://pastie.org/399342.</p> <p><em>Updated:</em> since the first answer I got speculates whether select.poll() is or not supported on Mac OS, but I have an iMac too and with the exact same OS version and it works fine:</p> <pre><code>2009-02-25 00:27:10,067 - Queue - DEBUG - Connecting to BeansTalk daemon @ localhost:11300 </code></pre>
3
2009-02-25T03:12:49Z
613,591
<p>use the <a href="http://www.macports.org/" rel="nofollow">MacPorts</a> version of <code>python</code> on your MBP. </p> <p>Mac OS X supports this. Apple stock Leopard <code>python 2.5.1</code> does not.</p> <p>you will want to download and install MacPorts if you have not already. FYI, I find <a href="http://porticus.alittledrop.com/" rel="nofollow">Porticus</a> to be an excellent GUI around MacPorts. </p> <p>here is a comparison of stock Leopard python vs. latest MacPorts python2.5...</p> <p><hr /></p> <p>Leopard python from Apple (python 2.5.1) - <strong><code>select.poll()</code> broken</strong></p> <pre><code>$ /usr/bin/python Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import socket, select &gt;&gt;&gt; select.poll() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'module' object has no attribute 'poll' &gt;&gt;&gt; </code></pre> <p>Macports (python 2.5.4) - <strong><code>select.poll()</code> works!</strong></p> <pre><code>$ /opt/local/bin/python2.5 Python 2.5.4 (r254:67916, Feb 3 2009, 21:40:31) [GCC 4.0.1 (Apple Inc. build 5488)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import socket, select &gt;&gt;&gt; select.poll() &lt;select.poll object at 0x11128&gt; &gt;&gt;&gt; </code></pre>
0
2009-03-05T04:41:29Z
[ "python", "osx", "beanstalkd" ]
Problems on select module on Python 2.5
584,575
<p>I have an application in Python 2.5 that listens to a beanstalk queue. It works fine on all machines I tested so far, except from my newly acquired MacBook Pro. </p> <p>On that computer, when I try to run it I get this error:</p> <pre><code>Traceback (most recent call last): File "jobs.py", line 181, in &lt;module&gt; Jobs().start() File "jobs.py", line 154, in start self.jobQueue = Queue() File "src/utils/queue.py", line 16, in __init__ self.connection = serverconn.ServerConn(self.server, self.port) File "src/beanstalk/serverconn.py", line 25, in __init__ self.poller = select.poll() AttributeError: 'module' object has no attribute 'poll' </code></pre> <p>The serverconn.py has the following imports:</p> <pre><code>import socket, select </code></pre> <p>And when I try to run it from command line, it fails as well:</p> <pre><code>Python 2.5.1 (r251:54863, Jul 23 2008, 11:00:16) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import select &gt;&gt;&gt; select.poll() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'module' object has no attribute 'poll' </code></pre> <p>Do you have any idea on what can be happening?</p> <p>PS: Even though I am pretty confident it's not a source problem, if you need some background on the source that's failing, it's available at http://pastie.org/399342.</p> <p><em>Updated:</em> since the first answer I got speculates whether select.poll() is or not supported on Mac OS, but I have an iMac too and with the exact same OS version and it works fine:</p> <pre><code>2009-02-25 00:27:10,067 - Queue - DEBUG - Connecting to BeansTalk daemon @ localhost:11300 </code></pre>
3
2009-02-25T03:12:49Z
5,124,744
<p>According to <a href="http://trac.macports.org/ticket/18376">this macports ticket</a> Apple's implementation of poll() is straight up broken. Apple worked around this by disabling poll() in Python and macports now disables poll in their Pythons as well. I think this means you need to look into Python's select.kevent() instead of poll on mac.</p>
6
2011-02-26T02:56:02Z
[ "python", "osx", "beanstalkd" ]
Determine if a listing is a directory or file in Python over FTP
584,865
<p>Python has a standard library module <code>ftplib</code> to run FTP communications. It has two means of getting a listing of directory contents. One, <code>FTP.nlst()</code>, will return a list of the contents of a directory given a directory name as an argument. (It will return the name of a file if given a file name instead.) This is a robust way to list the contents of a directory but does not give any indication whether each item in the list is a file or directory. The other method is <code>FTP.dir()</code>, which gives a string formatted listing of the directory contents of the directory given as an argument (or of the file attributes, given a file name).</p> <p>According to <a href="http://stackoverflow.com/questions/111954/using-pythons-ftplib-to-get-a-directory-listing-portably">a previous question on Stack Overflow</a>, parsing the results of <code>dir()</code> can be fragile (different servers may return different strings). I'm looking for some way to list just the directories contained within another directory over FTP, though. To the best of my knowledge, scraping for a <code>d</code> in the permissions part of the string is the only solution I've come up with, but I guess I can't guarantee that the permissions will appear in the same place between different servers. Is there a more robust solution to identifying directories over FTP?</p>
5
2009-02-25T05:54:36Z
585,232
<p>Unfortunately FTP doesn't have a command to list just folders so parsing the results you get from ftp.dir() would be 'best'.</p> <p>A simple app assuming a standard result from ls (not a windows ftp)</p> <pre><code>from ftplib import FTP ftp = FTP(host, user, passwd) for r in ftp.dir(): if r.upper().startswith('D'): print r[58:] # Starting point </code></pre> <p><a href="http://www.hiteksoftware.com/help/English/FtpCommands.htm#ftp%20commands">Standard FTP Commands</a></p> <p><a href="http://www.hiteksoftware.com/help/English/FtpCommands.htm#custom%20commands">Custom FTP Commands</a></p>
10
2009-02-25T09:04:16Z
[ "python", "ftp" ]
Determine if a listing is a directory or file in Python over FTP
584,865
<p>Python has a standard library module <code>ftplib</code> to run FTP communications. It has two means of getting a listing of directory contents. One, <code>FTP.nlst()</code>, will return a list of the contents of a directory given a directory name as an argument. (It will return the name of a file if given a file name instead.) This is a robust way to list the contents of a directory but does not give any indication whether each item in the list is a file or directory. The other method is <code>FTP.dir()</code>, which gives a string formatted listing of the directory contents of the directory given as an argument (or of the file attributes, given a file name).</p> <p>According to <a href="http://stackoverflow.com/questions/111954/using-pythons-ftplib-to-get-a-directory-listing-portably">a previous question on Stack Overflow</a>, parsing the results of <code>dir()</code> can be fragile (different servers may return different strings). I'm looking for some way to list just the directories contained within another directory over FTP, though. To the best of my knowledge, scraping for a <code>d</code> in the permissions part of the string is the only solution I've come up with, but I guess I can't guarantee that the permissions will appear in the same place between different servers. Is there a more robust solution to identifying directories over FTP?</p>
5
2009-02-25T05:54:36Z
3,114,604
<p>If the FTP server supports the <code>MLSD</code> command, then please check <a href="http://stackoverflow.com/questions/2867217/how-to-delete-files-with-a-python-script-from-a-ftp-server-which-are-older-than-7/3114477#3114477">that</a> answer for a couple of useful classes (<code>FTPDirectory</code> and <code>FTPTree</code>).</p>
1
2010-06-24T23:19:03Z
[ "python", "ftp" ]
Determine if a listing is a directory or file in Python over FTP
584,865
<p>Python has a standard library module <code>ftplib</code> to run FTP communications. It has two means of getting a listing of directory contents. One, <code>FTP.nlst()</code>, will return a list of the contents of a directory given a directory name as an argument. (It will return the name of a file if given a file name instead.) This is a robust way to list the contents of a directory but does not give any indication whether each item in the list is a file or directory. The other method is <code>FTP.dir()</code>, which gives a string formatted listing of the directory contents of the directory given as an argument (or of the file attributes, given a file name).</p> <p>According to <a href="http://stackoverflow.com/questions/111954/using-pythons-ftplib-to-get-a-directory-listing-portably">a previous question on Stack Overflow</a>, parsing the results of <code>dir()</code> can be fragile (different servers may return different strings). I'm looking for some way to list just the directories contained within another directory over FTP, though. To the best of my knowledge, scraping for a <code>d</code> in the permissions part of the string is the only solution I've come up with, but I guess I can't guarantee that the permissions will appear in the same place between different servers. Is there a more robust solution to identifying directories over FTP?</p>
5
2009-02-25T05:54:36Z
14,222,775
<p>Another way is to assume everything is a directory and try and change into it. If this succeeds it is a directory, but if this throws an ftplib.error_perm it is probably a file. You can catch then catch the exception. Sure, this isn't really the safest, but neither is parsing the crazy string for leading 'd's.</p> <p>Example</p> <pre><code>def processRecursive(ftp,directory): ftp.cwd(directory) #put whatever you want to do in each directory here #when you have called processRecursive with a file, #the command above will fail and you will return #get the files and directories contained in the current directory filenames = [] ftp.retrlines('NLST',filenames.append) for name in filenames: try: processRecursive(ftp,name) except ftplib.error_perm: #put whatever you want to do with files here #put whatever you want to do after processing the files #and sub-directories of a directory here </code></pre>
1
2013-01-08T19:41:06Z
[ "python", "ftp" ]
Database design of survey query system
585,006
<p>I am working on a so-called Behavioral Risk Factor Surveillance System (BRFSS), a web query system dealing with questionnaires coming every year. </p> <p>I had hard time in coming up with a suitable database design for it. Here is the problem: Each questionnaire contains about 80 questions, with demographic info, e.g. age, education, etc, and survey questions, e.g. smoking, health, etc. Every year, some questions change, some don't. Data source is an Excel file with 80+ columns. The system has to support queries like: </p> <pre><code>SELECT [question var], [demo var], count(*) FROM survey WHERE age in (...) AND educ in (...) [etc] GROUP BY &lt;question var&gt; </code></pre> <p>The data is read only, ie. never change once imported. So it does not have to be normalized too much. Intuitively, a spreadsheet-like table will do a good job wrt. speed and space. This becomes a problem, though, because questions will change, then we can't keep all the data in this table, which is necessary because of cross year queries. </p> <p>I tried normalize the responses into three tables: questions, responses, and response_values, which can support question variations. But then the response table spans over 98*14268 = 1,398,264 rows for one year! That's really huge. Query is slow like crazy! </p> <p>How should I design the database? Any help is appreciated! Thanks in advance!</p> <p>ps. I am using Python+Django+Sqlite. </p>
0
2009-02-25T07:04:33Z
585,009
<p>Have you checked <a href="http://www.databaseanswers.org/data%5Fmodels/index.htm" rel="nofollow">DatabaseAnswers</a> to see if there is a schema you could use as a starting point?</p>
6
2009-02-25T07:06:41Z
[ "python", "database", "django", "design", "sqlite" ]
Database design of survey query system
585,006
<p>I am working on a so-called Behavioral Risk Factor Surveillance System (BRFSS), a web query system dealing with questionnaires coming every year. </p> <p>I had hard time in coming up with a suitable database design for it. Here is the problem: Each questionnaire contains about 80 questions, with demographic info, e.g. age, education, etc, and survey questions, e.g. smoking, health, etc. Every year, some questions change, some don't. Data source is an Excel file with 80+ columns. The system has to support queries like: </p> <pre><code>SELECT [question var], [demo var], count(*) FROM survey WHERE age in (...) AND educ in (...) [etc] GROUP BY &lt;question var&gt; </code></pre> <p>The data is read only, ie. never change once imported. So it does not have to be normalized too much. Intuitively, a spreadsheet-like table will do a good job wrt. speed and space. This becomes a problem, though, because questions will change, then we can't keep all the data in this table, which is necessary because of cross year queries. </p> <p>I tried normalize the responses into three tables: questions, responses, and response_values, which can support question variations. But then the response table spans over 98*14268 = 1,398,264 rows for one year! That's really huge. Query is slow like crazy! </p> <p>How should I design the database? Any help is appreciated! Thanks in advance!</p> <p>ps. I am using Python+Django+Sqlite. </p>
0
2009-02-25T07:04:33Z
585,050
<p>Sounds like a case for a star schema.</p> <p>You would have a (huge) fact table like this:</p> <p>question_id, survey_id, age_group_id, health_classifier_id, is_smoking ... , answer_value</p> <p>and denormalised dimension tables:</p> <p>age_group: group_name, min_age, max_age, age_group_id</p> <p>1.4 million rows doesn't sound like much for a system like this. </p> <p>Some databases have special features to support querying on this kind of schema:</p> <p>On Oracle those would be:</p> <ul> <li>'dimensions' for supporting aggragation allong dimensions</li> <li>bitmap index for filtering on low cardinality attributes like age_group_id and is_smoking</li> <li>bitmap joind index for filtering on low cardinality attributes in a joined table, i.e. selecting from the fact table but filtering on min_age in the age_group table.</li> <li>partitioning tables to handle large tables</li> <li>materialized views for precalculating aggregation results</li> </ul> <p>There are also specialised db systems for this kind of data called multidimensional database.</p> <p>check if there are similiar constructs for your database or consider switching the database engine</p>
1
2009-02-25T07:29:34Z
[ "python", "database", "django", "design", "sqlite" ]
Database design of survey query system
585,006
<p>I am working on a so-called Behavioral Risk Factor Surveillance System (BRFSS), a web query system dealing with questionnaires coming every year. </p> <p>I had hard time in coming up with a suitable database design for it. Here is the problem: Each questionnaire contains about 80 questions, with demographic info, e.g. age, education, etc, and survey questions, e.g. smoking, health, etc. Every year, some questions change, some don't. Data source is an Excel file with 80+ columns. The system has to support queries like: </p> <pre><code>SELECT [question var], [demo var], count(*) FROM survey WHERE age in (...) AND educ in (...) [etc] GROUP BY &lt;question var&gt; </code></pre> <p>The data is read only, ie. never change once imported. So it does not have to be normalized too much. Intuitively, a spreadsheet-like table will do a good job wrt. speed and space. This becomes a problem, though, because questions will change, then we can't keep all the data in this table, which is necessary because of cross year queries. </p> <p>I tried normalize the responses into three tables: questions, responses, and response_values, which can support question variations. But then the response table spans over 98*14268 = 1,398,264 rows for one year! That's really huge. Query is slow like crazy! </p> <p>How should I design the database? Any help is appreciated! Thanks in advance!</p> <p>ps. I am using Python+Django+Sqlite. </p>
0
2009-02-25T07:04:33Z
585,051
<p>you need at least 3 tables:</p> <p>1) <code>Questions</code> which contains the text for each question, with autoincrement id key</p> <p>eg: (123, "What is the colour of your hair?")</p> <p>2) <code>Questionaires</code>, which map Q#'s onto questions.</p> <p>eg) question #10 on questionaire #3 maps on to question #123.</p> <p>3) <code>Answers</code>, which link each respondant with their questionaire and the data</p> <p>eg) Bob's response to question #10 on questionaire #3 is "brown".</p> <p>You should see how easy it is to add new questionaires using existing questions and adding new questions. Yes, there are going to be huge tables, but a good database engine should be able to handle 1M entries easily. You could use partitioning to make it more efficient, such as partition by year.</p> <p>I'll leave it as an exercise on how to convert this into sql.</p>
1
2009-02-25T07:29:39Z
[ "python", "database", "django", "design", "sqlite" ]
Database design of survey query system
585,006
<p>I am working on a so-called Behavioral Risk Factor Surveillance System (BRFSS), a web query system dealing with questionnaires coming every year. </p> <p>I had hard time in coming up with a suitable database design for it. Here is the problem: Each questionnaire contains about 80 questions, with demographic info, e.g. age, education, etc, and survey questions, e.g. smoking, health, etc. Every year, some questions change, some don't. Data source is an Excel file with 80+ columns. The system has to support queries like: </p> <pre><code>SELECT [question var], [demo var], count(*) FROM survey WHERE age in (...) AND educ in (...) [etc] GROUP BY &lt;question var&gt; </code></pre> <p>The data is read only, ie. never change once imported. So it does not have to be normalized too much. Intuitively, a spreadsheet-like table will do a good job wrt. speed and space. This becomes a problem, though, because questions will change, then we can't keep all the data in this table, which is necessary because of cross year queries. </p> <p>I tried normalize the responses into three tables: questions, responses, and response_values, which can support question variations. But then the response table spans over 98*14268 = 1,398,264 rows for one year! That's really huge. Query is slow like crazy! </p> <p>How should I design the database? Any help is appreciated! Thanks in advance!</p> <p>ps. I am using Python+Django+Sqlite. </p>
0
2009-02-25T07:04:33Z
586,449
<p>I've been also thinking after my post on stackoverflow. Here is how I can use the denormalized wide table (80+ columns) to support question changing every year and also aggregate cross tabulation. Please comment on. Thanks</p> <ol> <li><p>Create a new table for each year with the questions placed on columns e.g. </p> <p>id year age sex educ income ... smoke hiv drink ...</p></li> <li><p>Create two tables: Question and Query_Year, a many-to-many table Question_Year. Then we can populate a list of questions that are available for a specified year, and vice versa. </p></li> <li><p>Queries within one year is easy. And queries cross years, we can use a UNION operator. Since the questions should be compatible among the selected years, UNION is legitimate. e.g </p> <p>SELECT * FROM ( SELECT id, , , COUNT(*) FROM survey_2001 UNION ALL SELECT id, , , COUNT(*) FROM survey_2003 UNION ALL SELECT id, , , COUNT(*) FROM survey_2004 UNION ALL etc etc ) WHERE ( AGE in (...) AND EDUC in (...) AND etc etc ) GROUP BY , </p></li> </ol> <p>I suppose UNION is a relational operator which should not decrease the efficiency of a RDBMS. So it does not hurt if I combine many tables by union. The engine can also do some query analysis to boost the speed. </p> <p>I think this one is adequate and simple enough. Please comment on. Thanks! </p>
0
2009-02-25T15:26:02Z
[ "python", "database", "django", "design", "sqlite" ]
Find all strings in python code files
585,529
<p>I would like to list all strings within my large python project.</p> <p>Imagine the different possibilities to create a string in python:</p> <pre><code>mystring = "hello world" mystring = ("hello " "world") mystring = "hello " \ "world" </code></pre> <p>I need a tool that outputs "filename, linenumber, string" for each string in my project. Strings that are spread over multiple lines using "\" or "('')" should be shown in a single line.</p> <p>Any ideas how this could be done?</p>
6
2009-02-25T10:44:02Z
585,565
<p>If you can do this in Python, I'd suggest starting by looking at the <a href="http://docs.python.org/library/ast.html#module-ast" rel="nofollow">ast</a> (Abstract Syntax Tree) module, and going from there.</p>
3
2009-02-25T10:54:54Z
[ "python" ]
Find all strings in python code files
585,529
<p>I would like to list all strings within my large python project.</p> <p>Imagine the different possibilities to create a string in python:</p> <pre><code>mystring = "hello world" mystring = ("hello " "world") mystring = "hello " \ "world" </code></pre> <p>I need a tool that outputs "filename, linenumber, string" for each string in my project. Strings that are spread over multiple lines using "\" or "('')" should be shown in a single line.</p> <p>Any ideas how this could be done?</p>
6
2009-02-25T10:44:02Z
585,663
<p>Are you asking about the I18N utilities in Python?</p> <p><a href="http://docs.python.org/library/gettext.html#internationalizing-your-programs-and-modules" rel="nofollow">http://docs.python.org/library/gettext.html#internationalizing-your-programs-and-modules</a></p> <p>There's a utility called po-utils (formerly xpot) that can help with this.</p> <p><a href="http://po-utils.progiciels-bpi.ca/README.html" rel="nofollow">http://po-utils.progiciels-bpi.ca/README.html</a></p>
2
2009-02-25T11:41:28Z
[ "python" ]
Find all strings in python code files
585,529
<p>I would like to list all strings within my large python project.</p> <p>Imagine the different possibilities to create a string in python:</p> <pre><code>mystring = "hello world" mystring = ("hello " "world") mystring = "hello " \ "world" </code></pre> <p>I need a tool that outputs "filename, linenumber, string" for each string in my project. Strings that are spread over multiple lines using "\" or "('')" should be shown in a single line.</p> <p>Any ideas how this could be done?</p>
6
2009-02-25T10:44:02Z
585,710
<p><a href="http://docs.python.org/library/gettext.html" rel="nofollow">Gettext</a> might help you. Put your strings in <code>_(</code><strong>...</strong><code>)</code> structures:</p> <pre><code>a = _('Test') b = a c = _('Another text') </code></pre> <p>Then run in the shell prompt:</p> <pre><code>pygettext test.py </code></pre> <p>You'll get a <code>messages.pot</code> file with the information you need:</p> <pre><code># SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR ORGANIZATION # FIRST AUTHOR &lt;EMAIL@ADDRESS&gt;, YEAR. # msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "POT-Creation-Date: 2009-02-25 08:48+BRT\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME &lt;EMAIL@ADDRESS&gt;\n" "Language-Team: LANGUAGE &lt;LL@li.org&gt;\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=CHARSET\n" "Content-Transfer-Encoding: ENCODING\n" "Generated-By: pygettext.py 1.5\n" #: teste.py:1 msgid "Test" msgstr "" #: teste.py:3 msgid "Another text" msgstr "" </code></pre>
0
2009-02-25T12:00:29Z
[ "python" ]
Find all strings in python code files
585,529
<p>I would like to list all strings within my large python project.</p> <p>Imagine the different possibilities to create a string in python:</p> <pre><code>mystring = "hello world" mystring = ("hello " "world") mystring = "hello " \ "world" </code></pre> <p>I need a tool that outputs "filename, linenumber, string" for each string in my project. Strings that are spread over multiple lines using "\" or "('')" should be shown in a single line.</p> <p>Any ideas how this could be done?</p>
6
2009-02-25T10:44:02Z
585,780
<p>You may also consider to parse your code with <a href="http://pygments.org/" rel="nofollow">pygments.</a></p> <p>I don't know the other solution, but it sure is very simple to use.</p>
2
2009-02-25T12:24:21Z
[ "python" ]
Find all strings in python code files
585,529
<p>I would like to list all strings within my large python project.</p> <p>Imagine the different possibilities to create a string in python:</p> <pre><code>mystring = "hello world" mystring = ("hello " "world") mystring = "hello " \ "world" </code></pre> <p>I need a tool that outputs "filename, linenumber, string" for each string in my project. Strings that are spread over multiple lines using "\" or "('')" should be shown in a single line.</p> <p>Any ideas how this could be done?</p>
6
2009-02-25T10:44:02Z
585,884
<p>unwind's suggestion of using the ast module in 2.6 is a good one. (There's also the undocumented _ast module in 2.5.) Here's example code for that</p> <pre><code>code = """a = 'blah' b = '''multi line string''' c = u"spam" """ import ast root = ast.parse(code) class ShowStrings(ast.NodeVisitor): def visit_Str(self, node): print "string at", node.lineno, node.col_offset, repr(node.s) show_strings = ShowStrings() show_strings.visit(root) </code></pre> <p>The problem is multiline strings. If you run the above you'll get.</p> <pre><code>string at 1 4 'blah' string at 4 -1 'multi\nline\nstring' string at 5 4 u'spam' </code></pre> <p>You see that it doesn't report the start of the multiline string, only the end. There's no good solution for that using the builtin Python tools.</p> <p>Another option is that you can use my '<a href="http://dalkescientific.com/Python/python4ply.html" rel="nofollow">python4ply</a>' module. This is a grammar definition for Python for <a href="http://www.dabeaz.com/ply/" rel="nofollow">PLY</a>, which is a parser generator. Here's how you might use it:</p> <pre><code>import compiler import compiler.visitor # from python4ply; requires the ply parser generator import python_yacc code = """a = 'blah' b = '''multi line string''' c = u"spam" d = 1 """ tree = python_yacc.parse(code, "&lt;string&gt;") #print tree class ShowStrings(compiler.visitor.ASTVisitor): def visitConst(self, node): if isinstance(node.value, basestring): print "string at", node.lineno, repr(node.value) visitor = ShowStrings() compiler.walk(tree, visitor) </code></pre> <p>The output from this is</p> <pre><code>string at 1 'blah' string at 2 'multi\nline\nstring' string at 5 u'spam' </code></pre> <p>There's no support for column information. (There is some mostly complete commented out code to support that, but it's not fully tested.) Then again, I see you don't need it. It also means working with Python's 'compiler' module, which is clumsier than the AST module.</p> <p>Still, with a 30-40 lines of code you should have exactly what you want.</p>
11
2009-02-25T12:54:41Z
[ "python" ]
Find all strings in python code files
585,529
<p>I would like to list all strings within my large python project.</p> <p>Imagine the different possibilities to create a string in python:</p> <pre><code>mystring = "hello world" mystring = ("hello " "world") mystring = "hello " \ "world" </code></pre> <p>I need a tool that outputs "filename, linenumber, string" for each string in my project. Strings that are spread over multiple lines using "\" or "('')" should be shown in a single line.</p> <p>Any ideas how this could be done?</p>
6
2009-02-25T10:44:02Z
603,736
<p>Python's included <code>tokenize</code> module will also do the trick.</p> <pre><code>from __future__ import with_statement import sys import tokenize for filename in sys.argv[1:]: with open(filename) as f: for toktype, tokstr, (lineno, _), _, _ in tokenize.generate_tokens(f.readline): if toktype == tokenize.STRING: strrepr = repr(eval(tokstr)) print filename, lineno, strrepr </code></pre>
5
2009-03-02T19:58:12Z
[ "python" ]
About the optional argument in Canvas in PyS60
585,957
<p>In <a href="http://wiki.opensource.nokia.com/projects/PyS60" rel="nofollow">Python for Symbian60</a> blit() is defined as:</p> <p>blit(image [,target=(0,0), source=((0,0),image.size), mask=None, scale=0 ])</p> <p>In the optional parameter source what is the significance of image.size?</p>
0
2009-02-25T13:17:59Z
585,970
<p>My guess is that blit() will automatically use the result of <code>image.size</code> when you don't specify anything else (and thus blitting the whole image from (0,0) to (width,height)).</p> <p>If you want only a smaller part of the image copied, you can use the source parameter to define a different rectangle to copy.</p>
0
2009-02-25T13:22:22Z
[ "python", "nokia", "pys60" ]
About the optional argument in Canvas in PyS60
585,957
<p>In <a href="http://wiki.opensource.nokia.com/projects/PyS60" rel="nofollow">Python for Symbian60</a> blit() is defined as:</p> <p>blit(image [,target=(0,0), source=((0,0),image.size), mask=None, scale=0 ])</p> <p>In the optional parameter source what is the significance of image.size?</p>
0
2009-02-25T13:17:59Z
915,184
<p>Think that source=((0,0)) is the top left corner and image.size is the bottom right corner. You blit whatever is between those two points.</p> <p>Similar for target, btw.</p>
0
2009-05-27T11:18:58Z
[ "python", "nokia", "pys60" ]
What are good ways to upload bulk .csv data into a webapp using Django/Python?
586,517
<p>I have a very basic CSV file upload module working to bulk upload my user's data into my site. I process the CSV file in the backend with a python script that runs on crontab and then email the user the results of the bulk upload. This process works ok operationally, but my issue is with the format of the csv file. </p> <p>Are there good tools or even basic rules on how to accept different formats of the csv file? The user may have a different order of data columns, slightly different names for the column headers (I want the email column to be entitled "Email", but it may say "Primary Email", "Email Address"), or missing additional data columns. Any good examples of CSV upload functionality that is very permissive and user friendly?</p> <p>Also, how do I tell the user to export as CSV data? I'm importing address book information, so this data often comes from Outlook, Thunderbird, other software packages that have address books. Are there other popular data formats that I should accept?</p>
2
2009-02-25T15:39:46Z
586,579
<p>I would handle the random column header mapping in your script once it's uploaded. It's hard to make a "catch all" that would handle whatever the users might enter. I would have it evolve as you go and slowly build a list of one-one relations based on what your user uploads.</p> <p>Or!</p> <p>Check the column headers and make sure it's properly formatted and advise them how to fix it if it is not.</p> <blockquote> <p>"Primary Email" not recognized, our schema is "Email", "Address", "Phone", etc.</p> </blockquote> <p>You could also accept XML and this would allow you to create your own schema that they would have to adhere to. Check out <a href="http://www.xfront.com/files/tutorials.html" rel="nofollow">this tutorial</a>.</p>
1
2009-02-25T15:50:13Z
[ "jquery", "python", "django", "django-models", "csv" ]
What are good ways to upload bulk .csv data into a webapp using Django/Python?
586,517
<p>I have a very basic CSV file upload module working to bulk upload my user's data into my site. I process the CSV file in the backend with a python script that runs on crontab and then email the user the results of the bulk upload. This process works ok operationally, but my issue is with the format of the csv file. </p> <p>Are there good tools or even basic rules on how to accept different formats of the csv file? The user may have a different order of data columns, slightly different names for the column headers (I want the email column to be entitled "Email", but it may say "Primary Email", "Email Address"), or missing additional data columns. Any good examples of CSV upload functionality that is very permissive and user friendly?</p> <p>Also, how do I tell the user to export as CSV data? I'm importing address book information, so this data often comes from Outlook, Thunderbird, other software packages that have address books. Are there other popular data formats that I should accept?</p>
2
2009-02-25T15:39:46Z
586,582
<p>I'd check out Python's built-in csv module. Frankly a .replace() on your first row should cover your synonyms issue, and if you're using <a href="http://docs.python.org/library/csv.html#csv.DictReader" rel="nofollow">csv.DictReader</a> you should be able to deal with missing columns very easily:</p> <pre><code>my_dict_reader = csv.DictReader(somecsvfile) for row in my_dict_reader: SomeDBModel.address2=row.get('address2', None) </code></pre> <p>assuming you wanted to store a None value for missing fields.</p>
4
2009-02-25T15:50:32Z
[ "jquery", "python", "django", "django-models", "csv" ]
What are good ways to upload bulk .csv data into a webapp using Django/Python?
586,517
<p>I have a very basic CSV file upload module working to bulk upload my user's data into my site. I process the CSV file in the backend with a python script that runs on crontab and then email the user the results of the bulk upload. This process works ok operationally, but my issue is with the format of the csv file. </p> <p>Are there good tools or even basic rules on how to accept different formats of the csv file? The user may have a different order of data columns, slightly different names for the column headers (I want the email column to be entitled "Email", but it may say "Primary Email", "Email Address"), or missing additional data columns. Any good examples of CSV upload functionality that is very permissive and user friendly?</p> <p>Also, how do I tell the user to export as CSV data? I'm importing address book information, so this data often comes from Outlook, Thunderbird, other software packages that have address books. Are there other popular data formats that I should accept?</p>
2
2009-02-25T15:39:46Z
586,601
<p>You should force the first row to be the headers, make the user match up their headers to your field names on the next page, and remember that mapping for their future dumps.</p> <p>Whenever I do CSV imports the data really came from an Excel spreadsheet. I've been able to save time by using <a href="http://sourceforge.net/projects/pyexcelerator" rel="nofollow">pyexcelerator</a> to import the <code>.xls</code> directly. My <code>.csv</code> or <code>.xls</code> code is a generator that yields <code>{'field_name':'data', ...} </code> dictionaries that can be assigned to model objects.</p> <p>If you're doing address data, you should accept <a href="http://en.wikipedia.org/wiki/VCard" rel="nofollow">vCard</a>.</p>
3
2009-02-25T15:54:06Z
[ "jquery", "python", "django", "django-models", "csv" ]
What are good ways to upload bulk .csv data into a webapp using Django/Python?
586,517
<p>I have a very basic CSV file upload module working to bulk upload my user's data into my site. I process the CSV file in the backend with a python script that runs on crontab and then email the user the results of the bulk upload. This process works ok operationally, but my issue is with the format of the csv file. </p> <p>Are there good tools or even basic rules on how to accept different formats of the csv file? The user may have a different order of data columns, slightly different names for the column headers (I want the email column to be entitled "Email", but it may say "Primary Email", "Email Address"), or missing additional data columns. Any good examples of CSV upload functionality that is very permissive and user friendly?</p> <p>Also, how do I tell the user to export as CSV data? I'm importing address book information, so this data often comes from Outlook, Thunderbird, other software packages that have address books. Are there other popular data formats that I should accept?</p>
2
2009-02-25T15:39:46Z
586,622
<p>Take a look at this project: <a href="http://code.google.com/p/django-batchimport/" rel="nofollow">django-batchimport</a></p> <p>It might be overkill for you, but it can still give you some good ideas on improving your own code.</p> <p>Edit: also, ignore that it is only using xlrd for importing Excel. The base concepts are the same, just that you will use the csv module instead of xlrd.</p>
1
2009-02-25T15:59:24Z
[ "jquery", "python", "django", "django-models", "csv" ]
What are good ways to upload bulk .csv data into a webapp using Django/Python?
586,517
<p>I have a very basic CSV file upload module working to bulk upload my user's data into my site. I process the CSV file in the backend with a python script that runs on crontab and then email the user the results of the bulk upload. This process works ok operationally, but my issue is with the format of the csv file. </p> <p>Are there good tools or even basic rules on how to accept different formats of the csv file? The user may have a different order of data columns, slightly different names for the column headers (I want the email column to be entitled "Email", but it may say "Primary Email", "Email Address"), or missing additional data columns. Any good examples of CSV upload functionality that is very permissive and user friendly?</p> <p>Also, how do I tell the user to export as CSV data? I'm importing address book information, so this data often comes from Outlook, Thunderbird, other software packages that have address books. Are there other popular data formats that I should accept?</p>
2
2009-02-25T15:39:46Z
586,694
<p>If you'll copy excel table into clipboard and then paste results into notepad, you'll notice that it's tab separated. I once used it to make bulk import from most of table editors by copy-pasting data from the editor into textarea on html page.</p> <p>You can use a background for textarea as a hint for number of columns and place your headers at the top suggesting the order for a user. </p> <p>Javascript will process pasted data and display them to the user immediately with simple prevalidation making it easy to fix an error and repaste.</p> <p>Then import button is clicked, data is validated again and import results are displayed. Unfortunately, I've never heard any feedback about whenever this was easy to use or not.</p> <p>Anyway, I still see it as an option when implementing bulk import.</p>
1
2009-02-25T16:15:08Z
[ "jquery", "python", "django", "django-models", "csv" ]
What are good ways to upload bulk .csv data into a webapp using Django/Python?
586,517
<p>I have a very basic CSV file upload module working to bulk upload my user's data into my site. I process the CSV file in the backend with a python script that runs on crontab and then email the user the results of the bulk upload. This process works ok operationally, but my issue is with the format of the csv file. </p> <p>Are there good tools or even basic rules on how to accept different formats of the csv file? The user may have a different order of data columns, slightly different names for the column headers (I want the email column to be entitled "Email", but it may say "Primary Email", "Email Address"), or missing additional data columns. Any good examples of CSV upload functionality that is very permissive and user friendly?</p> <p>Also, how do I tell the user to export as CSV data? I'm importing address book information, so this data often comes from Outlook, Thunderbird, other software packages that have address books. Are there other popular data formats that I should accept?</p>
2
2009-02-25T15:39:46Z
588,212
<p>Look at <code>csv</code> module from stdlib. It contains presets for popualr CSV dialects like one produced by Excel.</p> <p>Reader class support field mapping and if file contains column header it coes not depend on column order. For more complex logic, like looking up several alternative names for a field, you'll need to write your own implementation.</p>
1
2009-02-25T22:29:30Z
[ "jquery", "python", "django", "django-models", "csv" ]
Python regular expression matching a multiline block of text
587,345
<p>I'm having a bit of trouble getting a Python regex to work when matching against text that spans multiple lines. The example text is ('\n' is a newline)</p> <pre><code>some Varying TEXT\n \n DSJFKDAFJKDAFJDSAKFJADSFLKDLAFKDSAF\n [more of the above, ending with a newline]\n [yep, there is a variable number of lines here]\n \n (repeat the above a few hundred times). </code></pre> <p>I'd like to capture two things: the 'some_Varying_TEXT' part, and all of the lines of uppercase text that comes two lines below it in one capture (i can strip out the newline characters later). I've tried with a few approaches:</p> <pre><code>re.compile(r"^&gt;(\w+)$$([.$]+)^$", re.MULTILINE) # try to capture both parts re.compile(r"(^[^&gt;][\w\s]+)$", re.MULTILINE|re.DOTALL) # just textlines </code></pre> <p>and a lot of variations hereof with no luck. The last one seems to match the lines of text one by one, which is not what I really want. I can catch the first part, no problem, but I can't seem to catch the 4-5 lines of uppercase text. I'd like match.group(1) to be some&#95;Varying&#95;Text and group(2) to be line1+line2+line3+etc until the empty line is encountered.</p> <p>If anyone's curious, its supposed to be a sequence of aminoacids that make up a protein.</p>
42
2009-02-25T19:00:49Z
587,389
<p>find:</p> <pre><code>^&gt;([^\n\r]+)[\n\r]([A-Z\n\r]+) </code></pre> <p>\1 = some_varying_text </p> <p>\2 = lines of all CAPS</p> <p><strong>Edit (proof that this works):</strong></p> <pre><code>text = """&gt; some_Varying_TEXT DSJFKDAFJKDAFJDSAKFJADSFLKDLAFKDSAF GATACAACATAGGATACA GGGGGAAAAAAAATTTTTTTTT CCCCAAAA &gt; some_Varying_TEXT2 DJASDFHKJFHKSDHF HHASGDFTERYTERE GAGAGAGAGAG PPPPPAAAAAAAAAAAAAAAP """ import re regex = re.compile(r'^&gt;([^\n\r]+)[\n\r]([A-Z\n\r]+)', re.MULTILINE) matches = [m.groups() for m in regex.finditer(text)] for m in matches: print 'Name: %s\nSequence:%s' % (m[0], m[1]) </code></pre>
1
2009-02-25T19:11:53Z
[ "python", "regex", "multiline" ]
Python regular expression matching a multiline block of text
587,345
<p>I'm having a bit of trouble getting a Python regex to work when matching against text that spans multiple lines. The example text is ('\n' is a newline)</p> <pre><code>some Varying TEXT\n \n DSJFKDAFJKDAFJDSAKFJADSFLKDLAFKDSAF\n [more of the above, ending with a newline]\n [yep, there is a variable number of lines here]\n \n (repeat the above a few hundred times). </code></pre> <p>I'd like to capture two things: the 'some_Varying_TEXT' part, and all of the lines of uppercase text that comes two lines below it in one capture (i can strip out the newline characters later). I've tried with a few approaches:</p> <pre><code>re.compile(r"^&gt;(\w+)$$([.$]+)^$", re.MULTILINE) # try to capture both parts re.compile(r"(^[^&gt;][\w\s]+)$", re.MULTILINE|re.DOTALL) # just textlines </code></pre> <p>and a lot of variations hereof with no luck. The last one seems to match the lines of text one by one, which is not what I really want. I can catch the first part, no problem, but I can't seem to catch the 4-5 lines of uppercase text. I'd like match.group(1) to be some&#95;Varying&#95;Text and group(2) to be line1+line2+line3+etc until the empty line is encountered.</p> <p>If anyone's curious, its supposed to be a sequence of aminoacids that make up a protein.</p>
42
2009-02-25T19:00:49Z
587,518
<p>This will work:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; rx_sequence=re.compile(r"^(.+?)\n\n((?:[A-Z]+\n)+)",re.MULTILINE) &gt;&gt;&gt; rx_blanks=re.compile(r"\W+") # to remove blanks and newlines &gt;&gt;&gt; text="""Some varying text1 ... ... AAABBBBBBCCCCCCDDDDDDD ... EEEEEEEFFFFFFFFGGGGGGG ... HHHHHHIIIIIJJJJJJJKKKK ... ... Some varying text 2 ... ... LLLLLMMMMMMNNNNNNNOOOO ... PPPPPPPQQQQQQRRRRRRSSS ... TTTTTUUUUUVVVVVVWWWWWW ... """ &gt;&gt;&gt; for match in rx_sequence.finditer(text): ... title, sequence = match.groups() ... title = title.strip() ... sequence = rx_blanks.sub("",sequence) ... print "Title:",title ... print "Sequence:",sequence ... print ... Title: Some varying text1 Sequence: AAABBBBBBCCCCCCDDDDDDDEEEEEEEFFFFFFFFGGGGGGGHHHHHHIIIIIJJJJJJJKKKK Title: Some varying text 2 Sequence: LLLLLMMMMMMNNNNNNNOOOOPPPPPPPQQQQQQRRRRRRSSSTTTTTUUUUUVVVVVVWWWWWW </code></pre> <p><hr /></p> <p>Some explanation about this regular expression might be useful: <code>^(.+?)\n\n((?:[A-Z]+\n)+)</code></p> <ul> <li>The first character (<code>^</code>) means "starting at the beginning of a line". Be aware that it does not match the newline itself (same for $: it means "just before a newline", but it does not match the newline itself).</li> <li>Then <code>(.+?)\n\n</code> means "match as few characters as possible (all characters are allowed) until you reach two newlines". The result (without the newlines) is put in the first group.</li> <li><code>[A-Z]+\n</code> means "match as many upper case letters as possible until you reach a newline. This defines what I will call a <em>textline</em>.</li> <li><code>((?:</code><em>textline</em><code>)+)</code> means match one or more <em>textlines</em> but do not put each line in a group. Instead, put <strong>all</strong> the <em>textlines</em> in one group.</li> <li>You could add a final <code>\n</code> in the regular expression if you want to enforce a double newline at the end.</li> <li>Also, if you are not sure about what type of newline you will get (<code>\n</code> or <code>\r</code> or <code>\r\n</code>) then just fix the regular expression by replacing every occurrence of <code>\n</code> by <code>(?:\n|\r\n?)</code>.</li> </ul>
10
2009-02-25T19:47:22Z
[ "python", "regex", "multiline" ]
Python regular expression matching a multiline block of text
587,345
<p>I'm having a bit of trouble getting a Python regex to work when matching against text that spans multiple lines. The example text is ('\n' is a newline)</p> <pre><code>some Varying TEXT\n \n DSJFKDAFJKDAFJDSAKFJADSFLKDLAFKDSAF\n [more of the above, ending with a newline]\n [yep, there is a variable number of lines here]\n \n (repeat the above a few hundred times). </code></pre> <p>I'd like to capture two things: the 'some_Varying_TEXT' part, and all of the lines of uppercase text that comes two lines below it in one capture (i can strip out the newline characters later). I've tried with a few approaches:</p> <pre><code>re.compile(r"^&gt;(\w+)$$([.$]+)^$", re.MULTILINE) # try to capture both parts re.compile(r"(^[^&gt;][\w\s]+)$", re.MULTILINE|re.DOTALL) # just textlines </code></pre> <p>and a lot of variations hereof with no luck. The last one seems to match the lines of text one by one, which is not what I really want. I can catch the first part, no problem, but I can't seem to catch the 4-5 lines of uppercase text. I'd like match.group(1) to be some&#95;Varying&#95;Text and group(2) to be line1+line2+line3+etc until the empty line is encountered.</p> <p>If anyone's curious, its supposed to be a sequence of aminoacids that make up a protein.</p>
42
2009-02-25T19:00:49Z
587,620
<p>Try this:</p> <pre><code>re.compile(r"^(.+)\n((?:\n.+)+)", re.MULTILINE) </code></pre> <p>I think your biggest problem is that you're expecting the <code>^</code> and <code>$</code> anchors to match linefeeds, but they don't. In multiline mode, <code>^</code> matches the position immediately <em>following</em> a newline and <code>$</code> matches the position immediately <em>preceding</em> a newline.</p> <p>Be aware, too, that a newline can consist of a linefeed (\n), a carriage-return (\r), or a carriage-return+linefeed (\r\n). If you aren't certain that your target text uses only linefeeds, you should use this more inclusive version of the regex:</p> <pre><code>re.compile(r"^(.+)(?:\n|\r\n?)((?:(?:\n|\r\n?).+)+)", re.MULTILINE) </code></pre> <p>BTW, you don't want to use the DOTALL modifier here; you're relying on the fact that the dot matches everything <em>except</em> newlines.</p>
56
2009-02-25T20:06:01Z
[ "python", "regex", "multiline" ]
Python regular expression matching a multiline block of text
587,345
<p>I'm having a bit of trouble getting a Python regex to work when matching against text that spans multiple lines. The example text is ('\n' is a newline)</p> <pre><code>some Varying TEXT\n \n DSJFKDAFJKDAFJDSAKFJADSFLKDLAFKDSAF\n [more of the above, ending with a newline]\n [yep, there is a variable number of lines here]\n \n (repeat the above a few hundred times). </code></pre> <p>I'd like to capture two things: the 'some_Varying_TEXT' part, and all of the lines of uppercase text that comes two lines below it in one capture (i can strip out the newline characters later). I've tried with a few approaches:</p> <pre><code>re.compile(r"^&gt;(\w+)$$([.$]+)^$", re.MULTILINE) # try to capture both parts re.compile(r"(^[^&gt;][\w\s]+)$", re.MULTILINE|re.DOTALL) # just textlines </code></pre> <p>and a lot of variations hereof with no luck. The last one seems to match the lines of text one by one, which is not what I really want. I can catch the first part, no problem, but I can't seem to catch the 4-5 lines of uppercase text. I'd like match.group(1) to be some&#95;Varying&#95;Text and group(2) to be line1+line2+line3+etc until the empty line is encountered.</p> <p>If anyone's curious, its supposed to be a sequence of aminoacids that make up a protein.</p>
42
2009-02-25T19:00:49Z
587,819
<p>My preference.</p> <pre><code>lineIter= iter(aFile) for line in lineIter: if line.startswith( "&gt;" ): someVaryingText= line break assert len( lineIter.next().strip() ) == 0 acids= [] for line in lineIter: if len(line.strip()) == 0: break acids.append( line ) </code></pre> <p>At this point you have someVaryingText as a string, and the acids as a list of strings. You can do <code>"".join( acids )</code> to make a single string.</p> <p>I find this less frustrating (and more flexible) than multiline regexes.</p>
1
2009-02-25T20:58:28Z
[ "python", "regex", "multiline" ]
Python regular expression matching a multiline block of text
587,345
<p>I'm having a bit of trouble getting a Python regex to work when matching against text that spans multiple lines. The example text is ('\n' is a newline)</p> <pre><code>some Varying TEXT\n \n DSJFKDAFJKDAFJDSAKFJADSFLKDLAFKDSAF\n [more of the above, ending with a newline]\n [yep, there is a variable number of lines here]\n \n (repeat the above a few hundred times). </code></pre> <p>I'd like to capture two things: the 'some_Varying_TEXT' part, and all of the lines of uppercase text that comes two lines below it in one capture (i can strip out the newline characters later). I've tried with a few approaches:</p> <pre><code>re.compile(r"^&gt;(\w+)$$([.$]+)^$", re.MULTILINE) # try to capture both parts re.compile(r"(^[^&gt;][\w\s]+)$", re.MULTILINE|re.DOTALL) # just textlines </code></pre> <p>and a lot of variations hereof with no luck. The last one seems to match the lines of text one by one, which is not what I really want. I can catch the first part, no problem, but I can't seem to catch the 4-5 lines of uppercase text. I'd like match.group(1) to be some&#95;Varying&#95;Text and group(2) to be line1+line2+line3+etc until the empty line is encountered.</p> <p>If anyone's curious, its supposed to be a sequence of aminoacids that make up a protein.</p>
42
2009-02-25T19:00:49Z
587,825
<p>If each file only has one sequence of aminoacids, I wouldn't use regular expressions at all. Just something like this:</p> <pre><code>def read_amino_acid_sequence(path): with open(path) as sequence_file: title = sequence_file.readline() # read 1st line aminoacid_sequence = sequence_file.read() # read the rest # some cleanup, if necessary title = title.strip() # remove trailing white spaces and newline aminoacid_sequence = aminoacid_sequence.replace(" ","").replace("\n","") return title, aminoacid_sequence </code></pre>
3
2009-02-25T20:59:59Z
[ "python", "regex", "multiline" ]
How to increment a value with leading zeroes?
587,647
<p>What would be the best way to increment a value that contains leading zeroes? For example, I'd like to increment "00000001". However, it should be noted that the number of leading zeroes will not exceed 30. So there may be cases like "0000012", "00000000000000099", or "000000000000045".</p> <p>I can think of a couple ways, but I want to see if someone comes up with something slick.</p>
8
2009-02-25T20:13:22Z
587,655
<p>Determine the length, convert it to an integer, increment it, then convert it back to a string with leading zeros so that it has the same length as before.</p>
1
2009-02-25T20:15:29Z
[ "python" ]
How to increment a value with leading zeroes?
587,647
<p>What would be the best way to increment a value that contains leading zeroes? For example, I'd like to increment "00000001". However, it should be noted that the number of leading zeroes will not exceed 30. So there may be cases like "0000012", "00000000000000099", or "000000000000045".</p> <p>I can think of a couple ways, but I want to see if someone comes up with something slick.</p>
8
2009-02-25T20:13:22Z
587,656
<pre><code>int('00000001') + 1 </code></pre> <p>if you want the leading zeroes back:</p> <pre><code>"%08g" % (int('000000001') + 1) </code></pre>
8
2009-02-25T20:15:43Z
[ "python" ]
How to increment a value with leading zeroes?
587,647
<p>What would be the best way to increment a value that contains leading zeroes? For example, I'd like to increment "00000001". However, it should be noted that the number of leading zeroes will not exceed 30. So there may be cases like "0000012", "00000000000000099", or "000000000000045".</p> <p>I can think of a couple ways, but I want to see if someone comes up with something slick.</p>
8
2009-02-25T20:13:22Z
587,689
<p>Presumably, you specifically mean an integer represented as a string with leading zeros?</p> <p>If that's the case, I'd do it thusly:</p> <pre><code>&gt;&gt;&gt; a '00000000000000099' &gt;&gt;&gt; l = len(a) &gt;&gt;&gt; b = int(a)+1 &gt;&gt;&gt; b 100 &gt;&gt;&gt; ("%0"+"%dd" % l) % b '00000000000000100' </code></pre>
2
2009-02-25T20:23:10Z
[ "python" ]
How to increment a value with leading zeroes?
587,647
<p>What would be the best way to increment a value that contains leading zeroes? For example, I'd like to increment "00000001". However, it should be noted that the number of leading zeroes will not exceed 30. So there may be cases like "0000012", "00000000000000099", or "000000000000045".</p> <p>I can think of a couple ways, but I want to see if someone comes up with something slick.</p>
8
2009-02-25T20:13:22Z
587,690
<p>"%%0%ii" % len(x) % (int(x)+1)</p> <p>-- MarkusQ</p> <p>P.S. For x = "0000034" it unfolds like so:</p> <pre><code>"%%0%ii" % len("0000034") % (int("0000034")+1) "%%0%ii" % 7 % (34+1) "%07i" % 35 "0000035" </code></pre>
8
2009-02-25T20:23:18Z
[ "python" ]
How to increment a value with leading zeroes?
587,647
<p>What would be the best way to increment a value that contains leading zeroes? For example, I'd like to increment "00000001". However, it should be noted that the number of leading zeroes will not exceed 30. So there may be cases like "0000012", "00000000000000099", or "000000000000045".</p> <p>I can think of a couple ways, but I want to see if someone comes up with something slick.</p>
8
2009-02-25T20:13:22Z
587,696
<p>Store your number as an integer. When you want to print it, add the leading zeros. This way you can easily do math without conversions, and it simplifies the thought process.</p>
1
2009-02-25T20:26:57Z
[ "python" ]
How to increment a value with leading zeroes?
587,647
<p>What would be the best way to increment a value that contains leading zeroes? For example, I'd like to increment "00000001". However, it should be noted that the number of leading zeroes will not exceed 30. So there may be cases like "0000012", "00000000000000099", or "000000000000045".</p> <p>I can think of a couple ways, but I want to see if someone comes up with something slick.</p>
8
2009-02-25T20:13:22Z
587,791
<p>Use the much overlooked str.zfill():</p> <pre><code>str(int(x) + 1).zfill(len(x)) </code></pre>
15
2009-02-25T20:50:12Z
[ "python" ]
How to increment a value with leading zeroes?
587,647
<p>What would be the best way to increment a value that contains leading zeroes? For example, I'd like to increment "00000001". However, it should be noted that the number of leading zeroes will not exceed 30. So there may be cases like "0000012", "00000000000000099", or "000000000000045".</p> <p>I can think of a couple ways, but I want to see if someone comes up with something slick.</p>
8
2009-02-25T20:13:22Z
21,325,089
<p>"my code is in c" <code>int a[6]={0,0,0,0,0,0},i=5,k,p; while(a[0]!=10) { do { for(p=0;p&lt;=i;p++) printf("%d",a[p]); printf("\n"); delay(100); a[i]++; }while(a[i]!=10); for(k=0;k&lt;=i;k++) if(a[i-k]==10) { a[i-(k+1)]++; a[i-k]=0; } }</code></p>
-1
2014-01-24T05:27:22Z
[ "python" ]
a question on for loops in python
588,052
<p>I want to calaculate pythagorean triplets(code below) and I want to calculate infinitly how do I do it without using the three for loops? Could I use a for loop in some way? thanks.</p> <pre><code>import math def main(): for x in range (10000, 1000): for y in range (10000, 1000): for z in range(10000, 1000): if x*x == y*y + z*z: print y, z, x print '-'*50 if __name__ == '__main__': main() </code></pre>
3
2009-02-25T21:47:41Z
588,067
<p>Generally, you can't. Three variables, three loops.</p> <p>But this is a special case, as <a href="http://stackoverflow.com/questions/588052/a-question-on-for-loops-in-python/588087#588087">nobody</a> pointed out. You can solve this problem with two loops.</p> <p>Also, there's no point in checking y, z and z, y.</p> <p>Oh, and <code>range(10000, 1000) = []</code>.</p> <pre><code>import math for x in range(1, 1000): for y in range(x, 1000): z = math.sqrt(x**2 + y**2) if int(z) == z: print x, y, int(z) print '-'*50 </code></pre>
8
2009-02-25T21:52:06Z
[ "python", "for-loop" ]
a question on for loops in python
588,052
<p>I want to calaculate pythagorean triplets(code below) and I want to calculate infinitly how do I do it without using the three for loops? Could I use a for loop in some way? thanks.</p> <pre><code>import math def main(): for x in range (10000, 1000): for y in range (10000, 1000): for z in range(10000, 1000): if x*x == y*y + z*z: print y, z, x print '-'*50 if __name__ == '__main__': main() </code></pre>
3
2009-02-25T21:47:41Z
588,084
<p>Besides what has already been posted, people would expect three loops for three collections. Anything else may get very confusing and provide no added benefit.</p>
0
2009-02-25T21:55:15Z
[ "python", "for-loop" ]
a question on for loops in python
588,052
<p>I want to calaculate pythagorean triplets(code below) and I want to calculate infinitly how do I do it without using the three for loops? Could I use a for loop in some way? thanks.</p> <pre><code>import math def main(): for x in range (10000, 1000): for y in range (10000, 1000): for z in range(10000, 1000): if x*x == y*y + z*z: print y, z, x print '-'*50 if __name__ == '__main__': main() </code></pre>
3
2009-02-25T21:47:41Z
588,087
<p>You would only need two loops - just check to see if <code>math.sqrt(x*x+y*y)</code> is an integer. If it is, you've discovered a pythagorean triple.</p> <p>I'm new to Python, so I don't know what <code>range(10000, 1000)</code> does - where does it start and stop? I ask because you can halve your runtime by having the range for <code>y</code> start at <code>x</code> instead of fixing it, due to the fact that addition is commutative.</p> <p><strong>edit:</strong> <a href="http://stackoverflow.com/questions/588052/a-question-on-for-loops-in-python/588067#588067">This answer</a> is what I was getting at, and what I would have written if I knew more Python. </p>
4
2009-02-25T21:55:26Z
[ "python", "for-loop" ]
a question on for loops in python
588,052
<p>I want to calaculate pythagorean triplets(code below) and I want to calculate infinitly how do I do it without using the three for loops? Could I use a for loop in some way? thanks.</p> <pre><code>import math def main(): for x in range (10000, 1000): for y in range (10000, 1000): for z in range(10000, 1000): if x*x == y*y + z*z: print y, z, x print '-'*50 if __name__ == '__main__': main() </code></pre>
3
2009-02-25T21:47:41Z
588,101
<p>You can arrange your code in a single main loop like this:</p> <pre><code>MIN = 10000 MAX = 10010 a = [MIN, MIN, MIN] while True: print a for i in range(len(a)): a[i] = a[i] + 1 if a[i] &lt; MAX: break a[i] = MIN i += 1 else: break </code></pre> <p>Instead of the <code>print a</code>, you can do your Pythagorean triplet test there. This will work for an arbitrary number of dimensions.</p> <p>If you really want to do this infinitely, you will have to use a different iteration technique such as <a href="http://en.wikipedia.org/wiki/Diagonal%5Fargument" rel="nofollow">diagonalization</a>.</p>
4
2009-02-25T21:58:16Z
[ "python", "for-loop" ]
a question on for loops in python
588,052
<p>I want to calaculate pythagorean triplets(code below) and I want to calculate infinitly how do I do it without using the three for loops? Could I use a for loop in some way? thanks.</p> <pre><code>import math def main(): for x in range (10000, 1000): for y in range (10000, 1000): for z in range(10000, 1000): if x*x == y*y + z*z: print y, z, x print '-'*50 if __name__ == '__main__': main() </code></pre>
3
2009-02-25T21:47:41Z
588,154
<p>Not the most efficient (Python will build an array with a billion tuples), but this is a single loop:</p> <pre><code>for x, y, z in [(x, y, z) for x in range(10000, 11000) for y in range(10000, 11000) for z in range(10000, 11000)]: if x*x == y*y + z*z: print y, z, x print '-'*50 </code></pre> <p>Or, as suggested by <a href="http://stackoverflow.com/users/69893/christian-witts">Christian Witts</a>,</p> <pre><code>for x, y, z in ((x, y, z) for x in xrange(10000, 11000) for y in xrange(10000, 11000) for z in xrange(10000, 11000)): if x*x == y*y + z*z: print y, z, x print '-'*50 </code></pre> <p>(assuming Python >= 2.4) uses <a href="http://www.python.org/dev/peps/pep-0289/" rel="nofollow">generators</a> instead of building a billion-tuple array.</p> <p>Either way, you shouldn't code like this... Your initial code with nested loops is clearer.</p>
1
2009-02-25T22:13:33Z
[ "python", "for-loop" ]
a question on for loops in python
588,052
<p>I want to calaculate pythagorean triplets(code below) and I want to calculate infinitly how do I do it without using the three for loops? Could I use a for loop in some way? thanks.</p> <pre><code>import math def main(): for x in range (10000, 1000): for y in range (10000, 1000): for z in range(10000, 1000): if x*x == y*y + z*z: print y, z, x print '-'*50 if __name__ == '__main__': main() </code></pre>
3
2009-02-25T21:47:41Z
588,245
<p>Using <a href="http://docs.python.org/library/functions.html#xrange" rel="nofollow">xrange</a> instead of <code>range</code> should use less memory, especially if you want to try large ranges.</p>
2
2009-02-25T22:39:31Z
[ "python", "for-loop" ]
a question on for loops in python
588,052
<p>I want to calaculate pythagorean triplets(code below) and I want to calculate infinitly how do I do it without using the three for loops? Could I use a for loop in some way? thanks.</p> <pre><code>import math def main(): for x in range (10000, 1000): for y in range (10000, 1000): for z in range(10000, 1000): if x*x == y*y + z*z: print y, z, x print '-'*50 if __name__ == '__main__': main() </code></pre>
3
2009-02-25T21:47:41Z
588,303
<p>This is the same as Can Berk Guder's answer, but done as a generator, just for fun. It's not really useful with the nested loops here, but it can often be a cleaner solution. Your function produces results; you worry later about how many to retrieve.</p> <pre><code>import math def triplets(limit): for x in range(1, limit): for y in range(x, limit): z = math.sqrt(x**2 + y**2) if int(z) == z: yield x, y, int(z) for x, y, z in triplets(10): print x, y, z print "-" * 50 </code></pre>
1
2009-02-25T22:58:04Z
[ "python", "for-loop" ]
a question on for loops in python
588,052
<p>I want to calaculate pythagorean triplets(code below) and I want to calculate infinitly how do I do it without using the three for loops? Could I use a for loop in some way? thanks.</p> <pre><code>import math def main(): for x in range (10000, 1000): for y in range (10000, 1000): for z in range(10000, 1000): if x*x == y*y + z*z: print y, z, x print '-'*50 if __name__ == '__main__': main() </code></pre>
3
2009-02-25T21:47:41Z
588,336
<p>If you want to count to infinity ..</p> <p>Create a generator function that counts from zero and never stops, and use the for loop on it</p> <pre><code>def inf(): i = 0 while True: yield i i = i + 1 for i in inf(): print i # or do whatever you want! </code></pre> <p>I don't know if there's already such a builtin function</p>
0
2009-02-25T23:08:12Z
[ "python", "for-loop" ]
a question on for loops in python
588,052
<p>I want to calaculate pythagorean triplets(code below) and I want to calculate infinitly how do I do it without using the three for loops? Could I use a for loop in some way? thanks.</p> <pre><code>import math def main(): for x in range (10000, 1000): for y in range (10000, 1000): for z in range(10000, 1000): if x*x == y*y + z*z: print y, z, x print '-'*50 if __name__ == '__main__': main() </code></pre>
3
2009-02-25T21:47:41Z
588,359
<p>Using the same algorithm (see the other answers for better approaches), you can use itertools.count to get a loop that runs forever.</p> <pre><code>import itertools for x in itertools.count(1): for y in xrange(1, x): for z in xrange(1, y): if x*x == y*y + z*z: print x, y, z </code></pre>
1
2009-02-25T23:13:41Z
[ "python", "for-loop" ]
a question on for loops in python
588,052
<p>I want to calaculate pythagorean triplets(code below) and I want to calculate infinitly how do I do it without using the three for loops? Could I use a for loop in some way? thanks.</p> <pre><code>import math def main(): for x in range (10000, 1000): for y in range (10000, 1000): for z in range(10000, 1000): if x*x == y*y + z*z: print y, z, x print '-'*50 if __name__ == '__main__': main() </code></pre>
3
2009-02-25T21:47:41Z
588,679
<p>Here's an efficient version, using iterators, that generates all such triples, in order. The trick here is to iterate up through the sets of (x,y) pairs that sum to N, for all N.</p> <pre> import math import itertools def all_int_pairs(): "generate all pairs of positive integers" for n in itertools.count(1): for x in xrange(1,n/2+1): yield x,n-x for x,y in all_int_pairs(): z = math.sqrt(x**2 + y**2) if int(z) == z: print x, y, int(z) print '-'*50 </pre>
2
2009-02-26T01:04:36Z
[ "python", "for-loop" ]