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
Outputting data a row at a time from mysql using sqlalchemy
536,051
<p>I want to fetch data from a mysql database using sqlalchemy and use the data in a different class.. Basically I fetch a row at a time, use the data, fetch another row, use the data and so on.. I am running into some problem doing this.. </p> <p>Basically, how do I output data a row at a time from mysql data?.. I have looked into all tutorials but they are not helping much.</p>
0
2009-02-11T09:19:22Z
536,180
<p>From what I understand, you're interested in something like this:</p> <pre><code># s is object returned by the .select() method rs = s.execute() row = rs.fetchone() # do something with the row row = rs.fetchone() # do something with another row </code></pre> <p>You can find this in a tutorial <a href="http://www.rmunn.com/sqlalchemy-tutorial/tutorial.html" rel="nofollow">here</a>.</p>
0
2009-02-11T09:59:46Z
[ "python", "mysql", "sqlalchemy" ]
Outputting data a row at a time from mysql using sqlalchemy
536,051
<p>I want to fetch data from a mysql database using sqlalchemy and use the data in a different class.. Basically I fetch a row at a time, use the data, fetch another row, use the data and so on.. I am running into some problem doing this.. </p> <p>Basically, how do I output data a row at a time from mysql data?.. I have looked into all tutorials but they are not helping much.</p>
0
2009-02-11T09:19:22Z
536,269
<p>Exactly what problems are you running into?</p> <p>You can simply iterate over the ResultProxy object:</p> <pre> for row in conn_or_sess_or_engine.execute(selectable_obj_or_SQLstring): do_something_with(row) </pre>
1
2009-02-11T10:36:33Z
[ "python", "mysql", "sqlalchemy" ]
C++ string parsing (python style)
536,148
<p>I love how in python I can do something like:</p> <pre><code>points = [] for line in open("data.txt"): a,b,c = map(float, line.split(',')) points += [(a,b,c)] </code></pre> <p>Basically it's reading a list of lines where each one represents a point in 3D space, the point is represented as three numbers separated by commas</p> <p>How can this be done in C++ without too much headache?</p> <p>Performance is not very important, this parsing only happens one time, so simplicity is more important.</p> <p>P.S. I know it sounds like a newbie question, but believe me I've written a lexer in D (pretty much like C++) which involves reading some text char by char and recognizing tokens,<br /> it's just that, coming back to C++ after a long period of python, just makes me not wanna waste my time on such things.</p>
15
2009-02-11T09:49:23Z
536,164
<p>You could read the file from a std::iostream line by line, put each line into a std::string and then use boost::tokenizer to split it. It won't be quite as elegant/short as the python one but a lot easier than reading things in a character at a time...</p>
3
2009-02-11T09:55:27Z
[ "c++", "python", "parsing", "string", "text-files" ]
C++ string parsing (python style)
536,148
<p>I love how in python I can do something like:</p> <pre><code>points = [] for line in open("data.txt"): a,b,c = map(float, line.split(',')) points += [(a,b,c)] </code></pre> <p>Basically it's reading a list of lines where each one represents a point in 3D space, the point is represented as three numbers separated by commas</p> <p>How can this be done in C++ without too much headache?</p> <p>Performance is not very important, this parsing only happens one time, so simplicity is more important.</p> <p>P.S. I know it sounds like a newbie question, but believe me I've written a lexer in D (pretty much like C++) which involves reading some text char by char and recognizing tokens,<br /> it's just that, coming back to C++ after a long period of python, just makes me not wanna waste my time on such things.</p>
15
2009-02-11T09:49:23Z
536,177
<pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;sstream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; // For replace() using namespace std; struct Point { double a, b, c; }; int main(int argc, char **argv) { vector&lt;Point&gt; points; ifstream f("data.txt"); string str; while (getline(f, str)) { replace(str.begin(), str.end(), ',', ' '); istringstream iss(str); Point p; iss &gt;&gt; p.a &gt;&gt; p.b &gt;&gt; p.c; points.push_back(p); } // Do something with points... return 0; } </code></pre>
13
2009-02-11T09:59:21Z
[ "c++", "python", "parsing", "string", "text-files" ]
C++ string parsing (python style)
536,148
<p>I love how in python I can do something like:</p> <pre><code>points = [] for line in open("data.txt"): a,b,c = map(float, line.split(',')) points += [(a,b,c)] </code></pre> <p>Basically it's reading a list of lines where each one represents a point in 3D space, the point is represented as three numbers separated by commas</p> <p>How can this be done in C++ without too much headache?</p> <p>Performance is not very important, this parsing only happens one time, so simplicity is more important.</p> <p>P.S. I know it sounds like a newbie question, but believe me I've written a lexer in D (pretty much like C++) which involves reading some text char by char and recognizing tokens,<br /> it's just that, coming back to C++ after a long period of python, just makes me not wanna waste my time on such things.</p>
15
2009-02-11T09:49:23Z
536,224
<p>This answer is based on the previous answer by j_random_hacker and makes use of Boost Spirit.</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;sstream&gt; #include &lt;string&gt; #include &lt;boost/spirit.hpp&gt; using namespace std; using namespace boost; using namespace boost::spirit; struct Point { double a, b, c; }; int main(int argc, char **argv) { vector&lt;Point&gt; points; ifstream f("data.txt"); string str; Point p; rule&lt;&gt; point_p = double_p[assign_a(p.a)] &gt;&gt; ',' &gt;&gt; double_p[assign_a(p.b)] &gt;&gt; ',' &gt;&gt; double_p[assign_a(p.c)] ; while (getline(f, str)) { parse( str, point_p, space_p ); points.push_back(p); } // Do something with points... return 0; } </code></pre>
7
2009-02-11T10:19:55Z
[ "c++", "python", "parsing", "string", "text-files" ]
C++ string parsing (python style)
536,148
<p>I love how in python I can do something like:</p> <pre><code>points = [] for line in open("data.txt"): a,b,c = map(float, line.split(',')) points += [(a,b,c)] </code></pre> <p>Basically it's reading a list of lines where each one represents a point in 3D space, the point is represented as three numbers separated by commas</p> <p>How can this be done in C++ without too much headache?</p> <p>Performance is not very important, this parsing only happens one time, so simplicity is more important.</p> <p>P.S. I know it sounds like a newbie question, but believe me I've written a lexer in D (pretty much like C++) which involves reading some text char by char and recognizing tokens,<br /> it's just that, coming back to C++ after a long period of python, just makes me not wanna waste my time on such things.</p>
15
2009-02-11T09:49:23Z
536,265
<p>I`d do something like this:</p> <pre><code>ifstream f("data.txt"); string str; while (getline(f, str)) { Point p; sscanf(str.c_str(), "%f, %f, %f\n", &amp;p.x, &amp;p.y, &amp;p.z); points.push_back(p); } </code></pre> <p>x,y,z must be floats.</p> <p>And include:</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; </code></pre>
24
2009-02-11T10:33:17Z
[ "c++", "python", "parsing", "string", "text-files" ]
C++ string parsing (python style)
536,148
<p>I love how in python I can do something like:</p> <pre><code>points = [] for line in open("data.txt"): a,b,c = map(float, line.split(',')) points += [(a,b,c)] </code></pre> <p>Basically it's reading a list of lines where each one represents a point in 3D space, the point is represented as three numbers separated by commas</p> <p>How can this be done in C++ without too much headache?</p> <p>Performance is not very important, this parsing only happens one time, so simplicity is more important.</p> <p>P.S. I know it sounds like a newbie question, but believe me I've written a lexer in D (pretty much like C++) which involves reading some text char by char and recognizing tokens,<br /> it's just that, coming back to C++ after a long period of python, just makes me not wanna waste my time on such things.</p>
15
2009-02-11T09:49:23Z
536,431
<p>All these good examples aside, in C++ you would normally override the <code>operator &gt;&gt;</code> for your point type to achieve something like this:</p> <pre><code>point p; while (file &gt;&gt; p) points.push_back(p); </code></pre> <p>or even:</p> <pre><code>copy( istream_iterator&lt;point&gt;(file), istream_iterator&lt;point&gt;(), back_inserter(points) ); </code></pre> <p>The relevant implementation of the operator could look very much like the code by j_random_hacker.</p>
16
2009-02-11T11:45:35Z
[ "c++", "python", "parsing", "string", "text-files" ]
C++ string parsing (python style)
536,148
<p>I love how in python I can do something like:</p> <pre><code>points = [] for line in open("data.txt"): a,b,c = map(float, line.split(',')) points += [(a,b,c)] </code></pre> <p>Basically it's reading a list of lines where each one represents a point in 3D space, the point is represented as three numbers separated by commas</p> <p>How can this be done in C++ without too much headache?</p> <p>Performance is not very important, this parsing only happens one time, so simplicity is more important.</p> <p>P.S. I know it sounds like a newbie question, but believe me I've written a lexer in D (pretty much like C++) which involves reading some text char by char and recognizing tokens,<br /> it's just that, coming back to C++ after a long period of python, just makes me not wanna waste my time on such things.</p>
15
2009-02-11T09:49:23Z
537,473
<p>Fun with Boost.Tuples:</p> <pre><code>#include &lt;boost/tuple/tuple_io.hpp&gt; #include &lt;vector&gt; #include &lt;fstream&gt; #include &lt;iostream&gt; #include &lt;algorithm&gt; int main() { using namespace boost::tuples; typedef boost::tuple&lt;float,float,float&gt; PointT; std::ifstream f("input.txt"); f &gt;&gt; set_open(' ') &gt;&gt; set_close(' ') &gt;&gt; set_delimiter(','); std::vector&lt;PointT&gt; v; std::copy(std::istream_iterator&lt;PointT&gt;(f), std::istream_iterator&lt;PointT&gt;(), std::back_inserter(v) ); std::copy(v.begin(), v.end(), std::ostream_iterator&lt;PointT&gt;(std::cout) ); return 0; } </code></pre> <p>Note that this is not strictly equivalent to the Python code in your question because the tuples don't have to be on separate lines. For example, this:</p> <pre><code>1,2,3 4,5,6 </code></pre> <p>will give the same output than:</p> <pre><code>1,2,3 4,5,6 </code></pre> <p>It's up to you to decide if that's a bug or a feature :)</p>
4
2009-02-11T16:01:43Z
[ "c++", "python", "parsing", "string", "text-files" ]
C++ string parsing (python style)
536,148
<p>I love how in python I can do something like:</p> <pre><code>points = [] for line in open("data.txt"): a,b,c = map(float, line.split(',')) points += [(a,b,c)] </code></pre> <p>Basically it's reading a list of lines where each one represents a point in 3D space, the point is represented as three numbers separated by commas</p> <p>How can this be done in C++ without too much headache?</p> <p>Performance is not very important, this parsing only happens one time, so simplicity is more important.</p> <p>P.S. I know it sounds like a newbie question, but believe me I've written a lexer in D (pretty much like C++) which involves reading some text char by char and recognizing tokens,<br /> it's just that, coming back to C++ after a long period of python, just makes me not wanna waste my time on such things.</p>
15
2009-02-11T09:49:23Z
538,747
<p>Its nowhere near as terse, and of course I didn't compile this.</p> <pre><code>float atof_s( std::string &amp; s ) { return atoi( s.c_str() ); } { ifstream f("data.txt") string str; vector&lt;vector&lt;float&gt;&gt; data; while( getline( f, str ) ) { vector&lt;float&gt; v; boost::algorithm::split_iterator&lt;string::iterator&gt; e; std::transform( boost::algorithm::make_split_iterator( str, token_finder( is_any_of( "," ) ) ), e, v.begin(), atof_s ); v.resize(3); // only grab the first 3 data.push_back(v); } </code></pre>
0
2009-02-11T20:58:00Z
[ "c++", "python", "parsing", "string", "text-files" ]
C++ string parsing (python style)
536,148
<p>I love how in python I can do something like:</p> <pre><code>points = [] for line in open("data.txt"): a,b,c = map(float, line.split(',')) points += [(a,b,c)] </code></pre> <p>Basically it's reading a list of lines where each one represents a point in 3D space, the point is represented as three numbers separated by commas</p> <p>How can this be done in C++ without too much headache?</p> <p>Performance is not very important, this parsing only happens one time, so simplicity is more important.</p> <p>P.S. I know it sounds like a newbie question, but believe me I've written a lexer in D (pretty much like C++) which involves reading some text char by char and recognizing tokens,<br /> it's just that, coming back to C++ after a long period of python, just makes me not wanna waste my time on such things.</p>
15
2009-02-11T09:49:23Z
768,898
<p>The <a href="http://www.partow.net/programming/strtk/index.html">C++ String Toolkit Library (StrTk)</a> has the following solution to your problem:</p> <pre><code>#include &lt;string&gt; #include &lt;deque&gt; #include "strtk.hpp" struct point { double x,y,z; } int main() { std::deque&lt;point&gt; points; point p; strtk::for_each_line("data.txt", [&amp;points,&amp;p](const std::string&amp; str) { strtk::parse(str,",",p.x,p.y,p.z); points.push_back(p); }); return 0; } </code></pre> <p>More examples can be found <a href="http://www.codeproject.com/KB/recipes/Tokenizer.aspx">Here</a></p>
13
2009-04-20T15:57:05Z
[ "c++", "python", "parsing", "string", "text-files" ]
C++ string parsing (python style)
536,148
<p>I love how in python I can do something like:</p> <pre><code>points = [] for line in open("data.txt"): a,b,c = map(float, line.split(',')) points += [(a,b,c)] </code></pre> <p>Basically it's reading a list of lines where each one represents a point in 3D space, the point is represented as three numbers separated by commas</p> <p>How can this be done in C++ without too much headache?</p> <p>Performance is not very important, this parsing only happens one time, so simplicity is more important.</p> <p>P.S. I know it sounds like a newbie question, but believe me I've written a lexer in D (pretty much like C++) which involves reading some text char by char and recognizing tokens,<br /> it's just that, coming back to C++ after a long period of python, just makes me not wanna waste my time on such things.</p>
15
2009-02-11T09:49:23Z
1,621,028
<p>One of Sony Picture Imagework's open-source projects is <a href="http://code.google.com/p/pystring/" rel="nofollow">Pystring</a>, which should make for a mostly direct translation of the string-splitting parts:</p> <blockquote> <p>Pystring is a collection of C++ functions which match the interface and behavior of python’s string class methods using std::string. Implemented in C++, it does not require or make use of a python interpreter. It provides convenience and familiarity for common string operations not included in the standard C++ library</p> </blockquote> <p>There are <a href="http://code.google.com/p/pystring/wiki/Examples" rel="nofollow">a few examples</a>, and <a href="http://code.google.com/p/pystring/wiki/Documentation" rel="nofollow">some documentation</a></p>
1
2009-10-25T14:19:26Z
[ "c++", "python", "parsing", "string", "text-files" ]
C++ string parsing (python style)
536,148
<p>I love how in python I can do something like:</p> <pre><code>points = [] for line in open("data.txt"): a,b,c = map(float, line.split(',')) points += [(a,b,c)] </code></pre> <p>Basically it's reading a list of lines where each one represents a point in 3D space, the point is represented as three numbers separated by commas</p> <p>How can this be done in C++ without too much headache?</p> <p>Performance is not very important, this parsing only happens one time, so simplicity is more important.</p> <p>P.S. I know it sounds like a newbie question, but believe me I've written a lexer in D (pretty much like C++) which involves reading some text char by char and recognizing tokens,<br /> it's just that, coming back to C++ after a long period of python, just makes me not wanna waste my time on such things.</p>
15
2009-02-11T09:49:23Z
5,718,665
<p>all these are good examples. yet they dont answer the following:</p> <ol> <li>a CSV file with different column numbers (some rows with more columns than others)</li> <li>or when some of the values have white space (ya yb,x1 x2,,x2,)</li> </ol> <p>so for those who are still looking, this class: <a href="http://www.codeguru.com/cpp/tic/tic0226.shtml" rel="nofollow">http://www.codeguru.com/cpp/tic/tic0226.shtml</a> is pretty cool... some changes might be needed </p>
0
2011-04-19T15:15:48Z
[ "c++", "python", "parsing", "string", "text-files" ]
Execute arbitrary python code remotely - can it be done?
536,370
<p>I'm working on a grid system which has a number of very powerful computers. These can be used to execute python functions very quickly. My users have a number of python functions which take a long time to calculate on workstations, ideally they would like to be able to call some functions on a remote powerful server, but have it appear to be running locally.</p> <p>Python has an old function called "apply" - it's mostly useless these days now that python supports the extended-call syntax (e.g. **arguments), however I need to implement something that works a bit like this:</p> <pre><code>rapply = Rapply( server_hostname ) # Set up a connection result = rapply( fn, args, kwargs ) # Remotely call the function assert result == fn( *args, **kwargs ) #Just as a test, verify that it has the expected value. </code></pre> <p>Rapply should be a class which can be used to remotely execute some arbitrary code (<code>fn</code> could be literally anything) on a remote server. It will send back the result which the <code>rapply</code> function will return. The "result" should have the same value as if I had called the function locally.</p> <p>Now let's suppose that <code>fn</code> is a user-provided function I need some way of sending it over the wire to the execution server. If I could guarantee that fn was always something simple it could could just be a string containing python source code... but what if it were not so simple? </p> <p>What if <code>fn</code> might have local dependencies: It could be a simple function which uses a class defined in a different module, is there a way of encapsulating <code>fn</code> and everything that <code>fn</code> requires which is not standard-library? An ideal solution would not require the users of this system to have much knowledge about python development. They simply want to write their function and call it.</p> <p>Just to clarify, I'm not interested in discussing what kind of network protocol might be used to implement the communication between the client &amp; server. My problem is how to encapsulate a function and its dependencies as a single object which can be serialized and remotely executed. </p> <p>I'm also not interested in the security implications of running arbitrary code on remote servers - let's just say that this system is intended purely for research and it is within a heavily firewalled environment. </p>
3
2009-02-11T11:21:41Z
536,408
<p>It sounds like you want to do the following.</p> <ul> <li><p>Define a shared filesystem space.</p></li> <li><p>Put ALL your python source in this shared filesystem space.</p></li> <li><p>Define simple agents or servers that will "execfile" a block of code.</p></li> <li><p>Your client then contacts the agent (REST protocol with POST methods works well for<br /> this) with the block of code. The agent saves the block of code and does an <code>execfile</code> on that block of code.</p></li> </ul> <p>Since all agents share a common filesystem, they all have the same Python library structure.</p> <p>We do with with a simple WSGI application we call "batch server". We have RESTful protocol for creating and checking on remote requests.</p>
4
2009-02-11T11:38:18Z
[ "python", "grid" ]
Execute arbitrary python code remotely - can it be done?
536,370
<p>I'm working on a grid system which has a number of very powerful computers. These can be used to execute python functions very quickly. My users have a number of python functions which take a long time to calculate on workstations, ideally they would like to be able to call some functions on a remote powerful server, but have it appear to be running locally.</p> <p>Python has an old function called "apply" - it's mostly useless these days now that python supports the extended-call syntax (e.g. **arguments), however I need to implement something that works a bit like this:</p> <pre><code>rapply = Rapply( server_hostname ) # Set up a connection result = rapply( fn, args, kwargs ) # Remotely call the function assert result == fn( *args, **kwargs ) #Just as a test, verify that it has the expected value. </code></pre> <p>Rapply should be a class which can be used to remotely execute some arbitrary code (<code>fn</code> could be literally anything) on a remote server. It will send back the result which the <code>rapply</code> function will return. The "result" should have the same value as if I had called the function locally.</p> <p>Now let's suppose that <code>fn</code> is a user-provided function I need some way of sending it over the wire to the execution server. If I could guarantee that fn was always something simple it could could just be a string containing python source code... but what if it were not so simple? </p> <p>What if <code>fn</code> might have local dependencies: It could be a simple function which uses a class defined in a different module, is there a way of encapsulating <code>fn</code> and everything that <code>fn</code> requires which is not standard-library? An ideal solution would not require the users of this system to have much knowledge about python development. They simply want to write their function and call it.</p> <p>Just to clarify, I'm not interested in discussing what kind of network protocol might be used to implement the communication between the client &amp; server. My problem is how to encapsulate a function and its dependencies as a single object which can be serialized and remotely executed. </p> <p>I'm also not interested in the security implications of running arbitrary code on remote servers - let's just say that this system is intended purely for research and it is within a heavily firewalled environment. </p>
3
2009-02-11T11:21:41Z
536,641
<p>You could use a SSH connection to the remote PC and run the commands on the other machine directly. You could even copy the python code to the machine and execute it.</p>
0
2009-02-11T12:55:01Z
[ "python", "grid" ]
Execute arbitrary python code remotely - can it be done?
536,370
<p>I'm working on a grid system which has a number of very powerful computers. These can be used to execute python functions very quickly. My users have a number of python functions which take a long time to calculate on workstations, ideally they would like to be able to call some functions on a remote powerful server, but have it appear to be running locally.</p> <p>Python has an old function called "apply" - it's mostly useless these days now that python supports the extended-call syntax (e.g. **arguments), however I need to implement something that works a bit like this:</p> <pre><code>rapply = Rapply( server_hostname ) # Set up a connection result = rapply( fn, args, kwargs ) # Remotely call the function assert result == fn( *args, **kwargs ) #Just as a test, verify that it has the expected value. </code></pre> <p>Rapply should be a class which can be used to remotely execute some arbitrary code (<code>fn</code> could be literally anything) on a remote server. It will send back the result which the <code>rapply</code> function will return. The "result" should have the same value as if I had called the function locally.</p> <p>Now let's suppose that <code>fn</code> is a user-provided function I need some way of sending it over the wire to the execution server. If I could guarantee that fn was always something simple it could could just be a string containing python source code... but what if it were not so simple? </p> <p>What if <code>fn</code> might have local dependencies: It could be a simple function which uses a class defined in a different module, is there a way of encapsulating <code>fn</code> and everything that <code>fn</code> requires which is not standard-library? An ideal solution would not require the users of this system to have much knowledge about python development. They simply want to write their function and call it.</p> <p>Just to clarify, I'm not interested in discussing what kind of network protocol might be used to implement the communication between the client &amp; server. My problem is how to encapsulate a function and its dependencies as a single object which can be serialized and remotely executed. </p> <p>I'm also not interested in the security implications of running arbitrary code on remote servers - let's just say that this system is intended purely for research and it is within a heavily firewalled environment. </p>
3
2009-02-11T11:21:41Z
536,649
<p><a href="http://pypy.readthedocs.org/en/latest/stackless.html#unimplemented-features" rel="nofollow">Stackless</a> had ability to pickle and unpickle running code. Unfortunately current implementation doesn't support this feature. </p>
1
2009-02-11T12:57:51Z
[ "python", "grid" ]
Execute arbitrary python code remotely - can it be done?
536,370
<p>I'm working on a grid system which has a number of very powerful computers. These can be used to execute python functions very quickly. My users have a number of python functions which take a long time to calculate on workstations, ideally they would like to be able to call some functions on a remote powerful server, but have it appear to be running locally.</p> <p>Python has an old function called "apply" - it's mostly useless these days now that python supports the extended-call syntax (e.g. **arguments), however I need to implement something that works a bit like this:</p> <pre><code>rapply = Rapply( server_hostname ) # Set up a connection result = rapply( fn, args, kwargs ) # Remotely call the function assert result == fn( *args, **kwargs ) #Just as a test, verify that it has the expected value. </code></pre> <p>Rapply should be a class which can be used to remotely execute some arbitrary code (<code>fn</code> could be literally anything) on a remote server. It will send back the result which the <code>rapply</code> function will return. The "result" should have the same value as if I had called the function locally.</p> <p>Now let's suppose that <code>fn</code> is a user-provided function I need some way of sending it over the wire to the execution server. If I could guarantee that fn was always something simple it could could just be a string containing python source code... but what if it were not so simple? </p> <p>What if <code>fn</code> might have local dependencies: It could be a simple function which uses a class defined in a different module, is there a way of encapsulating <code>fn</code> and everything that <code>fn</code> requires which is not standard-library? An ideal solution would not require the users of this system to have much knowledge about python development. They simply want to write their function and call it.</p> <p>Just to clarify, I'm not interested in discussing what kind of network protocol might be used to implement the communication between the client &amp; server. My problem is how to encapsulate a function and its dependencies as a single object which can be serialized and remotely executed. </p> <p>I'm also not interested in the security implications of running arbitrary code on remote servers - let's just say that this system is intended purely for research and it is within a heavily firewalled environment. </p>
3
2009-02-11T11:21:41Z
536,988
<p>You could use a ready-made clustering solution like <a href="http://www.parallelpython.com" rel="nofollow">Parallel Python</a>. You can relatively easily set up <a href="http://www.parallelpython.com/content/view/15/30/#QUICKCLUSTERS" rel="nofollow">multiple remote slaves and run arbitrary code on them</a>.</p>
1
2009-02-11T14:21:54Z
[ "python", "grid" ]
Execute arbitrary python code remotely - can it be done?
536,370
<p>I'm working on a grid system which has a number of very powerful computers. These can be used to execute python functions very quickly. My users have a number of python functions which take a long time to calculate on workstations, ideally they would like to be able to call some functions on a remote powerful server, but have it appear to be running locally.</p> <p>Python has an old function called "apply" - it's mostly useless these days now that python supports the extended-call syntax (e.g. **arguments), however I need to implement something that works a bit like this:</p> <pre><code>rapply = Rapply( server_hostname ) # Set up a connection result = rapply( fn, args, kwargs ) # Remotely call the function assert result == fn( *args, **kwargs ) #Just as a test, verify that it has the expected value. </code></pre> <p>Rapply should be a class which can be used to remotely execute some arbitrary code (<code>fn</code> could be literally anything) on a remote server. It will send back the result which the <code>rapply</code> function will return. The "result" should have the same value as if I had called the function locally.</p> <p>Now let's suppose that <code>fn</code> is a user-provided function I need some way of sending it over the wire to the execution server. If I could guarantee that fn was always something simple it could could just be a string containing python source code... but what if it were not so simple? </p> <p>What if <code>fn</code> might have local dependencies: It could be a simple function which uses a class defined in a different module, is there a way of encapsulating <code>fn</code> and everything that <code>fn</code> requires which is not standard-library? An ideal solution would not require the users of this system to have much knowledge about python development. They simply want to write their function and call it.</p> <p>Just to clarify, I'm not interested in discussing what kind of network protocol might be used to implement the communication between the client &amp; server. My problem is how to encapsulate a function and its dependencies as a single object which can be serialized and remotely executed. </p> <p>I'm also not interested in the security implications of running arbitrary code on remote servers - let's just say that this system is intended purely for research and it is within a heavily firewalled environment. </p>
3
2009-02-11T11:21:41Z
537,168
<p>Take a look at <a href="http://pyro.sourceforge.net/">PyRO</a> (Python Remote objects) It has the ability to set up services on all the computers in your cluster, and invoke them directly, or indirectly through a name server and a publish-subscribe mechanism. </p>
6
2009-02-11T14:56:50Z
[ "python", "grid" ]
Execute arbitrary python code remotely - can it be done?
536,370
<p>I'm working on a grid system which has a number of very powerful computers. These can be used to execute python functions very quickly. My users have a number of python functions which take a long time to calculate on workstations, ideally they would like to be able to call some functions on a remote powerful server, but have it appear to be running locally.</p> <p>Python has an old function called "apply" - it's mostly useless these days now that python supports the extended-call syntax (e.g. **arguments), however I need to implement something that works a bit like this:</p> <pre><code>rapply = Rapply( server_hostname ) # Set up a connection result = rapply( fn, args, kwargs ) # Remotely call the function assert result == fn( *args, **kwargs ) #Just as a test, verify that it has the expected value. </code></pre> <p>Rapply should be a class which can be used to remotely execute some arbitrary code (<code>fn</code> could be literally anything) on a remote server. It will send back the result which the <code>rapply</code> function will return. The "result" should have the same value as if I had called the function locally.</p> <p>Now let's suppose that <code>fn</code> is a user-provided function I need some way of sending it over the wire to the execution server. If I could guarantee that fn was always something simple it could could just be a string containing python source code... but what if it were not so simple? </p> <p>What if <code>fn</code> might have local dependencies: It could be a simple function which uses a class defined in a different module, is there a way of encapsulating <code>fn</code> and everything that <code>fn</code> requires which is not standard-library? An ideal solution would not require the users of this system to have much knowledge about python development. They simply want to write their function and call it.</p> <p>Just to clarify, I'm not interested in discussing what kind of network protocol might be used to implement the communication between the client &amp; server. My problem is how to encapsulate a function and its dependencies as a single object which can be serialized and remotely executed. </p> <p>I'm also not interested in the security implications of running arbitrary code on remote servers - let's just say that this system is intended purely for research and it is within a heavily firewalled environment. </p>
3
2009-02-11T11:21:41Z
30,859,367
<h1>Syntax:</h1> <p>cat ./test.py | sshpass -p 'password' ssh user@remote-ip "python - script-arguments-if-any for test.py script"</p> <p>1) here "test.py" is the local python script. 2) sshpass used to pass the ssh password to ssh connection</p>
0
2015-06-16T05:20:41Z
[ "python", "grid" ]
Python, Sqlite3 - How to convert a list to a BLOB cell
537,077
<p>What is the most elegant method for dumping a list in python into an sqlite3 DB as binary data (i.e., a BLOB cell)?</p> <pre><code>data = [ 0, 1, 2, 3, 4, 5 ] # now write this to db as binary data # 0000 0000 # 0000 0001 # ... # 0000 0101 </code></pre>
8
2009-02-11T14:38:06Z
537,192
<p>Assuming you want it treated as a sequence of 8-bit unsigned values, use the <code>array</code> module.</p> <pre><code>a = array.array('B', data) &gt;&gt;&gt; a.tostring() '\x00\x01\x02\x03\x04\x05' </code></pre> <p>Use different typecodes than <code>'B'</code> if you want to treat the data as different types. eg. 'b' for a sequence of signed bytes, or <code>'i'</code> for a signed integer.</p>
6
2009-02-11T15:01:45Z
[ "python", "sqlite" ]
Python, Sqlite3 - How to convert a list to a BLOB cell
537,077
<p>What is the most elegant method for dumping a list in python into an sqlite3 DB as binary data (i.e., a BLOB cell)?</p> <pre><code>data = [ 0, 1, 2, 3, 4, 5 ] # now write this to db as binary data # 0000 0000 # 0000 0001 # ... # 0000 0101 </code></pre>
8
2009-02-11T14:38:06Z
539,636
<p>It seems that Brian's solution fits your needs, but keep in mind that with that method your just storing the data as a string.</p> <p>If you want to store the raw binary data into the database (so it doesn't take up as much space), convert your data to a <strong>Binary</strong> sqlite object and then add it to your database.</p> <pre><code>query = u'''insert into testtable VALUES(?)''' b = sqlite3.Binary(some_binarydata) cur.execute(query,(b,)) con.commit() </code></pre> <p>(For some reason this doesn't seem to be documented in the python documentation)</p> <p>Here are some notes on sqlite BLOB data restrictions:</p> <p><a href="http://effbot.org/zone/sqlite-blob.htm" rel="nofollow">http://effbot.org/zone/sqlite-blob.htm</a></p>
17
2009-02-12T01:27:31Z
[ "python", "sqlite" ]
Python, Sqlite3 - How to convert a list to a BLOB cell
537,077
<p>What is the most elegant method for dumping a list in python into an sqlite3 DB as binary data (i.e., a BLOB cell)?</p> <pre><code>data = [ 0, 1, 2, 3, 4, 5 ] # now write this to db as binary data # 0000 0000 # 0000 0001 # ... # 0000 0101 </code></pre>
8
2009-02-11T14:38:06Z
1,416,888
<p>See this general solution at SourceForge which covers any arbitrary Python object (including list, tuple, dictionary, etc):</p> <p>y_serial.py module :: warehouse Python objects with SQLite</p> <p>"Serialization + persistance :: in a few lines of code, compress and annotate Python objects into SQLite; then later retrieve them chronologically by keywords without any SQL. Most useful "standard" module for a database to store schema-less data."</p> <p><a href="http://yserial.sourceforge.net" rel="nofollow">http://yserial.sourceforge.net</a></p>
1
2009-09-13T04:57:40Z
[ "python", "sqlite" ]
Python, Sqlite3 - How to convert a list to a BLOB cell
537,077
<p>What is the most elegant method for dumping a list in python into an sqlite3 DB as binary data (i.e., a BLOB cell)?</p> <pre><code>data = [ 0, 1, 2, 3, 4, 5 ] # now write this to db as binary data # 0000 0000 # 0000 0001 # ... # 0000 0101 </code></pre>
8
2009-02-11T14:38:06Z
4,464,661
<p>I have the same problem, and I'm thinking about solving this in another way.</p> <p>I think the <a href="http://docs.python.org/library/pickle.html" rel="nofollow">pickle</a> module is done exactly for something like this (serialization on python objects)</p> <p>Example (this one is for dumping to file... but I think it's easily changeble for db storage) </p> <p>Saving:</p> <pre><code># Save a dictionary into a pickle file. import pickle favorite_color = { "lion": "yellow", "kitty": "red" } pickle.dump( favorite_color, open( "save.p", "w" ) ) </code></pre> <p>Loading:</p> <pre><code># Load the dictionary back from the pickle file. import pickle favorite_color = pickle.load( open( "save.p" ) ) </code></pre> <p>IMHO I think this way is more elegant and safer(it works for any python object).</p> <p>That's my 2 cents</p> <p>UPDATE: <a href="http://stackoverflow.com/questions/198692/can-i-pickle-a-python-dictionary-into-a-sqlite3-text-field">After doing a bit of search on my idea</a>, they show some gotchas on my solution ( I can't make sql searches on that field). But I still think that it's a decent solution (if you don't need to search that field.</p>
3
2010-12-16T19:36:03Z
[ "python", "sqlite" ]
Python, Sqlite3 - How to convert a list to a BLOB cell
537,077
<p>What is the most elegant method for dumping a list in python into an sqlite3 DB as binary data (i.e., a BLOB cell)?</p> <pre><code>data = [ 0, 1, 2, 3, 4, 5 ] # now write this to db as binary data # 0000 0000 # 0000 0001 # ... # 0000 0101 </code></pre>
8
2009-02-11T14:38:06Z
15,392,922
<p>It is possible to store object data as pickle dump, jason etc but it is also possible to index, them, restrict them and run select queries that use those indices. Here is example with tuples, that can be easily applied for any other python class. All that is needed is explained in python sqlite3 documentation (somebody already posted the link). Anyway here it is all put together in the following example:</p> <pre><code>import sqlite3 import pickle def adapt_tuple(tuple): return pickle.dumps(tuple) sqlite3.register_adapter(tuple, adapt_tuple) #cannot use pickle.dumps directly because of inadequate argument signature sqlite3.register_converter("tuple", pickle.loads) def collate_tuple(string1, string2): return cmp(pickle.loads(string1), pickle.loads(string2)) ######################### # 1) Using declared types con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES) con.create_collation("cmptuple", collate_tuple) cur = con.cursor() cur.execute("create table test(p tuple unique collate cmptuple) ") cur.execute("create index tuple_collated_index on test(p collate cmptuple)") cur.execute("select name, type from sqlite_master") # where type = 'table'") print(cur.fetchall()) p = (1,2,3) p1 = (1,2) cur.execute("insert into test(p) values (?)", (p,)) cur.execute("insert into test(p) values (?)", (p1,)) cur.execute("insert into test(p) values (?)", ((10, 1),)) cur.execute("insert into test(p) values (?)", (tuple((9, 33)) ,)) cur.execute("insert into test(p) values (?)", (((9, 5), 33) ,)) try: cur.execute("insert into test(p) values (?)", (tuple((9, 33)) ,)) except Exception as e: print e cur.execute("select p from test order by p") print "\nwith declared types and default collate on column:" for raw in cur: print raw cur.execute("select p from test order by p collate cmptuple") print "\nwith declared types collate:" for raw in cur: print raw con.create_function('pycmp', 2, cmp) print "\nselect grater than using cmp function:" cur.execute("select p from test where pycmp(p,?) &gt;= 0", ((10, ),) ) for raw in cur: print raw cur.execute("select p from test where pycmp(p,?) &gt;= 0", ((3,))) for raw in cur: print raw print "\nselect grater than using collate:" cur.execute("select p from test where p &gt; ?", ((10,),) ) for raw in cur: print raw cur.execute("explain query plan select p from test where p &gt; ?", ((3,))) for raw in cur: print raw cur.close() con.close() </code></pre>
0
2013-03-13T17:57:28Z
[ "python", "sqlite" ]
Reserve memory for list in Python?
537,086
<p>When programming in Python, is it possible to reserve memory for a list that will be populated with a known number of items, so that the list will not be reallocated several times while building it? I've looked through the docs for a Python list type, and have not found anything that seems to do this. However, this type of list building shows up in a few hotspots of my code, so I want to make it as efficient as possible.</p> <p>Edit: Also, does it even make sense to do something like this in a language like Python? I'm a fairly experienced programmer, but new to Python and still getting a feel for its way of doing things. Does Python internally allocate <strong>all</strong> objects in separate heap spaces, defeating the purpose of trying to minimize allocations, or are primitives like ints, floats, etc. stored directly in lists?</p>
30
2009-02-11T14:41:14Z
537,111
<p>Just create the list at the beginning like this:</p> <pre><code>a = range(10) </code></pre> <p>Then you can assign values writing</p> <pre><code>a[7] = an object </code></pre>
0
2009-02-11T14:46:02Z
[ "python", "performance", "arrays", "memory-management", "list" ]
Reserve memory for list in Python?
537,086
<p>When programming in Python, is it possible to reserve memory for a list that will be populated with a known number of items, so that the list will not be reallocated several times while building it? I've looked through the docs for a Python list type, and have not found anything that seems to do this. However, this type of list building shows up in a few hotspots of my code, so I want to make it as efficient as possible.</p> <p>Edit: Also, does it even make sense to do something like this in a language like Python? I'm a fairly experienced programmer, but new to Python and still getting a feel for its way of doing things. Does Python internally allocate <strong>all</strong> objects in separate heap spaces, defeating the purpose of trying to minimize allocations, or are primitives like ints, floats, etc. stored directly in lists?</p>
30
2009-02-11T14:41:14Z
537,134
<p>you can create list of the known length like this:</p> <pre><code>&gt;&gt;&gt; [None] * known_number </code></pre>
11
2009-02-11T14:49:25Z
[ "python", "performance", "arrays", "memory-management", "list" ]
Reserve memory for list in Python?
537,086
<p>When programming in Python, is it possible to reserve memory for a list that will be populated with a known number of items, so that the list will not be reallocated several times while building it? I've looked through the docs for a Python list type, and have not found anything that seems to do this. However, this type of list building shows up in a few hotspots of my code, so I want to make it as efficient as possible.</p> <p>Edit: Also, does it even make sense to do something like this in a language like Python? I'm a fairly experienced programmer, but new to Python and still getting a feel for its way of doing things. Does Python internally allocate <strong>all</strong> objects in separate heap spaces, defeating the purpose of trying to minimize allocations, or are primitives like ints, floats, etc. stored directly in lists?</p>
30
2009-02-11T14:41:14Z
537,183
<p>In most of everyday code you won't need such optimization.</p> <p>However, when list efficiency becomes an issue, the first thing you should do is replace generic list with typed one from <a href="http://docs.python.org/library/array.html"><code>array</code> module</a> which is much more efficient.</p> <p>Here's how list of 4 million floating point numbers cound be created:</p> <pre><code>import array lst = array.array('f', [0.0]*4000*1000) </code></pre>
5
2009-02-11T15:00:53Z
[ "python", "performance", "arrays", "memory-management", "list" ]
Reserve memory for list in Python?
537,086
<p>When programming in Python, is it possible to reserve memory for a list that will be populated with a known number of items, so that the list will not be reallocated several times while building it? I've looked through the docs for a Python list type, and have not found anything that seems to do this. However, this type of list building shows up in a few hotspots of my code, so I want to make it as efficient as possible.</p> <p>Edit: Also, does it even make sense to do something like this in a language like Python? I'm a fairly experienced programmer, but new to Python and still getting a feel for its way of doing things. Does Python internally allocate <strong>all</strong> objects in separate heap spaces, defeating the purpose of trying to minimize allocations, or are primitives like ints, floats, etc. stored directly in lists?</p>
30
2009-02-11T14:41:14Z
537,288
<p>In Python, all objects are allocated on the heap.<br> But Python uses a special memory allocator so <code>malloc</code> won't be called every time you need a new object.<br> There are also some optimizations for small integers (and the like) which are cached; however, which types, and how, is implementation dependent.</p>
2
2009-02-11T15:19:39Z
[ "python", "performance", "arrays", "memory-management", "list" ]
Reserve memory for list in Python?
537,086
<p>When programming in Python, is it possible to reserve memory for a list that will be populated with a known number of items, so that the list will not be reallocated several times while building it? I've looked through the docs for a Python list type, and have not found anything that seems to do this. However, this type of list building shows up in a few hotspots of my code, so I want to make it as efficient as possible.</p> <p>Edit: Also, does it even make sense to do something like this in a language like Python? I'm a fairly experienced programmer, but new to Python and still getting a feel for its way of doing things. Does Python internally allocate <strong>all</strong> objects in separate heap spaces, defeating the purpose of trying to minimize allocations, or are primitives like ints, floats, etc. stored directly in lists?</p>
30
2009-02-11T14:41:14Z
537,351
<p>If you're wanting to manipulate numbers efficiently in Python then have a look at NumPy ( <a href="http://numpy.scipy.org/" rel="nofollow">http://numpy.scipy.org/</a>). It let's you do things extremely fast while still getting to use Python.</p> <p>To do what your asking in NumPy you'd do something like</p> <pre><code>import numpy as np myarray = np.zeros(4000) </code></pre> <p>which would give you an array of floating point numbers initialized to zero. You can then do very cool things like multiply whole arrays by a single factor or by other arrays and other stuff (kind of like in Matlab if you've ever used that) which is very fast (most of the actual work is happening in the highly optimized C part of the NumPy library).</p> <p>If it's not arrays of numbers your after then you're probably not going to find a way to do what you want in Python. A Python list of objects is a list of points to objects internally (I think so anyway, I'm not an expert of Python internals) so it would still be allocating each of its members as you create them.</p>
4
2009-02-11T15:35:34Z
[ "python", "performance", "arrays", "memory-management", "list" ]
Reserve memory for list in Python?
537,086
<p>When programming in Python, is it possible to reserve memory for a list that will be populated with a known number of items, so that the list will not be reallocated several times while building it? I've looked through the docs for a Python list type, and have not found anything that seems to do this. However, this type of list building shows up in a few hotspots of my code, so I want to make it as efficient as possible.</p> <p>Edit: Also, does it even make sense to do something like this in a language like Python? I'm a fairly experienced programmer, but new to Python and still getting a feel for its way of doing things. Does Python internally allocate <strong>all</strong> objects in separate heap spaces, defeating the purpose of trying to minimize allocations, or are primitives like ints, floats, etc. stored directly in lists?</p>
30
2009-02-11T14:41:14Z
537,405
<p>Here's four variants:</p> <ul> <li>an incremental list creation</li> <li>"pre-allocated" list</li> <li>array.array()</li> <li>numpy.zeros()</li> </ul> <p>&nbsp;</p> <pre><code>python -mtimeit -s"N=10**6" "a = []; app = a.append;"\ "for i in xrange(N): app(i);" 10 loops, best of 3: 390 msec per loop python -mtimeit -s"N=10**6" "a = [None]*N; app = a.append;"\ "for i in xrange(N): a[i] = i" 10 loops, best of 3: 245 msec per loop python -mtimeit -s"from array import array; N=10**6" "a = array('i', [0]*N)"\ "for i in xrange(N):" " a[i] = i" 10 loops, best of 3: 541 msec per loop python -mtimeit -s"from numpy import zeros; N=10**6" "a = zeros(N,dtype='i')"\ "for i in xrange(N):" " a[i] = i" 10 loops, best of 3: 353 msec per loop </code></pre> <p>It shows that <code>[None]*N</code> is the fastest and <code>array.array</code> is the slowest in this case.</p>
26
2009-02-11T15:47:29Z
[ "python", "performance", "arrays", "memory-management", "list" ]
Reserve memory for list in Python?
537,086
<p>When programming in Python, is it possible to reserve memory for a list that will be populated with a known number of items, so that the list will not be reallocated several times while building it? I've looked through the docs for a Python list type, and have not found anything that seems to do this. However, this type of list building shows up in a few hotspots of my code, so I want to make it as efficient as possible.</p> <p>Edit: Also, does it even make sense to do something like this in a language like Python? I'm a fairly experienced programmer, but new to Python and still getting a feel for its way of doing things. Does Python internally allocate <strong>all</strong> objects in separate heap spaces, defeating the purpose of trying to minimize allocations, or are primitives like ints, floats, etc. stored directly in lists?</p>
30
2009-02-11T14:41:14Z
13,865,566
<p>Take a look at this:</p> <pre><code>In [7]: %timeit array.array('f', [0.0]*4000*1000) 1 loops, best of 3: 306 ms per loop In [8]: %timeit array.array('f', [0.0])*4000*1000 100 loops, best of 3: 5.96 ms per loop In [11]: %timeit np.zeros(4000*1000, dtype='f') 100 loops, best of 3: 6.04 ms per loop In [9]: %timeit [0.0]*4000*1000 10 loops, best of 3: 32.4 ms per loop </code></pre> <p>So don't ever use <code>array.array('f', [0.0]*N)</code>, use <code>array.array('f', [0.0])*N</code> or <code>numpy.zeros</code>.</p>
7
2012-12-13T17:52:13Z
[ "python", "performance", "arrays", "memory-management", "list" ]
python, funny business with threads and IDEs?
537,196
<p>Maybe i cant do what i want? I want to have 1 thread do w/e it wants and a 2nd thread to recv user input to set the quit flag. using this code i want to enter q anytime to quit or have it timeout after printing hey 6 times</p> <pre><code>import sys import threading import time class MyThread ( threading.Thread ): def run (s): try: s.wantQuit = 0 while(not s.wantQuit): print "want input" button = raw_input() if button == "q": s.wantQuit=1 except KeyboardInterrupt: s.wantQuit = 1 print "abort with KeyboardInterrupt" print "done mythread" myThread = MyThread () myThread.start() a=5 while not myThread.wantQuit: print "hey" if (a == 0): break; a = a-1; time.sleep(1) myThread.wantQuit=1 print "main thread done" </code></pre> <p>what happens is instead of two threads i have the main one printing hey 4/6 times, then a dialog poping up asking for my input and the app being locked up until i enter it. WTF?! </p> <pre><code>want input hey hey hey hey abort with KeyboardInterrupt done mythread main thread done </code></pre> <p>i am using PyScripter (it has debugging), i also tried pydle which doesnt seem to allow me to enter input and locks up eventually after running it once.</p>
0
2009-02-11T15:02:29Z
537,480
<p>The problem here is that raw_input waits for an enter to flush the input stream; check out its <a href="http://docs.python.org/library/functions.html#raw_input" rel="nofollow">documentation</a>. PyScripter is probably seeing that the program is waiting for an input and giving you an input box (don't know for sure, never used it.)</p> <p>The program works exactly as I expect it to from the command line; the secondary thread blocks on the raw_input until I hit "q[enter]", at which point the program ends.</p> <p>It is not, AFAICS, easy to check and see if a character is available in the input stream before blocking on a read call. You probably should check out <a href="http://mail.python.org/pipermail/python-list/2005-January/303883.html" rel="nofollow">this thread</a> on how to read a character in a blocking fashion without requiring an [enter], and then <a href="http://mail.python.org/pipermail/python-list/2005-January/302469.html" rel="nofollow">this post</a> on the challenge of reading a character without blocking at all.</p> <p>You can possibly use a combination of msvcrt.kbhit on windows and <a href="http://www.python.org/doc/faq/library/#how-do-i-get-a-single-keypress-at-a-time" rel="nofollow">this recipe</a> from the python FAQ to get the q character without requiring a keypress, but I'll leave it as an exercise to the reader.</p> <p>Addendum: One thing you could do would be to use the select library to set a timeout on reads from the keyboard, which will make your program act more like you expect:</p> <pre><code>import sys import threading import time import select def timeout_read(n_chars): r, _, _ = select.select([sys.stdin], [], [], 1) return r[0].read(n_chars) if r else "" class MyThread (threading.Thread): def run (self): try: self.wantQuit = 0 while not self.wantQuit: print "want input" button = timeout_read(1) if button == "q": self.wantQuit=1 except KeyboardInterrupt: self.wantQuit = 1 print "abort with KeyboardInterrupt" print "done mythread" myThread = MyThread () myThread.start() a=5 while not myThread.wantQuit: print "hey" if (a == 0): break; a = a-1; time.sleep(1) myThread.wantQuit=1 print "main thread done" </code></pre> <p>Note that you will still need to press "q[enter]" with this solution.</p>
2
2009-02-11T16:02:40Z
[ "python", "multithreading", "ide" ]
How would you set up a python web server with multiple vhosts?
537,399
<p>I've been told wsgi is the way to go and not mod_python. But more specifically, how would you set up your multi website server environment? Choice of web server, etc?</p>
1
2009-02-11T15:46:06Z
537,504
<p>I'd recommend Nginx for the web server. Fast and easy to set up. </p> <p>You'd probably want to have one unix user per vhost - so every home directory holds its own application, python environment and server configuration. This allows you to restart a particular app safely, simply by killing worker processes that your vhost owns. </p> <p>Just a tip, hope it helps.</p>
1
2009-02-11T16:08:12Z
[ "python", "webserver", "environment", "wsgi" ]
How would you set up a python web server with multiple vhosts?
537,399
<p>I've been told wsgi is the way to go and not mod_python. But more specifically, how would you set up your multi website server environment? Choice of web server, etc?</p>
1
2009-02-11T15:46:06Z
537,518
<p>You could use Apache and <a href="http://www.modwsgi.org/" rel="nofollow">mod_wsgi</a>. That way, you can still use Apache's built-in support for vhosts.</p>
0
2009-02-11T16:11:15Z
[ "python", "webserver", "environment", "wsgi" ]
How would you set up a python web server with multiple vhosts?
537,399
<p>I've been told wsgi is the way to go and not mod_python. But more specifically, how would you set up your multi website server environment? Choice of web server, etc?</p>
1
2009-02-11T15:46:06Z
537,521
<p>Apache+mod_wsgi is a common choice.</p> <p>Here's a simple example vhost, setup up to map any requests for /wsgi/something to the application (which can then look at PATH_INFO to choose an action, or however you are doing your dispatching). The root URL '/' is also routed to the WSGI application.</p> <pre><code>LoadModule wsgi_module /usr/local/lib/mod_wsgi.so ... &lt;VirtualHost *:80&gt; ServerName www.example.com DocumentRoot /www/example/htdocs WSGIScriptAliasMatch ^/$ /www/example/application.py WSGIScriptAlias /wsgi /www/example/application.py &lt;/VirtualHost&gt; </code></pre> <p>You can use the WSGIProcessGroup directive to separate handlers for different vhosts if you like. If you need vhosts' scripts to be run under different users you'll need to use WSGIDaemonProcess instead of the embedded Python interpreter.</p> <p>application.py would, when run, leave your WSGI callable in the global ‘application’ variable. You can also add a run-as-main footer for compatibility with old-school CGI:</p> <pre><code>#!/usr/bin/env python from mymodule import MyApplication application= MyApplication() if __name__=='main': import wsgiref.handlers wsgiref.handlers.CGIHandler().run(application) </code></pre>
4
2009-02-11T16:11:33Z
[ "python", "webserver", "environment", "wsgi" ]
Standard python interpreter has a vi command mode?
537,522
<p>this is going to sound pretty ignorant, but:</p> <p>I was working a bit in the python interpreter (python 2.4 on RHEL 5.3), and suddenly found myself in what seems to be a 'vi command mode'. That is, I can edit previous commands with typical vi key bindings, going left with h, deleting with x...</p> <p>I love it - the only thing is, I don't know how I got here (perhaps it's through one of the modules I've imported: pylab/matplotlib?).</p> <p>Can anyone shed some light on how to enable this mode in the interpreter?</p>
20
2009-02-11T16:11:44Z
537,633
<p>This kind of all depends on a few things.</p> <p>First of all, the python shell uses readline, and as such, your <code>~/.inputrc</code> is important here. That's the same with psql the PostgreSQL command-line interpreter and mysql the MySQL shell. All of those can be configured to use vi-style command bindings, with history etc.</p> <p><code>&lt;ESC&gt;</code> will put you into vi mode at the python shell once you've got your editing mode set to vi</p> <p>You may need the following definition in your <code>~/.inputrc</code></p> <pre><code>set editing-mode vi </code></pre> <p><strong>OSX info</strong></p> <p>OSX uses libedit which uses ~/.editrc. You can <em>man editrc</em> for more information.</p> <p>For example, to mimick a popular key combination which searches in your history, you can add the following to your .editrc</p> <pre><code>bind "^R" em-inc-search-prev </code></pre>
24
2009-02-11T16:32:38Z
[ "python", "vi" ]
Standard python interpreter has a vi command mode?
537,522
<p>this is going to sound pretty ignorant, but:</p> <p>I was working a bit in the python interpreter (python 2.4 on RHEL 5.3), and suddenly found myself in what seems to be a 'vi command mode'. That is, I can edit previous commands with typical vi key bindings, going left with h, deleting with x...</p> <p>I love it - the only thing is, I don't know how I got here (perhaps it's through one of the modules I've imported: pylab/matplotlib?).</p> <p>Can anyone shed some light on how to enable this mode in the interpreter?</p>
20
2009-02-11T16:11:44Z
538,573
<p>Ctrl-Alt-J switches from Emacs mode to Vi mode in <a href="http://tiswww.case.edu/php/chet/readline/rluserman.html#SEC22">readline programs</a>.</p> <p>Alternatively add "set editing-mode vi" to your ~/.inputrc</p>
18
2009-02-11T20:18:07Z
[ "python", "vi" ]
Standard python interpreter has a vi command mode?
537,522
<p>this is going to sound pretty ignorant, but:</p> <p>I was working a bit in the python interpreter (python 2.4 on RHEL 5.3), and suddenly found myself in what seems to be a 'vi command mode'. That is, I can edit previous commands with typical vi key bindings, going left with h, deleting with x...</p> <p>I love it - the only thing is, I don't know how I got here (perhaps it's through one of the modules I've imported: pylab/matplotlib?).</p> <p>Can anyone shed some light on how to enable this mode in the interpreter?</p>
20
2009-02-11T16:11:44Z
29,808,730
<p>For Mac OS X 10.10.3, python2.7, vi mode can be configured by placing "bind -v" in ~/.editrc. The last few paragraphs of the man page hint at this.</p>
2
2015-04-22T21:01:20Z
[ "python", "vi" ]
Standard python interpreter has a vi command mode?
537,522
<p>this is going to sound pretty ignorant, but:</p> <p>I was working a bit in the python interpreter (python 2.4 on RHEL 5.3), and suddenly found myself in what seems to be a 'vi command mode'. That is, I can edit previous commands with typical vi key bindings, going left with h, deleting with x...</p> <p>I love it - the only thing is, I don't know how I got here (perhaps it's through one of the modules I've imported: pylab/matplotlib?).</p> <p>Can anyone shed some light on how to enable this mode in the interpreter?</p>
20
2009-02-11T16:11:44Z
36,364,300
<p>Use <a href="https://docs.python.org/3/library/readline.html#readline.parse_and_bind" rel="nofollow">readline.parse_and_bind</a> method. For example, try on python interactive console:</p> <pre><code>import readline readline.parse_and_bind("set editing-mode vi") </code></pre> <p>It seems any command you can set in .inputrc you can set via this method too. I tried it in Python 2.7 and 3.5.1.</p> <p>See also <code>man readline</code></p>
0
2016-04-01T19:22:22Z
[ "python", "vi" ]
How can I create multiple hashes of a file using only one pass?
537,542
<p>How can I get a MD5, SHA and other hashes from a file but only doing one pass? I have 100mb files, so I'd hate to process those 100MB files multiple times.</p>
6
2009-02-11T16:17:38Z
537,585
<p>Something like this perhaps?</p> <pre><code>&gt;&gt;&gt; import hashlib &gt;&gt;&gt; hashes = (hashlib.md5(), hashlib.sha1()) &gt;&gt;&gt; f = open('some_file', 'r') &gt;&gt;&gt; for line in f: ... for hash in hashes: ... hash.update(line) ... &gt;&gt;&gt; for hash in hashes: ... print hash.name, hash.hexdigest() </code></pre> <p>or loop over f.read(1024) or something like that to get fixed-length blocks</p>
15
2009-02-11T16:25:24Z
[ "python", "hash" ]
How can I create multiple hashes of a file using only one pass?
537,542
<p>How can I get a MD5, SHA and other hashes from a file but only doing one pass? I have 100mb files, so I'd hate to process those 100MB files multiple times.</p>
6
2009-02-11T16:17:38Z
537,597
<p>I don't know Python but I am familiar w/ hash calculations.</p> <p>If you handle the reading of files manually, just read in one block (of 256 bytes or 4096 bytes or whatever) at a time, and pass each block of data to update the hash of each algorithm. (you'll have to initialize state at the beginning and finalize the state at the end.)</p>
3
2009-02-11T16:26:27Z
[ "python", "hash" ]
How can I create multiple hashes of a file using only one pass?
537,542
<p>How can I get a MD5, SHA and other hashes from a file but only doing one pass? I have 100mb files, so I'd hate to process those 100MB files multiple times.</p>
6
2009-02-11T16:17:38Z
537,916
<p>Here's a modified <a href="http://stackoverflow.com/questions/537542/how-can-i-create-multiple-hashes-of-a-file-using-only-one-pass/537585#537585"><code>@ʞɔıu</code>'s answer</a> using <a href="http://stackoverflow.com/questions/537542/how-can-i-create-multiple-hashes-of-a-file-using-only-one-pass/537597#537597"><code>@Jason S</code>' suggestion</a>. </p> <pre><code>from __future__ import with_statement from hashlib import md5, sha1 filename = 'hash_one-pass.py' hashes = md5(), sha1() chunksize = max(4096, max(h.block_size for h in hashes)) with open(filename, 'rb') as f: while True: chunk = f.read(chunksize) if not chunk: break for h in hashes: h.update(chunk) for h in hashes: print h.name, h.hexdigest() </code></pre>
6
2009-02-11T17:38:04Z
[ "python", "hash" ]
Python IDE built into Visual Studio 2008?
537,689
<p>Hi I develop in Visual Studio 2008 a lot and would like to find an addin like vsphp which enables intellisense and debugging in Visual Studio. Is IronStudio what I am looking for? As far as I understand IronStudio is a Plugin for .NET.</p> <p>If there is no Plugin for Visual Studio 2008 whats a great IDE for a python newbee who loves Visual Studio (hate netbeans and eclipse sorry just don't feel the love)</p> <p>Also if IronPython Studio is an IDE do I want the Isolated or Integrated Version? I don't seem to understand the name.</p> <p>I installed integrated and got this: <a href="http://dl.getdropbox.com/u/5910/Jing/2009-02-11_1750.png">http://dl.getdropbox.com/u/5910/Jing/2009-02-11_1750.png</a> :( no console like here: <a href="http://www.codeplex.com/IronPythonStudio">http://www.codeplex.com/IronPythonStudio</a></p>
16
2009-02-11T16:42:09Z
537,724
<p>I had a similar dilemma when I first started writing in Python. I couldn't find any plugins for VS so I tried a few alternatives:</p> <ul> <li>IDLE - comes packaged with Python and works but felt very cludgy to me</li> <li><a href="http://www.wingware.com/" rel="nofollow">Wingware Python IDE</a> - not free, but seemed to have pretty good debugging capabilities</li> <li><a href="http://www.e-texteditor.com/" rel="nofollow">e-texteditor</a> - has nice syntax highlighting but running Python script from it frequently causes issues.</li> <li><a href="http://www.eclipse.org/" rel="nofollow">Eclipse</a> with <a href="http://pydev.sourceforge.net/" rel="nofollow">PyDev</a> - is what I now use - syntax highlighting, auto-completion, debugging capabilities etc. etc.</li> </ul> <p>There's a couple of reviews of options that might be of use to you:</p> <ul> <li><a href="http://spyced.blogspot.com/2005/09/review-of-6-python-ides.html" rel="nofollow">Jonathan Ellis's Programming Blog</a></li> <li><a href="http://en.wikipedia.org/wiki/Comparison_of_integrated_development_environments" rel="nofollow">Wikipedia</a></li> </ul> <p>Personally, I'd recommend Eclipse + PyDev :-)</p> <p><strong>[Edit]</strong> Iron Python looks pretty cool - might have to check that one out!</p> <p><strong>[Update 25/04/2013]</strong> I just use <a href="http://www.jetbrains.com/pycharm/" rel="nofollow">PyCharm</a> these days. Absolutely fantastic IDE and it even understands DJango</p>
6
2009-02-11T16:48:18Z
[ "python", "visual-studio-2008", "ide" ]
Python IDE built into Visual Studio 2008?
537,689
<p>Hi I develop in Visual Studio 2008 a lot and would like to find an addin like vsphp which enables intellisense and debugging in Visual Studio. Is IronStudio what I am looking for? As far as I understand IronStudio is a Plugin for .NET.</p> <p>If there is no Plugin for Visual Studio 2008 whats a great IDE for a python newbee who loves Visual Studio (hate netbeans and eclipse sorry just don't feel the love)</p> <p>Also if IronPython Studio is an IDE do I want the Isolated or Integrated Version? I don't seem to understand the name.</p> <p>I installed integrated and got this: <a href="http://dl.getdropbox.com/u/5910/Jing/2009-02-11_1750.png">http://dl.getdropbox.com/u/5910/Jing/2009-02-11_1750.png</a> :( no console like here: <a href="http://www.codeplex.com/IronPythonStudio">http://www.codeplex.com/IronPythonStudio</a></p>
16
2009-02-11T16:42:09Z
537,755
<p>Provided that you have Visual Studio 2008 and the VS 2k8 Shell Integrated Redistributable package, IronPython Studio Integrated will plug into the VS 2k8 IDE.</p> <p><a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=40646580-97FA-4698-B65F-620D4B4B1ED7&amp;displaylang=en" rel="nofollow">Visual Studio 2008 Shell (Integrated)</a></p> <p><a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=c6a64e02-6fd6-41e3-a3fd-399d174a84b7&amp;displaylang=en" rel="nofollow">Visual Studio 2010 beta 2 Shell (Integrated)</a></p>
5
2009-02-11T16:54:35Z
[ "python", "visual-studio-2008", "ide" ]
Python IDE built into Visual Studio 2008?
537,689
<p>Hi I develop in Visual Studio 2008 a lot and would like to find an addin like vsphp which enables intellisense and debugging in Visual Studio. Is IronStudio what I am looking for? As far as I understand IronStudio is a Plugin for .NET.</p> <p>If there is no Plugin for Visual Studio 2008 whats a great IDE for a python newbee who loves Visual Studio (hate netbeans and eclipse sorry just don't feel the love)</p> <p>Also if IronPython Studio is an IDE do I want the Isolated or Integrated Version? I don't seem to understand the name.</p> <p>I installed integrated and got this: <a href="http://dl.getdropbox.com/u/5910/Jing/2009-02-11_1750.png">http://dl.getdropbox.com/u/5910/Jing/2009-02-11_1750.png</a> :( no console like here: <a href="http://www.codeplex.com/IronPythonStudio">http://www.codeplex.com/IronPythonStudio</a></p>
16
2009-02-11T16:42:09Z
537,761
<p>Have a look at <a href="http://code.google.com/p/pyscripter/">PyScripter</a>, I haven't tried it extensively but heard good things about it.</p> <p>It's not an addon to Visual Studio, it's an independent IDE.</p>
8
2009-02-11T16:55:48Z
[ "python", "visual-studio-2008", "ide" ]
Python IDE built into Visual Studio 2008?
537,689
<p>Hi I develop in Visual Studio 2008 a lot and would like to find an addin like vsphp which enables intellisense and debugging in Visual Studio. Is IronStudio what I am looking for? As far as I understand IronStudio is a Plugin for .NET.</p> <p>If there is no Plugin for Visual Studio 2008 whats a great IDE for a python newbee who loves Visual Studio (hate netbeans and eclipse sorry just don't feel the love)</p> <p>Also if IronPython Studio is an IDE do I want the Isolated or Integrated Version? I don't seem to understand the name.</p> <p>I installed integrated and got this: <a href="http://dl.getdropbox.com/u/5910/Jing/2009-02-11_1750.png">http://dl.getdropbox.com/u/5910/Jing/2009-02-11_1750.png</a> :( no console like here: <a href="http://www.codeplex.com/IronPythonStudio">http://www.codeplex.com/IronPythonStudio</a></p>
16
2009-02-11T16:42:09Z
537,903
<p>I'll second one of Jon's suggestions: PyDev and Eclipse. This is great if you are already using Eclipse for other development.</p> <p>You can grab it (and links to the Eclipse platform) from here: <a href="http://pydev.sourceforge.net/download.html" rel="nofollow">http://pydev.sourceforge.net/download.html</a></p>
2
2009-02-11T17:33:52Z
[ "python", "visual-studio-2008", "ide" ]
Python IDE built into Visual Studio 2008?
537,689
<p>Hi I develop in Visual Studio 2008 a lot and would like to find an addin like vsphp which enables intellisense and debugging in Visual Studio. Is IronStudio what I am looking for? As far as I understand IronStudio is a Plugin for .NET.</p> <p>If there is no Plugin for Visual Studio 2008 whats a great IDE for a python newbee who loves Visual Studio (hate netbeans and eclipse sorry just don't feel the love)</p> <p>Also if IronPython Studio is an IDE do I want the Isolated or Integrated Version? I don't seem to understand the name.</p> <p>I installed integrated and got this: <a href="http://dl.getdropbox.com/u/5910/Jing/2009-02-11_1750.png">http://dl.getdropbox.com/u/5910/Jing/2009-02-11_1750.png</a> :( no console like here: <a href="http://www.codeplex.com/IronPythonStudio">http://www.codeplex.com/IronPythonStudio</a></p>
16
2009-02-11T16:42:09Z
1,152,075
<p>Java based IDE's are no good they tend to be fat, slow, and unpolished. Eclipse has a poor programming paradigm that is unnecesarrily confusing. The many IDE vendors made a mistake by quitting their native products and basing them instead on Eclipse. They can't differentiate themselves and the experience is awful. Real shame actually. VS needs competition but they all rolled over and died.</p>
5
2009-07-20T07:13:11Z
[ "python", "visual-studio-2008", "ide" ]
Python IDE built into Visual Studio 2008?
537,689
<p>Hi I develop in Visual Studio 2008 a lot and would like to find an addin like vsphp which enables intellisense and debugging in Visual Studio. Is IronStudio what I am looking for? As far as I understand IronStudio is a Plugin for .NET.</p> <p>If there is no Plugin for Visual Studio 2008 whats a great IDE for a python newbee who loves Visual Studio (hate netbeans and eclipse sorry just don't feel the love)</p> <p>Also if IronPython Studio is an IDE do I want the Isolated or Integrated Version? I don't seem to understand the name.</p> <p>I installed integrated and got this: <a href="http://dl.getdropbox.com/u/5910/Jing/2009-02-11_1750.png">http://dl.getdropbox.com/u/5910/Jing/2009-02-11_1750.png</a> :( no console like here: <a href="http://www.codeplex.com/IronPythonStudio">http://www.codeplex.com/IronPythonStudio</a></p>
16
2009-02-11T16:42:09Z
3,042,402
<p><a href="http://www.ironpython.net" rel="nofollow">IronPython tools for Visual Studio 2010.</a> is fairly well intergrated. I know you asked for 2008 but now that 2010 is out ;)</p>
4
2010-06-15T03:46:43Z
[ "python", "visual-studio-2008", "ide" ]
Python IDE built into Visual Studio 2008?
537,689
<p>Hi I develop in Visual Studio 2008 a lot and would like to find an addin like vsphp which enables intellisense and debugging in Visual Studio. Is IronStudio what I am looking for? As far as I understand IronStudio is a Plugin for .NET.</p> <p>If there is no Plugin for Visual Studio 2008 whats a great IDE for a python newbee who loves Visual Studio (hate netbeans and eclipse sorry just don't feel the love)</p> <p>Also if IronPython Studio is an IDE do I want the Isolated or Integrated Version? I don't seem to understand the name.</p> <p>I installed integrated and got this: <a href="http://dl.getdropbox.com/u/5910/Jing/2009-02-11_1750.png">http://dl.getdropbox.com/u/5910/Jing/2009-02-11_1750.png</a> :( no console like here: <a href="http://www.codeplex.com/IronPythonStudio">http://www.codeplex.com/IronPythonStudio</a></p>
16
2009-02-11T16:42:09Z
5,258,719
<p>Python tools for Visual Studio 2010 is out now <a href="http://ironpython.codeplex.com/releases/view/41236" rel="nofollow">http://ironpython.codeplex.com/releases/view/41236</a></p>
2
2011-03-10T11:00:21Z
[ "python", "visual-studio-2008", "ide" ]
Python IDE built into Visual Studio 2008?
537,689
<p>Hi I develop in Visual Studio 2008 a lot and would like to find an addin like vsphp which enables intellisense and debugging in Visual Studio. Is IronStudio what I am looking for? As far as I understand IronStudio is a Plugin for .NET.</p> <p>If there is no Plugin for Visual Studio 2008 whats a great IDE for a python newbee who loves Visual Studio (hate netbeans and eclipse sorry just don't feel the love)</p> <p>Also if IronPython Studio is an IDE do I want the Isolated or Integrated Version? I don't seem to understand the name.</p> <p>I installed integrated and got this: <a href="http://dl.getdropbox.com/u/5910/Jing/2009-02-11_1750.png">http://dl.getdropbox.com/u/5910/Jing/2009-02-11_1750.png</a> :( no console like here: <a href="http://www.codeplex.com/IronPythonStudio">http://www.codeplex.com/IronPythonStudio</a></p>
16
2009-02-11T16:42:09Z
10,888,693
<p>IronPython and Python Tools for Visual Studio (PTVS) are different things.</p> <p>PTVS <a href="http://pytools.codeplex.com/" rel="nofollow">http://pytools.codeplex.com/</a> is a free &amp; open source plug-in for Visual Studio 2010 from Microsoft's Developer Division. It allows you to code python using Visual Studio, gaining the benefits to use all the major productivity features of Visual Studio.</p> <p>PTVS is compatible with IronPython and CPython, which are Python distributions where you run your code.</p> <p>CPython is the traditional Python distribution while IronPython <a href="http://ironpython.net" rel="nofollow">http://ironpython.net</a> is an alternate that allows you to run python over .Net and allows you to user other .Net libraries on your applications.</p>
1
2012-06-04T21:33:23Z
[ "python", "visual-studio-2008", "ide" ]
Python IDE built into Visual Studio 2008?
537,689
<p>Hi I develop in Visual Studio 2008 a lot and would like to find an addin like vsphp which enables intellisense and debugging in Visual Studio. Is IronStudio what I am looking for? As far as I understand IronStudio is a Plugin for .NET.</p> <p>If there is no Plugin for Visual Studio 2008 whats a great IDE for a python newbee who loves Visual Studio (hate netbeans and eclipse sorry just don't feel the love)</p> <p>Also if IronPython Studio is an IDE do I want the Isolated or Integrated Version? I don't seem to understand the name.</p> <p>I installed integrated and got this: <a href="http://dl.getdropbox.com/u/5910/Jing/2009-02-11_1750.png">http://dl.getdropbox.com/u/5910/Jing/2009-02-11_1750.png</a> :( no console like here: <a href="http://www.codeplex.com/IronPythonStudio">http://www.codeplex.com/IronPythonStudio</a></p>
16
2009-02-11T16:42:09Z
16,182,502
<p>Why don't you try the Aptana studio. It is similar to the Eclipse and PyDev. But is an separate IDE based upon python and web development.</p>
0
2013-04-24T02:43:28Z
[ "python", "visual-studio-2008", "ide" ]
Iterating over a string
538,346
<p>In C++, I could do:</p> <pre><code>for (int i = 0; i &lt; str.length(); ++i) std::cout &lt;&lt; str[i] &lt;&lt; std::endl; </code></pre> <p>How do I iterate over a string in Python?</p>
282
2009-02-11T19:22:15Z
538,352
<p>Even easier:</p> <pre><code>for c in "test": print c </code></pre>
65
2009-02-11T19:24:12Z
[ "python", "string", "iteration" ]
Iterating over a string
538,346
<p>In C++, I could do:</p> <pre><code>for (int i = 0; i &lt; str.length(); ++i) std::cout &lt;&lt; str[i] &lt;&lt; std::endl; </code></pre> <p>How do I iterate over a string in Python?</p>
282
2009-02-11T19:22:15Z
538,374
<p>As Johannes pointed out, </p> <pre><code>for c in "string": #do something with c </code></pre> <p>You can iterate pretty much anything in python using the <code>for loop</code> construct, </p> <p>for example, <code>open("file.txt")</code> returns a file object (and opens the file), iterating over it iterates over lines in that file</p> <pre><code>for line in open(filename): # do something with line </code></pre> <p>If that seems like magic, well it kinda is, but the idea behind it is really simple. </p> <p>There's a simple iterator protocol that can be applied to any kind of object to make the <code>for</code> loop work on it.</p> <p>Simply implement an iterator that defines a <code>next()</code> method, and implement an <code>__iter__</code> method on a class to make it iterable. (the <code>__iter__</code> of course, should return an iterator object, that is, an object that defines <code>next()</code>)</p> <p><a href="http://docs.python.org/library/stdtypes.html#iterator-types">See official documentation</a></p>
213
2009-02-11T19:30:23Z
[ "python", "string", "iteration" ]
Iterating over a string
538,346
<p>In C++, I could do:</p> <pre><code>for (int i = 0; i &lt; str.length(); ++i) std::cout &lt;&lt; str[i] &lt;&lt; std::endl; </code></pre> <p>How do I iterate over a string in Python?</p>
282
2009-02-11T19:22:15Z
555,631
<p>Just to make a more comprehensive answer, the C way of iterating over a string can apply in Python, if you really wanna force a square peg into a round hole.</p> <pre><code>i = 0 while i &lt; len(str): print str[i] i += 1 </code></pre> <p>But then again, why do that when strings are inherently iterable?</p> <pre><code>for i in str: print i </code></pre>
24
2009-02-17T05:36:55Z
[ "python", "string", "iteration" ]
Iterating over a string
538,346
<p>In C++, I could do:</p> <pre><code>for (int i = 0; i &lt; str.length(); ++i) std::cout &lt;&lt; str[i] &lt;&lt; std::endl; </code></pre> <p>How do I iterate over a string in Python?</p>
282
2009-02-11T19:22:15Z
4,547,728
<p>If you need access to the index as you iterate through the string, use <a href="http://docs.python.org/library/functions.html#enumerate"><code>enumerate()</code></a>:</p> <pre><code>&gt;&gt;&gt; for i, c in enumerate('test'): ... print i, c ... 0 t 1 e 2 s 3 t </code></pre>
169
2010-12-28T16:54:32Z
[ "python", "string", "iteration" ]
Iterating over a string
538,346
<p>In C++, I could do:</p> <pre><code>for (int i = 0; i &lt; str.length(); ++i) std::cout &lt;&lt; str[i] &lt;&lt; std::endl; </code></pre> <p>How do I iterate over a string in Python?</p>
282
2009-02-11T19:22:15Z
34,354,312
<p>If you would like to use a more functional approach to iterating over a string (perhaps to transform it somehow), you can split the string into characters, apply a function to each one, then join the resulting list of characters back into a string.</p> <p>A string is inherently a list of characters, hence 'map' will iterate over the string - as second argument - applying the function - the first argument - to each one.</p> <p>For example, here I use a simple lambda approach since all I want to do is a trivial modification to the character: here, to increment each character value:</p> <pre><code>&gt;&gt;&gt; ''.join(map(lambda x: chr(ord(x)+1), "HAL")) 'IBM' </code></pre> <p>or more generally:</p> <pre><code>&gt;&gt;&gt; ''.join(map(my_function, my_string)) </code></pre> <p>where my_function takes a char value and returns a char value.</p>
3
2015-12-18T11:11:28Z
[ "python", "string", "iteration" ]
Handling very large numbers in Python
538,551
<p>I've been considering fast poker hand evaluation in Python. It occurred to me that one way to speed the process up would be to represent all the card faces and suits as prime numbers and multiply them together to represent the hands. To whit:</p> <pre><code>class PokerCard: faces = '23456789TJQKA' suits = 'cdhs' facePrimes = [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 53, 59, 61] suitPrimes = [2, 3, 5, 7] </code></pre> <p>AND</p> <pre><code> def HashVal(self): return PokerCard.facePrimes[self.cardFace] * PokerCard.suitPrimes[self.cardSuit] </code></pre> <p>This would give each hand a numeric value that, through modulo could tell me how many kings are in the hand or how many hearts. For example, any hand with five or more clubs in it would divide evenly by 2^5; any hand with four kings would divide evenly by 59^4, etc.</p> <p>The problem is that a seven-card hand like AcAdAhAsKdKhKs has a hash value of approximately 62.7 quadrillion, which would take considerably more than 32 bits to represent internally. Is there a way to store such large numbers in Python that will allow me to perform arithmetic operations on it?</p>
48
2009-02-11T20:13:45Z
538,571
<p>python supports arbitrarily large integers naturally:</p> <pre><code>In [1]: 59**3*61**4*2*3*5*7*3*5*7 Out[1]: 62702371781194950 In [2]: _ % 61**4 Out[2]: 0 </code></pre>
13
2009-02-11T20:18:04Z
[ "python", "optimization", "largenumber" ]
Handling very large numbers in Python
538,551
<p>I've been considering fast poker hand evaluation in Python. It occurred to me that one way to speed the process up would be to represent all the card faces and suits as prime numbers and multiply them together to represent the hands. To whit:</p> <pre><code>class PokerCard: faces = '23456789TJQKA' suits = 'cdhs' facePrimes = [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 53, 59, 61] suitPrimes = [2, 3, 5, 7] </code></pre> <p>AND</p> <pre><code> def HashVal(self): return PokerCard.facePrimes[self.cardFace] * PokerCard.suitPrimes[self.cardSuit] </code></pre> <p>This would give each hand a numeric value that, through modulo could tell me how many kings are in the hand or how many hearts. For example, any hand with five or more clubs in it would divide evenly by 2^5; any hand with four kings would divide evenly by 59^4, etc.</p> <p>The problem is that a seven-card hand like AcAdAhAsKdKhKs has a hash value of approximately 62.7 quadrillion, which would take considerably more than 32 bits to represent internally. Is there a way to store such large numbers in Python that will allow me to perform arithmetic operations on it?</p>
48
2009-02-11T20:13:45Z
538,583
<p>Python supports a "bignum" integer type which can work with arbitrarily large numbers. In Python 2.5+, this type is called <code>long</code> and is separate from the <code>int</code> type, but the interpreter will automatically use whichever is more appropriate. In Python 3.0+, the <code>int</code> type has been dropped completely.</p> <p>That's just an implementation detail, though — as long as you have version 2.5 or better, just perform standard math operations and any number which exceeds the boundaries of 32-bit math will be automatically (and transparently) converted to a bignum.</p> <p>You can find all the gory details in <a href="http://www.python.org/dev/peps/pep-0237">PEP 0237</a>.</p>
71
2009-02-11T20:19:45Z
[ "python", "optimization", "largenumber" ]
Handling very large numbers in Python
538,551
<p>I've been considering fast poker hand evaluation in Python. It occurred to me that one way to speed the process up would be to represent all the card faces and suits as prime numbers and multiply them together to represent the hands. To whit:</p> <pre><code>class PokerCard: faces = '23456789TJQKA' suits = 'cdhs' facePrimes = [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 53, 59, 61] suitPrimes = [2, 3, 5, 7] </code></pre> <p>AND</p> <pre><code> def HashVal(self): return PokerCard.facePrimes[self.cardFace] * PokerCard.suitPrimes[self.cardSuit] </code></pre> <p>This would give each hand a numeric value that, through modulo could tell me how many kings are in the hand or how many hearts. For example, any hand with five or more clubs in it would divide evenly by 2^5; any hand with four kings would divide evenly by 59^4, etc.</p> <p>The problem is that a seven-card hand like AcAdAhAsKdKhKs has a hash value of approximately 62.7 quadrillion, which would take considerably more than 32 bits to represent internally. Is there a way to store such large numbers in Python that will allow me to perform arithmetic operations on it?</p>
48
2009-02-11T20:13:45Z
538,797
<p>You could do this for the fun of it, but other than that it's not a good idea. It would not speed up anything I can think of.</p> <ul> <li><p>Getting the cards in a hand will be an integer factoring operation which is much more expensive than just accessing an array.</p></li> <li><p>Adding cards would be multiplication, and removing cards division, both of large multi-word numbers, which are more expensive operations than adding or removing elements from lists.</p></li> <li><p>The actual numeric value of a hand will tell you nothing. You will need to factor the primes and follow the Poker rules to compare two hands. h1 &lt; h2 for such hands means nothing.</p></li> </ul>
19
2009-02-11T21:07:15Z
[ "python", "optimization", "largenumber" ]
Handling very large numbers in Python
538,551
<p>I've been considering fast poker hand evaluation in Python. It occurred to me that one way to speed the process up would be to represent all the card faces and suits as prime numbers and multiply them together to represent the hands. To whit:</p> <pre><code>class PokerCard: faces = '23456789TJQKA' suits = 'cdhs' facePrimes = [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 53, 59, 61] suitPrimes = [2, 3, 5, 7] </code></pre> <p>AND</p> <pre><code> def HashVal(self): return PokerCard.facePrimes[self.cardFace] * PokerCard.suitPrimes[self.cardSuit] </code></pre> <p>This would give each hand a numeric value that, through modulo could tell me how many kings are in the hand or how many hearts. For example, any hand with five or more clubs in it would divide evenly by 2^5; any hand with four kings would divide evenly by 59^4, etc.</p> <p>The problem is that a seven-card hand like AcAdAhAsKdKhKs has a hash value of approximately 62.7 quadrillion, which would take considerably more than 32 bits to represent internally. Is there a way to store such large numbers in Python that will allow me to perform arithmetic operations on it?</p>
48
2009-02-11T20:13:45Z
20,980,470
<p>python supports <strong><em>arbitrarily</em></strong> large <strong><em>integers</em></strong> naturally:</p> <p>example:</p> <blockquote> <p><strong>>>></strong> 10**1000 100000000000000000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000000</p> </blockquote> <p>You could even get, for example of a huge integer value, fib(4000000).</p> <p>But still it does <strong>not</strong> (for now) supports an arbitrarily large <strong>float</strong> !!</p> <p>If you need one big, large, float then check up on the decimal Module. There are examples of use on these foruns: <a href="http://stackoverflow.com/questions/20201706/overflowerror-34-result-too-large">OverflowError: (34, &#39;Result too large&#39;)</a></p> <p>Another reference: <a href="http://docs.python.org/2/library/decimal.html">http://docs.python.org/2/library/decimal.html</a></p> <p>You can even using the gmpy module if you need a speed-up (which is likely to be of your interest): <a href="http://stackoverflow.com/questions/1386604/handling-big-numbers-in-code">Handling big numbers in code</a></p> <p>Another reference: <a href="https://code.google.com/p/gmpy/">https://code.google.com/p/gmpy/</a></p>
21
2014-01-07T19:50:08Z
[ "python", "optimization", "largenumber" ]
Python format timedelta to string
538,666
<p>I'm a Python newbie (2 weeks) and I'm having trouble formatting a <code>datetime.timedelta</code> object.</p> <p>Here's what I'm trying to do: I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to display that duration in the format of hours:minutes.</p> <p>I have tried a variety of methods for doing this and I'm having difficulty. My current approach is to add methods to the class for my objects that return hours and minutes. I can get the hours by dividing the timedelta.seconds by 3600 and rounding it. I'm having trouble with getting the remainder seconds and converting that to minutes.</p> <p>By the way, I'm using <code>Google AppEngine</code> with <code>Django Templates</code> for presentation.</p> <p>If anyone can help or knows of a better way to resolve this, I would be very happy.</p> <p>Thanks,</p>
125
2009-02-11T20:40:43Z
538,687
<pre><code>&gt;&gt;&gt; str(datetime.timedelta(hours=10.56)) 10:33:36 &gt;&gt;&gt; td = datetime.timedelta(hours=10.505) # any timedelta object &gt;&gt;&gt; ':'.join(str(td).split(':')[:2]) 10:30 </code></pre> <p>Passing the <code>timedelta</code> object to the <code>str()</code> function calls the same formatting code used if we simply type <code>print td</code>. Since you don't want the seconds, we can split the string by colons (3 parts) and put it back together with only the first 2 parts.</p>
29
2009-02-11T20:44:39Z
[ "python", "string", "datetime", "format", "timedelta" ]
Python format timedelta to string
538,666
<p>I'm a Python newbie (2 weeks) and I'm having trouble formatting a <code>datetime.timedelta</code> object.</p> <p>Here's what I'm trying to do: I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to display that duration in the format of hours:minutes.</p> <p>I have tried a variety of methods for doing this and I'm having difficulty. My current approach is to add methods to the class for my objects that return hours and minutes. I can get the hours by dividing the timedelta.seconds by 3600 and rounding it. I'm having trouble with getting the remainder seconds and converting that to minutes.</p> <p>By the way, I'm using <code>Google AppEngine</code> with <code>Django Templates</code> for presentation.</p> <p>If anyone can help or knows of a better way to resolve this, I would be very happy.</p> <p>Thanks,</p>
125
2009-02-11T20:40:43Z
538,720
<p>Following Joe's example value above, I'd use the modulus arithmetic operator, thusly:</p> <pre><code>td = datetime.timedelta(hours=10.56) td_str = "%d:%d" % (td.seconds/3600, td.seconds%3600/60) </code></pre> <p>Note that integer division in Python rounds down by default; if you want to be more explicit, use math.floor() or math.ceil() as appropriate.</p>
6
2009-02-11T20:52:18Z
[ "python", "string", "datetime", "format", "timedelta" ]
Python format timedelta to string
538,666
<p>I'm a Python newbie (2 weeks) and I'm having trouble formatting a <code>datetime.timedelta</code> object.</p> <p>Here's what I'm trying to do: I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to display that duration in the format of hours:minutes.</p> <p>I have tried a variety of methods for doing this and I'm having difficulty. My current approach is to add methods to the class for my objects that return hours and minutes. I can get the hours by dividing the timedelta.seconds by 3600 and rounding it. I'm having trouble with getting the remainder seconds and converting that to minutes.</p> <p>By the way, I'm using <code>Google AppEngine</code> with <code>Django Templates</code> for presentation.</p> <p>If anyone can help or knows of a better way to resolve this, I would be very happy.</p> <p>Thanks,</p>
125
2009-02-11T20:40:43Z
538,721
<p>You can just convert the timedelta to a string with str(). Here's an example:</p> <pre><code>import datetime start = datetime.datetime(2009,2,10,14,00) end = datetime.datetime(2009,2,10,16,00) delta = end-start print str(delta) # prints 2:00:00 </code></pre>
119
2009-02-11T20:52:24Z
[ "python", "string", "datetime", "format", "timedelta" ]
Python format timedelta to string
538,666
<p>I'm a Python newbie (2 weeks) and I'm having trouble formatting a <code>datetime.timedelta</code> object.</p> <p>Here's what I'm trying to do: I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to display that duration in the format of hours:minutes.</p> <p>I have tried a variety of methods for doing this and I'm having difficulty. My current approach is to add methods to the class for my objects that return hours and minutes. I can get the hours by dividing the timedelta.seconds by 3600 and rounding it. I'm having trouble with getting the remainder seconds and converting that to minutes.</p> <p>By the way, I'm using <code>Google AppEngine</code> with <code>Django Templates</code> for presentation.</p> <p>If anyone can help or knows of a better way to resolve this, I would be very happy.</p> <p>Thanks,</p>
125
2009-02-11T20:40:43Z
538,818
<p>Thanks everyone for your help. I took many of your ideas and put them together, let me know what you think.</p> <p>I added two methods to the class like this:</p> <pre><code>def hours(self): retval = "" if self.totalTime: hoursfloat = self.totalTime.seconds / 3600 retval = round(hoursfloat) return retval def minutes(self): retval = "" if self.totalTime: minutesfloat = self.totalTime.seconds / 60 hoursAsMinutes = self.hours() * 60 retval = round(minutesfloat - hoursAsMinutes) return retval </code></pre> <p>In my django I used this (sum is the object and it is in a dictionary):</p> <pre><code>&lt;td&gt;{{ sum.0 }}&lt;/td&gt; &lt;td&gt;{{ sum.1.hours|stringformat:"d" }}:{{ sum.1.minutes|stringformat:"#02.0d" }}&lt;/td&gt; </code></pre>
-7
2009-02-11T21:11:26Z
[ "python", "string", "datetime", "format", "timedelta" ]
Python format timedelta to string
538,666
<p>I'm a Python newbie (2 weeks) and I'm having trouble formatting a <code>datetime.timedelta</code> object.</p> <p>Here's what I'm trying to do: I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to display that duration in the format of hours:minutes.</p> <p>I have tried a variety of methods for doing this and I'm having difficulty. My current approach is to add methods to the class for my objects that return hours and minutes. I can get the hours by dividing the timedelta.seconds by 3600 and rounding it. I'm having trouble with getting the remainder seconds and converting that to minutes.</p> <p>By the way, I'm using <code>Google AppEngine</code> with <code>Django Templates</code> for presentation.</p> <p>If anyone can help or knows of a better way to resolve this, I would be very happy.</p> <p>Thanks,</p>
125
2009-02-11T20:40:43Z
539,360
<p>As you know, you can get the seconds from a timedelta object by accessing the <code>.seconds</code> attribute.</p> <p>You can convert that to hours and remainder by using a combination of modulo and subtraction:</p> <pre class="lang-py prettyprint-override"><code># arbitrary number of seconds s = 13420 # hours hours = s // 3600 # remaining seconds s = s - (hours * 3600) # minutes minutes = s // 60 # remaining seconds seconds = s - (minutes * 60) # total time print '%s:%s:%s' % (hours, minutes, seconds) # result: 3:43:40 </code></pre> <p>However, python provides the builtin function divmod() which allows us to simplify this code:</p> <pre><code>s = 13420 hours, remainder = divmod(s, 3600) minutes, seconds = divmod(remainder, 60) print '%s:%s:%s' % (hours, minutes, seconds) # result: 3:43:40 </code></pre> <p>Hope this helps!</p>
116
2009-02-11T23:34:33Z
[ "python", "string", "datetime", "format", "timedelta" ]
Python format timedelta to string
538,666
<p>I'm a Python newbie (2 weeks) and I'm having trouble formatting a <code>datetime.timedelta</code> object.</p> <p>Here's what I'm trying to do: I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to display that duration in the format of hours:minutes.</p> <p>I have tried a variety of methods for doing this and I'm having difficulty. My current approach is to add methods to the class for my objects that return hours and minutes. I can get the hours by dividing the timedelta.seconds by 3600 and rounding it. I'm having trouble with getting the remainder seconds and converting that to minutes.</p> <p>By the way, I'm using <code>Google AppEngine</code> with <code>Django Templates</code> for presentation.</p> <p>If anyone can help or knows of a better way to resolve this, I would be very happy.</p> <p>Thanks,</p>
125
2009-02-11T20:40:43Z
1,644,095
<p>My <code>datetime.timedelta</code> objects went greater than a day. So here is a further problem. All the discussion above assumes less than a day. A <code>timedelta</code> is actually a tuple of days, seconds and microseconds. The above discussion should use <code>td.seconds</code> as joe did, but if you have days it is NOT included in the seconds value. </p> <p>I am getting a span of time between 2 datetimes and printing days and hours.</p> <pre><code>span = currentdt - previousdt print '%d,%d\n' % (span.days,span.seconds/3600) </code></pre>
9
2009-10-29T14:23:22Z
[ "python", "string", "datetime", "format", "timedelta" ]
Python format timedelta to string
538,666
<p>I'm a Python newbie (2 weeks) and I'm having trouble formatting a <code>datetime.timedelta</code> object.</p> <p>Here's what I'm trying to do: I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to display that duration in the format of hours:minutes.</p> <p>I have tried a variety of methods for doing this and I'm having difficulty. My current approach is to add methods to the class for my objects that return hours and minutes. I can get the hours by dividing the timedelta.seconds by 3600 and rounding it. I'm having trouble with getting the remainder seconds and converting that to minutes.</p> <p>By the way, I'm using <code>Google AppEngine</code> with <code>Django Templates</code> for presentation.</p> <p>If anyone can help or knows of a better way to resolve this, I would be very happy.</p> <p>Thanks,</p>
125
2009-02-11T20:40:43Z
13,756,038
<pre><code>def td_format(td_object): seconds = int(td_object.total_seconds()) periods = [ ('year', 60*60*24*365), ('month', 60*60*24*30), ('day', 60*60*24), ('hour', 60*60), ('minute', 60), ('second', 1) ] strings=[] for period_name,period_seconds in periods: if seconds &gt; period_seconds: period_value , seconds = divmod(seconds,period_seconds) if period_value == 1: strings.append("%s %s" % (period_value, period_name)) else: strings.append("%s %ss" % (period_value, period_name)) return ", ".join(strings) </code></pre>
20
2012-12-07T02:24:53Z
[ "python", "string", "datetime", "format", "timedelta" ]
Python format timedelta to string
538,666
<p>I'm a Python newbie (2 weeks) and I'm having trouble formatting a <code>datetime.timedelta</code> object.</p> <p>Here's what I'm trying to do: I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to display that duration in the format of hours:minutes.</p> <p>I have tried a variety of methods for doing this and I'm having difficulty. My current approach is to add methods to the class for my objects that return hours and minutes. I can get the hours by dividing the timedelta.seconds by 3600 and rounding it. I'm having trouble with getting the remainder seconds and converting that to minutes.</p> <p>By the way, I'm using <code>Google AppEngine</code> with <code>Django Templates</code> for presentation.</p> <p>If anyone can help or knows of a better way to resolve this, I would be very happy.</p> <p>Thanks,</p>
125
2009-02-11T20:40:43Z
14,247,500
<p>Questioner wants a nicer format than the typical:</p> <pre><code> &gt;&gt;&gt; import datetime &gt;&gt;&gt; datetime.timedelta(seconds=41000) datetime.timedelta(0, 41000) &gt;&gt;&gt; str(datetime.timedelta(seconds=41000)) '11:23:20' &gt;&gt;&gt; str(datetime.timedelta(seconds=4102.33)) '1:08:22.330000' &gt;&gt;&gt; str(datetime.timedelta(seconds=413302.33)) '4 days, 18:48:22.330000' </code></pre> <p>So, really there's two formats, one where days are 0 and it's left out, and another where there's text "n days, h:m:s". But, the seconds may have fractions, and there's no leading zeroes in the printouts, so columns are messy.</p> <p>Here's my routine, if you like it:</p> <pre><code>def printNiceTimeDelta(stime, etime): delay = datetime.timedelta(seconds=(etime - stime)) if (delay.days &gt; 0): out = str(delay).replace(" days, ", ":") else: out = "0:" + str(delay) outAr = out.split(':') outAr = ["%02d" % (int(float(x))) for x in outAr] out = ":".join(outAr) return out </code></pre> <p>this returns output as dd:hh:mm:ss format:</p> <pre><code>00:00:00:15 00:00:00:19 02:01:31:40 02:01:32:22 </code></pre> <p>I did think about adding years to this, but this is left as an exercise for the reader, since the output is safe at over 1 year:</p> <pre><code>&gt;&gt;&gt; str(datetime.timedelta(seconds=99999999)) '1157 days, 9:46:39' </code></pre>
9
2013-01-09T22:16:26Z
[ "python", "string", "datetime", "format", "timedelta" ]
Python format timedelta to string
538,666
<p>I'm a Python newbie (2 weeks) and I'm having trouble formatting a <code>datetime.timedelta</code> object.</p> <p>Here's what I'm trying to do: I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to display that duration in the format of hours:minutes.</p> <p>I have tried a variety of methods for doing this and I'm having difficulty. My current approach is to add methods to the class for my objects that return hours and minutes. I can get the hours by dividing the timedelta.seconds by 3600 and rounding it. I'm having trouble with getting the remainder seconds and converting that to minutes.</p> <p>By the way, I'm using <code>Google AppEngine</code> with <code>Django Templates</code> for presentation.</p> <p>If anyone can help or knows of a better way to resolve this, I would be very happy.</p> <p>Thanks,</p>
125
2009-02-11T20:40:43Z
17,195,550
<p>He already has a timedelta object so why not use its built-in method total_seconds() to convert it to seconds, then use divmod() to get hours and minutes? </p> <pre><code> hours, remainder = divmod(myTimeDelta.total_seconds(), 3600) minutes, seconds = divmod(remainder, 60) # Formatted only for hours and minutes as requested print '%s:%s' % (hours, minutes) </code></pre> <p>This works regardless if the time delta has even days or years.</p>
9
2013-06-19T15:41:24Z
[ "python", "string", "datetime", "format", "timedelta" ]
Python format timedelta to string
538,666
<p>I'm a Python newbie (2 weeks) and I'm having trouble formatting a <code>datetime.timedelta</code> object.</p> <p>Here's what I'm trying to do: I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to display that duration in the format of hours:minutes.</p> <p>I have tried a variety of methods for doing this and I'm having difficulty. My current approach is to add methods to the class for my objects that return hours and minutes. I can get the hours by dividing the timedelta.seconds by 3600 and rounding it. I'm having trouble with getting the remainder seconds and converting that to minutes.</p> <p>By the way, I'm using <code>Google AppEngine</code> with <code>Django Templates</code> for presentation.</p> <p>If anyone can help or knows of a better way to resolve this, I would be very happy.</p> <p>Thanks,</p>
125
2009-02-11T20:40:43Z
17,772,597
<pre><code>t1 = datetime.datetime.strptime(StartTime, "%H:%M:%S %d-%m-%y") t2 = datetime.datetime.strptime(EndTime, "%H:%M:%S %d-%m-%y") return str(t2-t1) </code></pre> <p>So for:</p> <pre><code>StartTime = '15:28:53 21-07-13' EndTime = '15:32:40 21-07-13' </code></pre> <p>returns:</p> <pre><code>'0:03:47' </code></pre>
0
2013-07-21T13:01:00Z
[ "python", "string", "datetime", "format", "timedelta" ]
Python format timedelta to string
538,666
<p>I'm a Python newbie (2 weeks) and I'm having trouble formatting a <code>datetime.timedelta</code> object.</p> <p>Here's what I'm trying to do: I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to display that duration in the format of hours:minutes.</p> <p>I have tried a variety of methods for doing this and I'm having difficulty. My current approach is to add methods to the class for my objects that return hours and minutes. I can get the hours by dividing the timedelta.seconds by 3600 and rounding it. I'm having trouble with getting the remainder seconds and converting that to minutes.</p> <p>By the way, I'm using <code>Google AppEngine</code> with <code>Django Templates</code> for presentation.</p> <p>If anyone can help or knows of a better way to resolve this, I would be very happy.</p> <p>Thanks,</p>
125
2009-02-11T20:40:43Z
19,074,707
<pre><code>def seconds_to_time_left_string(total_seconds): s = int(total_seconds) years = s // 31104000 if years &gt; 1: return '%d years' % years s = s - (years * 31104000) months = s // 2592000 if years == 1: r = 'one year' if months &gt; 0: r += ' and %d months' % months return r if months &gt; 1: return '%d months' % months s = s - (months * 2592000) days = s // 86400 if months == 1: r = 'one month' if days &gt; 0: r += ' and %d days' % days return r if days &gt; 1: return '%d days' % days s = s - (days * 86400) hours = s // 3600 if days == 1: r = 'one day' if hours &gt; 0: r += ' and %d hours' % hours return r s = s - (hours * 3600) minutes = s // 60 seconds = s - (minutes * 60) if hours &gt;= 6: return '%d hours' % hours if hours &gt;= 1: r = '%d hours' % hours if hours == 1: r = 'one hour' if minutes &gt; 0: r += ' and %d minutes' % minutes return r if minutes == 1: r = 'one minute' if seconds &gt; 0: r += ' and %d seconds' % seconds return r if minutes == 0: return '%d seconds' % seconds if seconds == 0: return '%d minutes' % minutes return '%d minutes and %d seconds' % (minutes, seconds) for i in range(10): print pow(8, i), seconds_to_time_left_string(pow(8, i)) Output: 1 1 seconds 8 8 seconds 64 one minute and 4 seconds 512 8 minutes and 32 seconds 4096 one hour and 8 minutes 32768 9 hours 262144 3 days 2097152 24 days 16777216 6 months 134217728 4 years </code></pre>
3
2013-09-29T05:21:26Z
[ "python", "string", "datetime", "format", "timedelta" ]
Python format timedelta to string
538,666
<p>I'm a Python newbie (2 weeks) and I'm having trouble formatting a <code>datetime.timedelta</code> object.</p> <p>Here's what I'm trying to do: I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to display that duration in the format of hours:minutes.</p> <p>I have tried a variety of methods for doing this and I'm having difficulty. My current approach is to add methods to the class for my objects that return hours and minutes. I can get the hours by dividing the timedelta.seconds by 3600 and rounding it. I'm having trouble with getting the remainder seconds and converting that to minutes.</p> <p>By the way, I'm using <code>Google AppEngine</code> with <code>Django Templates</code> for presentation.</p> <p>If anyone can help or knows of a better way to resolve this, I would be very happy.</p> <p>Thanks,</p>
125
2009-02-11T20:40:43Z
23,582,157
<p>I had a similar problem with the output of overtime calculation at work. The value should always show up in HH:MM, even when it is greater than one day and the value can get negative. I combined some of the shown solutions and maybe someone else find this solution useful. I realized that if the timedelta value is negative most of the shown solutions with the divmod method doesn't work out of the box:</p> <pre><code>def td2HHMMstr(td): '''Convert timedelta objects to a HH:MM string with (+/-) sign''' if td &lt; datetime.timedelta(seconds=0): sign='-' td = -td else: sign = '' tdhours, rem = divmod(td.total_seconds(), 3600) tdminutes, rem = divmod(rem, 60) tdstr = '{}{:}:{:02d}'.format(sign, int(tdhours), int(tdminutes)) return tdstr </code></pre> <p>timedelta to HH:MM string:</p> <pre><code>td2HHMMstr(datetime.timedelta(hours=1, minutes=45)) '1:54' td2HHMMstr(datetime.timedelta(days=2, hours=3, minutes=2)) '51:02' td2HHMMstr(datetime.timedelta(hours=-3, minutes=-2)) '-3:02' td2HHMMstr(datetime.timedelta(days=-35, hours=-3, minutes=-2)) '-843:02' </code></pre>
3
2014-05-10T14:21:19Z
[ "python", "string", "datetime", "format", "timedelta" ]
Python format timedelta to string
538,666
<p>I'm a Python newbie (2 weeks) and I'm having trouble formatting a <code>datetime.timedelta</code> object.</p> <p>Here's what I'm trying to do: I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to display that duration in the format of hours:minutes.</p> <p>I have tried a variety of methods for doing this and I'm having difficulty. My current approach is to add methods to the class for my objects that return hours and minutes. I can get the hours by dividing the timedelta.seconds by 3600 and rounding it. I'm having trouble with getting the remainder seconds and converting that to minutes.</p> <p>By the way, I'm using <code>Google AppEngine</code> with <code>Django Templates</code> for presentation.</p> <p>If anyone can help or knows of a better way to resolve this, I would be very happy.</p> <p>Thanks,</p>
125
2009-02-11T20:40:43Z
28,242,294
<p>I know that this is an old answered question, but I use <code>datetime.utcfromtimestamp()</code> for this. It takes the number of seconds and returns a <code>datetime</code> that can be formatted like any other <code>datetime</code>.</p> <pre><code>duration = datetime.utcfromtimestamp(end - begin) print duration.strftime('%H:%M') </code></pre> <p>As long as you stay in the legal ranges for the time parts this should work, i.e. it doesn't return 1234:35 as hours are &lt;= 23.</p>
3
2015-01-30T18:24:06Z
[ "python", "string", "datetime", "format", "timedelta" ]
Python format timedelta to string
538,666
<p>I'm a Python newbie (2 weeks) and I'm having trouble formatting a <code>datetime.timedelta</code> object.</p> <p>Here's what I'm trying to do: I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to display that duration in the format of hours:minutes.</p> <p>I have tried a variety of methods for doing this and I'm having difficulty. My current approach is to add methods to the class for my objects that return hours and minutes. I can get the hours by dividing the timedelta.seconds by 3600 and rounding it. I'm having trouble with getting the remainder seconds and converting that to minutes.</p> <p>By the way, I'm using <code>Google AppEngine</code> with <code>Django Templates</code> for presentation.</p> <p>If anyone can help or knows of a better way to resolve this, I would be very happy.</p> <p>Thanks,</p>
125
2009-02-11T20:40:43Z
28,731,232
<p>I would seriously consider the Occam's Razor approach here:</p> <pre><code>td = str(timedelta).split('.')[0] </code></pre> <p>This returns a string without the microseconds</p> <p>If you want to regenerate the datetime.timedelta object, just do this:</p> <pre><code>h,m,s = re.split(':', td) new_delta = datetime.timedelta(hours=int(h),minutes=int(m),seconds=int(s)) </code></pre> <p>2 years in, I love this language!</p>
3
2015-02-25T22:53:28Z
[ "python", "string", "datetime", "format", "timedelta" ]
Python format timedelta to string
538,666
<p>I'm a Python newbie (2 weeks) and I'm having trouble formatting a <code>datetime.timedelta</code> object.</p> <p>Here's what I'm trying to do: I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to display that duration in the format of hours:minutes.</p> <p>I have tried a variety of methods for doing this and I'm having difficulty. My current approach is to add methods to the class for my objects that return hours and minutes. I can get the hours by dividing the timedelta.seconds by 3600 and rounding it. I'm having trouble with getting the remainder seconds and converting that to minutes.</p> <p>By the way, I'm using <code>Google AppEngine</code> with <code>Django Templates</code> for presentation.</p> <p>If anyone can help or knows of a better way to resolve this, I would be very happy.</p> <p>Thanks,</p>
125
2009-02-11T20:40:43Z
35,766,976
<p>Please check this function - it converts timedelta object into string 'HH:MM:SS'</p> <pre><code>def format_timedelta(td): hours, remainder = divmod(td.total_seconds(), 3600) minutes, seconds = divmod(remainder, 60) hours, minutes, seconds = int(hours), int(minutes), int(seconds) if hours &lt; 10: hours = '0%s' % int(hours) if minutes &lt; 10: minutes = '0%s' % minutes if seconds &lt; 10: seconds = '0%s' % seconds return '%s:%s:%s' % (hours, minutes, seconds) </code></pre>
0
2016-03-03T08:34:33Z
[ "python", "string", "datetime", "format", "timedelta" ]
Python format timedelta to string
538,666
<p>I'm a Python newbie (2 weeks) and I'm having trouble formatting a <code>datetime.timedelta</code> object.</p> <p>Here's what I'm trying to do: I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to display that duration in the format of hours:minutes.</p> <p>I have tried a variety of methods for doing this and I'm having difficulty. My current approach is to add methods to the class for my objects that return hours and minutes. I can get the hours by dividing the timedelta.seconds by 3600 and rounding it. I'm having trouble with getting the remainder seconds and converting that to minutes.</p> <p>By the way, I'm using <code>Google AppEngine</code> with <code>Django Templates</code> for presentation.</p> <p>If anyone can help or knows of a better way to resolve this, I would be very happy.</p> <p>Thanks,</p>
125
2009-02-11T20:40:43Z
39,704,521
<pre><code>from django.utils.translation import ngettext def localize_timedelta(delta): ret = [] num_years = int(delta.days / 365) if num_years &gt; 0: delta -= timedelta(days=num_years * 365) ret.append(ngettext('%d year', '%d years', num_years) % num_years) if delta.days &gt; 0: ret.append(ngettext('%d day', '%d days', delta.days) % delta.days) num_hours = int(delta.seconds / 3600) if num_hours &gt; 0: delta -= timedelta(hours=num_hours) ret.append(ngettext('%d hour', '%d hours', num_hours) % num_hours) num_minutes = int(delta.seconds / 60) if num_minutes &gt; 0: ret.append(ngettext('%d minute', '%d minutes', num_minutes) % num_minutes) return ' '.join(ret) </code></pre> <p>This will produce:</p> <pre><code>&gt;&gt;&gt; from datetime import timedelta &gt;&gt;&gt; localize_timedelta(timedelta(days=3660, minutes=500)) '10 years 10 days 8 hours 20 minutes' </code></pre>
0
2016-09-26T13:41:45Z
[ "python", "string", "datetime", "format", "timedelta" ]
Parallel/Async Download of S3 data into EC2 in Python?
538,875
<p>I have large data files stored in S3 that I need to analyze. Each batch consists of ~50 files, each of which can be analyzed independently. </p> <p>I'd like to setup parallel downloads of the S3 data into the EC2 instance, and setup triggers that start the analysis process on each file that downloads.</p> <p>Are there any libraries that handle an async download, trigger on complete model? </p> <p>If not, I'm thinking of setting up multiple download processes with pyprocessing, each of which will download and analyze a single piece of the file. Does that sound reasonable or are there better alternatives?</p>
1
2009-02-11T21:25:10Z
538,895
<p>It sounds like you're looking for <a href="http://twistedmatrix.com/trac/" rel="nofollow">twisted</a>:</p> <p>"Twisted is an event-driven networking engine written in Python and licensed under the MIT license."</p> <p><a href="http://twistedmatrix.com/trac/" rel="nofollow">http://twistedmatrix.com/trac/</a></p> <p>I've used the twisted python for quite a few asynchronous projects involving both communicating over the Internet and with subprocesses.</p>
0
2009-02-11T21:28:41Z
[ "python", "amazon-s3", "amazon-ec2" ]
Parallel/Async Download of S3 data into EC2 in Python?
538,875
<p>I have large data files stored in S3 that I need to analyze. Each batch consists of ~50 files, each of which can be analyzed independently. </p> <p>I'd like to setup parallel downloads of the S3 data into the EC2 instance, and setup triggers that start the analysis process on each file that downloads.</p> <p>Are there any libraries that handle an async download, trigger on complete model? </p> <p>If not, I'm thinking of setting up multiple download processes with pyprocessing, each of which will download and analyze a single piece of the file. Does that sound reasonable or are there better alternatives?</p>
1
2009-02-11T21:25:10Z
538,902
<p>I don't know of anything that already exists that does exactly what you're looking for, but even if not it should be reasonably easy to put together with Python. For a threaded approach, you might take a look at this <a href="http://code.activestate.com/recipes/284631/" rel="nofollow"><strong>Python recipe</strong></a> that does multi-threaded HTTP downloads for testing download mirrors.</p> <p><strong>EDIT</strong>: Few packages that I found that might do the majority of the work for you and be what you're looking for</p> <ul> <li><a href="http://pypi.python.org/pypi/spider.py/0.5" rel="nofollow"><strong>spider</strong></a></li> <li><a href="http://pypi.python.org/pypi/HarvestMan/1.4.6%20final/" rel="nofollow"><strong>HarvestMan</strong></a></li> </ul>
0
2009-02-11T21:30:34Z
[ "python", "amazon-s3", "amazon-ec2" ]
Parallel/Async Download of S3 data into EC2 in Python?
538,875
<p>I have large data files stored in S3 that I need to analyze. Each batch consists of ~50 files, each of which can be analyzed independently. </p> <p>I'd like to setup parallel downloads of the S3 data into the EC2 instance, and setup triggers that start the analysis process on each file that downloads.</p> <p>Are there any libraries that handle an async download, trigger on complete model? </p> <p>If not, I'm thinking of setting up multiple download processes with pyprocessing, each of which will download and analyze a single piece of the file. Does that sound reasonable or are there better alternatives?</p>
1
2009-02-11T21:25:10Z
644,538
<p>Answering my own question, I ended up writing a simple modification to the Amazon S3 python library that lets you download the file in chunks or read it line by line. <a href="http://parand.com/say/index.php/2009/03/13/python-s3-library-for-chunked-streaming-download/" rel="nofollow">Available here</a>.</p>
2
2009-03-13T20:37:58Z
[ "python", "amazon-s3", "amazon-ec2" ]
Return a tuple of arguments to be fed to string.format()
539,066
<p>Currently, I'm trying to get a method in Python to return a list of zero, one, or two strings to plug into a string formatter, and then pass them to the string method. My code looks something like this:</p> <pre><code>class PairEvaluator(HandEvaluator): def returnArbitrary(self): return ('ace', 'king') pe = PairEvaluator() cards = pe.returnArbitrary() print('Two pair, {0}s and {1}s'.format(cards)) </code></pre> <p>When I try to run this code, the compiler gives an IndexError: tuple index out of range.<br> How should I structure my return value to pass it as an argument to <code>.format()</code>?</p>
21
2009-02-11T22:10:10Z
539,102
<p>This attempts to use "cards" as single format input to print, not the contents of cards.</p> <p>Try something like:</p> <pre><code>print('Two pair, %ss and %ss' % cards) </code></pre>
1
2009-02-11T22:20:26Z
[ "python", "string-formatting", "tuples" ]
Return a tuple of arguments to be fed to string.format()
539,066
<p>Currently, I'm trying to get a method in Python to return a list of zero, one, or two strings to plug into a string formatter, and then pass them to the string method. My code looks something like this:</p> <pre><code>class PairEvaluator(HandEvaluator): def returnArbitrary(self): return ('ace', 'king') pe = PairEvaluator() cards = pe.returnArbitrary() print('Two pair, {0}s and {1}s'.format(cards)) </code></pre> <p>When I try to run this code, the compiler gives an IndexError: tuple index out of range.<br> How should I structure my return value to pass it as an argument to <code>.format()</code>?</p>
21
2009-02-11T22:10:10Z
539,106
<pre><code>print('Two pair, {0}s and {1}s'.format(*cards)) </code></pre> <p>You are missing only the star :D</p>
53
2009-02-11T22:20:47Z
[ "python", "string-formatting", "tuples" ]
Return a tuple of arguments to be fed to string.format()
539,066
<p>Currently, I'm trying to get a method in Python to return a list of zero, one, or two strings to plug into a string formatter, and then pass them to the string method. My code looks something like this:</p> <pre><code>class PairEvaluator(HandEvaluator): def returnArbitrary(self): return ('ace', 'king') pe = PairEvaluator() cards = pe.returnArbitrary() print('Two pair, {0}s and {1}s'.format(cards)) </code></pre> <p>When I try to run this code, the compiler gives an IndexError: tuple index out of range.<br> How should I structure my return value to pass it as an argument to <code>.format()</code>?</p>
21
2009-02-11T22:10:10Z
13,582,206
<p>Format is preferred over the % operator, as of its introduction in Python 2.6: <a href="http://docs.python.org/2/library/stdtypes.html#str.format" rel="nofollow">http://docs.python.org/2/library/stdtypes.html#str.format</a></p> <p>It's also a lot simpler just to unpack the tuple with * -- or a dict with ** -- rather than modify the format string.</p>
2
2012-11-27T10:29:51Z
[ "python", "string-formatting", "tuples" ]
Context processor using Werkzeug and Jinja2
539,116
<p>My application is running on App Engine and is implemented using <a href="http://werkzeug.pocoo.org/" rel="nofollow">Werkzeug</a> and <a href="http://jinja.pocoo.org/2/" rel="nofollow">Jinja2</a>. I'd like to have something functionally equivalent of Django's own context processor: a callable that takes a request and adds something to the template context. I already have a "context processors" that add something to the template context, but how do I get this <em>request</em> part working? I implemented context processors as a callables that just return a dictionary that later is used to update context.</p> <p>For example, I'd like to add something that is contained in <code>request.environ</code>.</p>
4
2009-02-11T22:22:39Z
539,427
<p>One way of achieving this is through late-bound <a href="http://jinja.pocoo.org/2/documentation/api#jinja2.Environment.globals" rel="nofollow">template globals</a> using the <a href="http://werkzeug.pocoo.org/documentation/local" rel="nofollow">thread-local proxy</a> in Werkzeug.</p> <p>A simple example that puts the request into the the template globals:</p> <pre><code>from werkzeug import Local, LocalManager local = Local() local_manager = LocalManager([local]) from jinja2 import Environment, FileSystemLoader # Create a global dict using the local's proxy to the request attribute global_dict = {'request': local('request')} jinja2_env = Environment(loader=FileSystemLoader('/')) jinja2_env.globals.update(global_dict) def application(environ, start_response): """A WSGI Application""" # later, bind the actual attribute to the local object local.request = request = Request(environ) # continue to view handling code # ... application = local_manager.make_middleware(application) </code></pre> <p>Now in any of your templates, the current request will appear bound to the variable "request". Of course that could be anything else in environ. The trick is to use the local proxy, then set the value before you render any template.</p> <p>I should probably also add that a framework like <a href="http://glashammer.org" rel="nofollow">Glashammer</a> (Werkzeug+Jinja2) streamlines this process for you by using events. Many functions can connect to the events during the process of the WSGI call (for example, when a request is created) and they can put stuff in the template namespace at that point.</p>
4
2009-02-11T23:55:13Z
[ "python", "django", "google-app-engine", "jinja2", "werkzeug" ]
Context processor using Werkzeug and Jinja2
539,116
<p>My application is running on App Engine and is implemented using <a href="http://werkzeug.pocoo.org/" rel="nofollow">Werkzeug</a> and <a href="http://jinja.pocoo.org/2/" rel="nofollow">Jinja2</a>. I'd like to have something functionally equivalent of Django's own context processor: a callable that takes a request and adds something to the template context. I already have a "context processors" that add something to the template context, but how do I get this <em>request</em> part working? I implemented context processors as a callables that just return a dictionary that later is used to update context.</p> <p>For example, I'd like to add something that is contained in <code>request.environ</code>.</p>
4
2009-02-11T22:22:39Z
562,828
<p>Well, using <a href="http://stackoverflow.com/questions/539116/context-processor-using-werkzeug-and-jinja2/539427#539427">what Ali wrote</a> I came to the solution that is specific to App Engine (because of its import cache). Unfortunately, Ali's code does not work with App Engine, because the code that sets Jinja globals are imported only once (making the globals effectively static).</p> <p>I had to write my own <code>render()</code> function and update the context there. For completeness sake, below is the code I came to:</p> <pre><code>def render(template, **kwargs): response_code = kwargs.pop('response_code', 200) mimetype = kwargs.pop('mimetype', 'text/html') for item in getattr(settings, 'CONTEXT_PROCESSORS', []): try: processor = import_string(item) kwargs.update(processor(local.request)) except (ImportError, AttributeError), e: logging.error(e) return Response(jinja_env.get_template(template).render(**kwargs), status=response_code, mimetype=mimetype) </code></pre> <p>This is App Engine specific. In other environments Ali's code works as expected (and that's why I am retagging my question).</p>
3
2009-02-18T21:02:52Z
[ "python", "django", "google-app-engine", "jinja2", "werkzeug" ]
Python - Test directory permissions
539,133
<p>In Python on Windows, is there a way to determine if a user has permission to access a directory? I've taken a look at <code>os.access</code> but it gives false results.</p> <pre><code>&gt;&gt;&gt; os.access('C:\haveaccess', os.R_OK) False &gt;&gt;&gt; os.access(r'C:\haveaccess', os.R_OK) True &gt;&gt;&gt; os.access('C:\donthaveaccess', os.R_OK) False &gt;&gt;&gt; os.access(r'C:\donthaveaccess', os.R_OK) True </code></pre> <p>Am I doing something wrong? Is there a better way to check if a user has permission to access a directory?</p>
5
2009-02-11T22:26:47Z
539,159
<p>It can be complicated to check for permissions in Windows (beware of issues in Vista with UAC, for example! -- see this <a href="http://stackoverflow.com/questions/450210/how-to-check-if-a-file-can-be-created-inside-given-directory-on-ms-xp-vista">related question</a>).</p> <p>Are you talking about simple read access, i.e. reading the directory's contents? The surest way of testing permissions would be to try to access the directory (e.g. do an <code>os.listdir</code>) and catch the exception.</p> <p>Also, in order for paths to be interpreted correctly you have to use raw strings or escape the backslashes ('\\'), -- or use forward slashes instead. </p> <p>(EDIT: you can avoid slashes altogether by using <code>os.path.join</code> -- the recommended way to build paths)</p>
6
2009-02-11T22:32:04Z
[ "python", "windows", "permissions", "directory" ]
Python - Test directory permissions
539,133
<p>In Python on Windows, is there a way to determine if a user has permission to access a directory? I've taken a look at <code>os.access</code> but it gives false results.</p> <pre><code>&gt;&gt;&gt; os.access('C:\haveaccess', os.R_OK) False &gt;&gt;&gt; os.access(r'C:\haveaccess', os.R_OK) True &gt;&gt;&gt; os.access('C:\donthaveaccess', os.R_OK) False &gt;&gt;&gt; os.access(r'C:\donthaveaccess', os.R_OK) True </code></pre> <p>Am I doing something wrong? Is there a better way to check if a user has permission to access a directory?</p>
5
2009-02-11T22:26:47Z
539,269
<p>While os.access tries its best to tell if a path is accessible or not, it doesn't claim to be perfect. From the Python docs:</p> <blockquote> <p>Note: I/O operations may fail even when access() indicates that they would succeed, particularly for operations on network filesystems which may have permissions semantics beyond the usual POSIX permission-bit model.</p> </blockquote> <p>The recommended way to find out if the user has access to do whatever is to try to do it, and catch any exceptions that occur.</p>
4
2009-02-11T23:04:01Z
[ "python", "windows", "permissions", "directory" ]
Python - Test directory permissions
539,133
<p>In Python on Windows, is there a way to determine if a user has permission to access a directory? I've taken a look at <code>os.access</code> but it gives false results.</p> <pre><code>&gt;&gt;&gt; os.access('C:\haveaccess', os.R_OK) False &gt;&gt;&gt; os.access(r'C:\haveaccess', os.R_OK) True &gt;&gt;&gt; os.access('C:\donthaveaccess', os.R_OK) False &gt;&gt;&gt; os.access(r'C:\donthaveaccess', os.R_OK) True </code></pre> <p>Am I doing something wrong? Is there a better way to check if a user has permission to access a directory?</p>
5
2009-02-11T22:26:47Z
539,516
<p>Did you get '\d' characters in the non-raw? Did you mean "c:\haveaccess"</p>
0
2009-02-12T00:30:44Z
[ "python", "windows", "permissions", "directory" ]
Python - Test directory permissions
539,133
<p>In Python on Windows, is there a way to determine if a user has permission to access a directory? I've taken a look at <code>os.access</code> but it gives false results.</p> <pre><code>&gt;&gt;&gt; os.access('C:\haveaccess', os.R_OK) False &gt;&gt;&gt; os.access(r'C:\haveaccess', os.R_OK) True &gt;&gt;&gt; os.access('C:\donthaveaccess', os.R_OK) False &gt;&gt;&gt; os.access(r'C:\donthaveaccess', os.R_OK) True </code></pre> <p>Am I doing something wrong? Is there a better way to check if a user has permission to access a directory?</p>
5
2009-02-11T22:26:47Z
2,445,812
<p>Actually 'C:\haveaccess' is different than r'C:\haveaccess'. From Python point of view 'C:\haveaccess' is not a valid path, so use 'C:\\haveaccess' instead. I think os.access works just fine.</p>
1
2010-03-15T08:23:53Z
[ "python", "windows", "permissions", "directory" ]
Background Image on Jython GUI
539,313
<p>I am trying to create a GUI in Jython. I want to import a background image that I can place buttons and textfields on. I've already created the frame with the buttons and labels in their appropriate places, I just need to know how to import a background image. The GUI is implemented in Jython.</p>
0
2009-02-11T23:17:52Z
539,346
<p>Take a look at the Java swing material, essentially you are just using the same api in python syntax. This might help: <a href="http://forums.sun.com/thread.jspa?threadID=599393" rel="nofollow">http://forums.sun.com/thread.jspa?threadID=599393</a></p>
1
2009-02-11T23:29:53Z
[ "python", "jython" ]
Connecting to MS SQL Server using python on linux with 'Windows Credentials'
539,430
<p>Is there any way to connect to an MS SQL Server database with python on linux using Windows Domain Credentials?</p> <p>I can connect perfectly fine from my windows machine using Windows Credentials, but attempting to do the same from a linux python with pyodbs + freetds + unixodbc </p> <pre><code>&gt;&gt;import pyodbc &gt;&gt;conn = pyodbc.connect("DRIVER={FreeTDS};SERVER=servername;UID=username;PWD=password;DATABASE=dbname") </code></pre> <p>results in this error:</p> <pre><code>class 'pyodbc.Error'&gt;: ('28000', '[28000] [unixODBC][FreeTDS][SQL Server]Login incorrect. (20014) (SQLDriverConnectW)') </code></pre> <p>I'm sure the password is written correctly, but I've tried many different combinations of username:</p> <pre><code>DOMAIN\username DOMAIN\\username </code></pre> <p>or even</p> <pre><code>UID=username;DOMAIN=domain </code></pre> <p>to no avail. Any ideas?</p>
4
2009-02-11T23:59:39Z
539,550
<p>I don't believe you'll be able to log in to a windows domain account in this way. You need to set up a user in sql directly for this manner of passing credentials.</p>
0
2009-02-12T00:46:42Z
[ "python", "sql-server", "pyodbc", "freetds", "unixodbc" ]
Connecting to MS SQL Server using python on linux with 'Windows Credentials'
539,430
<p>Is there any way to connect to an MS SQL Server database with python on linux using Windows Domain Credentials?</p> <p>I can connect perfectly fine from my windows machine using Windows Credentials, but attempting to do the same from a linux python with pyodbs + freetds + unixodbc </p> <pre><code>&gt;&gt;import pyodbc &gt;&gt;conn = pyodbc.connect("DRIVER={FreeTDS};SERVER=servername;UID=username;PWD=password;DATABASE=dbname") </code></pre> <p>results in this error:</p> <pre><code>class 'pyodbc.Error'&gt;: ('28000', '[28000] [unixODBC][FreeTDS][SQL Server]Login incorrect. (20014) (SQLDriverConnectW)') </code></pre> <p>I'm sure the password is written correctly, but I've tried many different combinations of username:</p> <pre><code>DOMAIN\username DOMAIN\\username </code></pre> <p>or even</p> <pre><code>UID=username;DOMAIN=domain </code></pre> <p>to no avail. Any ideas?</p>
4
2009-02-11T23:59:39Z
539,593
<p>I haven't done it in a while, but I remember the whole unixodbc + FreeTDS + pyodbc thing being a little tricky. However, it can be done, and once setup it's not that hard.</p> <p>This website provides very good instructions: <a href="http://web.archive.org/web/20150214152131/http://www.pauldeden.com/2008/12/how-to-setup-pyodbc-to-connect-to-mssql.html" rel="nofollow" title="On Archive.org: pauldeden.com/2008/12/how-to-setup-pyodbc-to-connect-to-mssql.html">http://www.pauldeden.com/2008/12/how-to-setup-pyodbc-to-connect-to-mssql.html (archived copy on Web Archive)</a></p> <p>Also, in my experience pyodbc had issues compiling/running on 64 bit Linux machines. Because of that we eventually used ceODBC. ceODBC isn't quite as stable as pyodbc (encountered more unexpected bugs than in pyodbc when running in python prorgram), but it is very easy to get up and running on Linux 64 bit.</p>
1
2009-02-12T01:05:14Z
[ "python", "sql-server", "pyodbc", "freetds", "unixodbc" ]
Connecting to MS SQL Server using python on linux with 'Windows Credentials'
539,430
<p>Is there any way to connect to an MS SQL Server database with python on linux using Windows Domain Credentials?</p> <p>I can connect perfectly fine from my windows machine using Windows Credentials, but attempting to do the same from a linux python with pyodbs + freetds + unixodbc </p> <pre><code>&gt;&gt;import pyodbc &gt;&gt;conn = pyodbc.connect("DRIVER={FreeTDS};SERVER=servername;UID=username;PWD=password;DATABASE=dbname") </code></pre> <p>results in this error:</p> <pre><code>class 'pyodbc.Error'&gt;: ('28000', '[28000] [unixODBC][FreeTDS][SQL Server]Login incorrect. (20014) (SQLDriverConnectW)') </code></pre> <p>I'm sure the password is written correctly, but I've tried many different combinations of username:</p> <pre><code>DOMAIN\username DOMAIN\\username </code></pre> <p>or even</p> <pre><code>UID=username;DOMAIN=domain </code></pre> <p>to no avail. Any ideas?</p>
4
2009-02-11T23:59:39Z
953,930
<p><strong>As pointed out in one of the comments, this answer is quite stale by now. I regularly and routinely use GSSAPI to authenticate from Linux to SQL Server 2008 R2 but mostly with the EasySoft ODBC manager and the (commercial) EasySoft ODBC SQL Server driver.</strong></p> <p>In early 2009, a colleague and I managed to connect to a SQL Server 2005 instance from Solaris 10 using GSSAPI (Kerberos credentials) using DBB::Perl over a FreeTDS build linked against a particular version of the MIT kerberos libraries. The trick was -- and this is a little bit difficult to believe but I have verified it by looking through the FreeTDS source code -- to specify a <em>zero-length</em> user_name. If the length of the user_name string is 0 then the FreeTDS code will attempt to use GSSAPI (if that support has been compiled in). I have not been able to do this via Python and pyodbc as I could not figure out a way of getting ODBC to pass down a zero-length user_name.</p> <p>Here in the perl code .. there are multiple opportunities for breakage wrt configuration files such as .freetds.conf etc. I seem to recall that the principal had to be in uppercase but my notes seem to be in disagreement with that.</p> <pre> $serverprincipal = 'MSSQLSvc/foo.bar.yourdomain.com:1433@YOURDOMAIN.COM'; $dbh = DBI->connect("dbi:Sybase:server=THESERVERNAME;kerberos=$serverprincipal", '', ''); </pre> <p>You will have to know how to use the setspn utility in order to get the SQL Server server to use the appropriate security principal name.</p> <p>I do not have any knowledge of the kerberos side of things because our environment was set up by an out and out Kerberos guru and has fancy stuff like mutual trust set up between the AD domain that the SQL Server is running in and the Kerberos domain that my client was running in.</p> <p>There is some code <a href="http://code.google.com/p/libsqljdbc-auth/" rel="nofollow">http://code.google.com/p/libsqljdbc-auth/</a> which does GSSAPI authentication from Linux to SQL Server but it is Java only. The author (who seems to know his stuff) also has contributed a similar patch to the jTDS project which works with more recent versions of Java that have GSSAPI built in.</p> <p>So the pieces are all there, it is just a big tangled mess trying to get them all to work together. I found the pyodbc to unixODBC to FreeTDS odbc to TDS integration pretty hard to trace/debug. The perl stuff because it was a pretty thin wrapper on top to CT-Lib was much easier to get going.</p>
4
2009-06-05T01:47:56Z
[ "python", "sql-server", "pyodbc", "freetds", "unixodbc" ]
Connecting to MS SQL Server using python on linux with 'Windows Credentials'
539,430
<p>Is there any way to connect to an MS SQL Server database with python on linux using Windows Domain Credentials?</p> <p>I can connect perfectly fine from my windows machine using Windows Credentials, but attempting to do the same from a linux python with pyodbs + freetds + unixodbc </p> <pre><code>&gt;&gt;import pyodbc &gt;&gt;conn = pyodbc.connect("DRIVER={FreeTDS};SERVER=servername;UID=username;PWD=password;DATABASE=dbname") </code></pre> <p>results in this error:</p> <pre><code>class 'pyodbc.Error'&gt;: ('28000', '[28000] [unixODBC][FreeTDS][SQL Server]Login incorrect. (20014) (SQLDriverConnectW)') </code></pre> <p>I'm sure the password is written correctly, but I've tried many different combinations of username:</p> <pre><code>DOMAIN\username DOMAIN\\username </code></pre> <p>or even</p> <pre><code>UID=username;DOMAIN=domain </code></pre> <p>to no avail. Any ideas?</p>
4
2009-02-11T23:59:39Z
5,832,263
<p>Probably a bit too late to help you out - but I encountered the same issue. At the time of writing, the latest version of pyodbc allows me to login with windows credentials. Just leave the UID field blank in your connection string like so:</p> <pre><code>cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=myserverinstance;DATABASE=mydatabase;UID=;PWD=mypassword') </code></pre> <p>Now this is using your existing windows credentials when you're logged on... not sure how to specify any arb windows domain credentials...</p>
1
2011-04-29T12:49:35Z
[ "python", "sql-server", "pyodbc", "freetds", "unixodbc" ]
Connecting to MS SQL Server using python on linux with 'Windows Credentials'
539,430
<p>Is there any way to connect to an MS SQL Server database with python on linux using Windows Domain Credentials?</p> <p>I can connect perfectly fine from my windows machine using Windows Credentials, but attempting to do the same from a linux python with pyodbs + freetds + unixodbc </p> <pre><code>&gt;&gt;import pyodbc &gt;&gt;conn = pyodbc.connect("DRIVER={FreeTDS};SERVER=servername;UID=username;PWD=password;DATABASE=dbname") </code></pre> <p>results in this error:</p> <pre><code>class 'pyodbc.Error'&gt;: ('28000', '[28000] [unixODBC][FreeTDS][SQL Server]Login incorrect. (20014) (SQLDriverConnectW)') </code></pre> <p>I'm sure the password is written correctly, but I've tried many different combinations of username:</p> <pre><code>DOMAIN\username DOMAIN\\username </code></pre> <p>or even</p> <pre><code>UID=username;DOMAIN=domain </code></pre> <p>to no avail. Any ideas?</p>
4
2009-02-11T23:59:39Z
15,551,792
<p>As of at least March 2013, this seems to work out of the box with FreeTDS. I specified the <a href="http://www.freetds.org/userguide/choosingtdsprotocol.htm" rel="nofollow">TDS protocol version</a> for good measure--not sure if that makes the difference:</p> <pre><code>connStr = "DRIVER={{FreeTDS}};SERVER={0};PORT=1433;TDS_Version=7.2;UID={1}\\{2};PWD={3}".format(hostname, active_directory_domain, username, password) </code></pre> <p>Integrated authentication also appears to be supported in Microsoft's official driver for linux: <a href="http://msdn.microsoft.com/en-us/library/hh568450.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/hh568450.aspx</a> . I'm not sure how many Linux distributions it actually works on or how much of the source is available. They explicitly mention RHEL 5 and 6 and some dependencies on the <a href="https://www.microsoft.com/en-us/download/details.aspx?id=28160" rel="nofollow">download page</a>.</p>
2
2013-03-21T15:34:02Z
[ "python", "sql-server", "pyodbc", "freetds", "unixodbc" ]
Namespace Specification In Absence of Ambuguity
539,578
<p>Why do some languages, like C++ and Python, require the namespace of an object be specified even when no ambiguity exists? I understand that there are backdoors to this, like <code>using namespace x</code> in C++, or <code>from x import *</code> in Python. However, I can't understand the rationale behind not wanting the language to just "do the right thing" when only one accessible namespace contains a given identifier and no ambiguity exists. To me it's just unnecessary verbosity and a violation of DRY, since you're being forced to specify something the compiler already knows.</p> <p>For example:</p> <pre><code>import foo # Contains someFunction(). someFunction() # imported from foo. No ambiguity. Works. </code></pre> <p>Vs.</p> <pre><code>import foo # Contains someFunction() import bar # Contains someFunction() also. # foo.someFunction or bar.someFunction? Should be an error only because # ambiguity exists. someFunction() </code></pre>
0
2009-02-12T00:56:34Z
539,585
<p>This all depends on your definition of "right thing". Is it the right thing for the compiler to guess your intention if there's only one match?</p> <p>There are arguments for both sides.</p>
0
2009-02-12T01:01:40Z
[ "c++", "python", "namespaces", "language-design" ]
Namespace Specification In Absence of Ambuguity
539,578
<p>Why do some languages, like C++ and Python, require the namespace of an object be specified even when no ambiguity exists? I understand that there are backdoors to this, like <code>using namespace x</code> in C++, or <code>from x import *</code> in Python. However, I can't understand the rationale behind not wanting the language to just "do the right thing" when only one accessible namespace contains a given identifier and no ambiguity exists. To me it's just unnecessary verbosity and a violation of DRY, since you're being forced to specify something the compiler already knows.</p> <p>For example:</p> <pre><code>import foo # Contains someFunction(). someFunction() # imported from foo. No ambiguity. Works. </code></pre> <p>Vs.</p> <pre><code>import foo # Contains someFunction() import bar # Contains someFunction() also. # foo.someFunction or bar.someFunction? Should be an error only because # ambiguity exists. someFunction() </code></pre>
0
2009-02-12T00:56:34Z
539,591
<p>One reason is to protect against accidentally introducing a conflict when you change the code (or for an external module/library, when someone else changes it) later on. For example, in Python you can write</p> <pre><code>from foo import * from bar import * </code></pre> <p>without conflicts if you know that modules <code>foo</code> and <code>bar</code> don't have any variables with the same names. But what if in later versions both <code>foo</code> and <code>bar</code> include variables named <code>rofl</code>? Then <code>bar.rofl</code> will cover up <code>foo.rofl</code> without you knowing about it.</p> <p>I also like to be able to look up to the top of the file and see exactly what names are being imported and where they're coming from (I'm talking about Python, of course, but the same reasoning could apply for C++).</p>
11
2009-02-12T01:04:47Z
[ "c++", "python", "namespaces", "language-design" ]
Namespace Specification In Absence of Ambuguity
539,578
<p>Why do some languages, like C++ and Python, require the namespace of an object be specified even when no ambiguity exists? I understand that there are backdoors to this, like <code>using namespace x</code> in C++, or <code>from x import *</code> in Python. However, I can't understand the rationale behind not wanting the language to just "do the right thing" when only one accessible namespace contains a given identifier and no ambiguity exists. To me it's just unnecessary verbosity and a violation of DRY, since you're being forced to specify something the compiler already knows.</p> <p>For example:</p> <pre><code>import foo # Contains someFunction(). someFunction() # imported from foo. No ambiguity. Works. </code></pre> <p>Vs.</p> <pre><code>import foo # Contains someFunction() import bar # Contains someFunction() also. # foo.someFunction or bar.someFunction? Should be an error only because # ambiguity exists. someFunction() </code></pre>
0
2009-02-12T00:56:34Z
539,595
<p>There have been languages where the compiler tried to "do the right thing" - Algol and PL/I come to mind. The reason they are not around anymore is that compilers are very bad at doing the right thing, but very good at doing the wrong one, given half a chance!</p>
4
2009-02-12T01:06:29Z
[ "c++", "python", "namespaces", "language-design" ]
Namespace Specification In Absence of Ambuguity
539,578
<p>Why do some languages, like C++ and Python, require the namespace of an object be specified even when no ambiguity exists? I understand that there are backdoors to this, like <code>using namespace x</code> in C++, or <code>from x import *</code> in Python. However, I can't understand the rationale behind not wanting the language to just "do the right thing" when only one accessible namespace contains a given identifier and no ambiguity exists. To me it's just unnecessary verbosity and a violation of DRY, since you're being forced to specify something the compiler already knows.</p> <p>For example:</p> <pre><code>import foo # Contains someFunction(). someFunction() # imported from foo. No ambiguity. Works. </code></pre> <p>Vs.</p> <pre><code>import foo # Contains someFunction() import bar # Contains someFunction() also. # foo.someFunction or bar.someFunction? Should be an error only because # ambiguity exists. someFunction() </code></pre>
0
2009-02-12T00:56:34Z
539,600
<p>The ideal this rule strives for is to make creating reusable components easy - and if you reuse your component, you just don't know which symbols will be defined in other namespaces the client uses. So the rule forces you to make your intention clear with respect to further definitions you don't know about yet.</p> <p>However, this ideal has not been reached for C++, mainly because of Koenig lookup.</p>
1
2009-02-12T01:10:07Z
[ "c++", "python", "namespaces", "language-design" ]
Namespace Specification In Absence of Ambuguity
539,578
<p>Why do some languages, like C++ and Python, require the namespace of an object be specified even when no ambiguity exists? I understand that there are backdoors to this, like <code>using namespace x</code> in C++, or <code>from x import *</code> in Python. However, I can't understand the rationale behind not wanting the language to just "do the right thing" when only one accessible namespace contains a given identifier and no ambiguity exists. To me it's just unnecessary verbosity and a violation of DRY, since you're being forced to specify something the compiler already knows.</p> <p>For example:</p> <pre><code>import foo # Contains someFunction(). someFunction() # imported from foo. No ambiguity. Works. </code></pre> <p>Vs.</p> <pre><code>import foo # Contains someFunction() import bar # Contains someFunction() also. # foo.someFunction or bar.someFunction? Should be an error only because # ambiguity exists. someFunction() </code></pre>
0
2009-02-12T00:56:34Z
539,604
<p>Python takes the view that 'explicit is better than implicit'. (type <code>import this</code> into a python interpreter)</p> <p>Also, say I'm reading someone's code. Perhaps it's your code; perhaps it's my code from six months ago. I see a reference to <code>bar()</code>. Where did the function come from? I could look through the file for a <code>def bar()</code>, but if I don't find it, what then? If python is automatically finding the first bar() available through an import, then I have to search through each file imported to find it. What a pain! And what if the function-finding recurses through the import heirarchy?</p> <p>I'd rather see <code>zomg.bar()</code>; that tells me where the function is from, and ensures I always get the same one if code changes (unless I change the <code>zomg</code> module).</p>
11
2009-02-12T01:10:48Z
[ "c++", "python", "namespaces", "language-design" ]
Namespace Specification In Absence of Ambuguity
539,578
<p>Why do some languages, like C++ and Python, require the namespace of an object be specified even when no ambiguity exists? I understand that there are backdoors to this, like <code>using namespace x</code> in C++, or <code>from x import *</code> in Python. However, I can't understand the rationale behind not wanting the language to just "do the right thing" when only one accessible namespace contains a given identifier and no ambiguity exists. To me it's just unnecessary verbosity and a violation of DRY, since you're being forced to specify something the compiler already knows.</p> <p>For example:</p> <pre><code>import foo # Contains someFunction(). someFunction() # imported from foo. No ambiguity. Works. </code></pre> <p>Vs.</p> <pre><code>import foo # Contains someFunction() import bar # Contains someFunction() also. # foo.someFunction or bar.someFunction? Should be an error only because # ambiguity exists. someFunction() </code></pre>
0
2009-02-12T00:56:34Z
539,621
<p>The problem is about abstraction and reuse : <strong>you don't really know if there will not be any future ambiguity</strong>. </p> <p>For example, It's very common to setup different libraries in a project just to discover that they all have their own string class implementation, called "string". You compiler will then complain that there is ambiguity if the libraries are not encapsulated in separate namespaces.</p> <p>It's then a delightful pleasure to dodge this kind of ambiguity by specifying wich implementation (like the standard std::string one) you wants to use at each specific instruction or context (read : scope).</p> <p><strong>And if you think that it's obvious in a particular context</strong> (read : in a particular <strong>function or .cpp</strong> in c++, <strong>.py file</strong> in python - NEVER in C++ header files) <strong>you just have to express yourself and say that "it should be obvious", adding the "using namespace" instruction (or import *)</strong>. Until the compiler complain because it is not.</p> <p>If you use using in specific scopes, you don't break the DRY rule at all.</p>
4
2009-02-12T01:20:32Z
[ "c++", "python", "namespaces", "language-design" ]
Namespace Specification In Absence of Ambuguity
539,578
<p>Why do some languages, like C++ and Python, require the namespace of an object be specified even when no ambiguity exists? I understand that there are backdoors to this, like <code>using namespace x</code> in C++, or <code>from x import *</code> in Python. However, I can't understand the rationale behind not wanting the language to just "do the right thing" when only one accessible namespace contains a given identifier and no ambiguity exists. To me it's just unnecessary verbosity and a violation of DRY, since you're being forced to specify something the compiler already knows.</p> <p>For example:</p> <pre><code>import foo # Contains someFunction(). someFunction() # imported from foo. No ambiguity. Works. </code></pre> <p>Vs.</p> <pre><code>import foo # Contains someFunction() import bar # Contains someFunction() also. # foo.someFunction or bar.someFunction? Should be an error only because # ambiguity exists. someFunction() </code></pre>
0
2009-02-12T00:56:34Z
539,643
<p>Is it really the right thing?</p> <p>What if I have two types ::bat and ::foo::bar</p> <p>I want to reference the bat type but accidentally hit the r key instead of t (they're right next to each others).</p> <p>Is it "the right thing" for the compiler to then go searching through every namespace to find ::foo::bar without giving me even a warning?</p> <p>Or what if I use "bar" as shorthand for the "::foo::bar" type all over my codebase. Then one day I include a library which defines a ::bar datatype. Suddenly an ambiguity exists where there was none before. And suddenly, "the right thing" has become wrong.</p> <p>The right thing for the compiler to do in this case would be to assume I meant the type I actually wrote. If I write bar with no namespace prefix, it should assume I'm referring to a type bar in the global namespace. But if it does that in our hypothetical scenario, it'll change what type my code references without even alerting me.</p> <p>Alternatively, it could give me an error, but come on, that'd just be ridiculous, because even with the current language rules, there should be no ambiguity here, since one of the types is hidden away in a namespace I didn't specify, so it shouldn't be considered.</p> <p>Another problem is that the compiler may not know what other types exist. In C++, the order of definitions matters.</p> <p>In C#, types can be defined in separate assemblies, and referenced in your code. How does the compiler know that another type with the same name doesn't exist in another assembly, just in a different namespace? How does it know that one won't be added to another assembly later on?</p> <p>The right thing is to do what gives the programmer the fewest nasty surprises. Second-guessing the programmer based on incomplete data is generally not the right thing to do.</p> <p>Most languages give you several tools to avoid having to specify the namespace.</p> <p>In c++, you have "using namespace foo", as well as typedefs. If you don't want to repeat the namespace prefix, then don't. Use the tools made available by the language so you don't have to.</p>
1
2009-02-12T01:31:41Z
[ "c++", "python", "namespaces", "language-design" ]