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
Change directory to the directory of a Python script
509,742
<p>How do i change directory to the directory with my python script in? So far I figured out I should use <code>os.chdir</code> and <code>sys.argv[0]</code>. I'm sure there is a better way then to write my own function to parse argv[0].</p>
4
2009-02-04T01:24:43Z
23,595,382
<p><code>os.chdir(os.path.dirname(os.path.abspath(__file__)))</code> should do it. </p> <p><code>os.chdir(os.path.dirname(__file__))</code> would not work if the script is run from the directory in which it is present.</p>
3
2014-05-11T16:56:16Z
[ "python", "scripting", "directory" ]
Change directory to the directory of a Python script
509,742
<p>How do i change directory to the directory with my python script in? So far I figured out I should use <code>os.chdir</code> and <code>sys.argv[0]</code>. I'm sure there is a better way then to write my own function to parse argv[0].</p>
4
2009-02-04T01:24:43Z
33,669,495
<p>on windows OS, if you call something like <strong><em>python somefile.py</em></strong> this <strong><em>os.chdir(os.path.dirname(__file__))</em></strong> will throw a WindowsError. But this should work for all cases: </p> <pre><code>import os absFilePath = os.path.abspath(__file__) os.chdir( os.path.dirname(absFilePath) ) </code></pre>
0
2015-11-12T10:37:18Z
[ "python", "scripting", "directory" ]
Best way to write a Python function that integrates a gaussian?
509,994
<p>In attempting to use scipy's quad method to integrate a gaussian (lets say there's a gaussian method named gauss), I was having problems passing needed parameters to gauss and leaving quad to do the integration over the correct variable. Does anyone have a good example of how to use quad w/ a multidimensional function?</p> <p>But this led me to a more grand question about the best way to integrate a gaussian in general. I didn't find a gaussian integrate in scipy (to my surprise). My plan was to write a simple gaussian function and pass it to quad (or maybe now a fixed width integrator). What would you do?</p> <p>Edit: Fixed-width meaning something like trapz that uses a fixed dx to calculate areas under a curve.</p> <p>What I've come to so far is a method make___gauss that returns a lambda function that can then go into quad. This way I can make a normal function with the average and variance I need before integrating.</p> <pre><code>def make_gauss(N, sigma, mu): return (lambda x: N/(sigma * (2*numpy.pi)**.5) * numpy.e ** (-(x-mu)**2/(2 * sigma**2))) quad(make_gauss(N=10, sigma=2, mu=0), -inf, inf) </code></pre> <p>When I tried passing a general gaussian function (that needs to be called with x, N, mu, and sigma) and filling in some of the values using quad like</p> <pre><code>quad(gen_gauss, -inf, inf, (10,2,0)) </code></pre> <p>the parameters 10, 2, and 0 did NOT necessarily match N=10, sigma=2, mu=0, which prompted the more extended definition.</p> <p>The erf(z) in scipy.special would require me to define exactly what t is initially, but it nice to know it is there.</p>
6
2009-02-04T03:49:20Z
510,014
<p>Why not just always do your integration from -infinity to +infinity, so that you always know the answer? (joking!)</p> <p>My guess is that the only reason that there's not already a canned Gaussian function in SciPy is that it's a trivial function to write. Your suggestion about writing your own function and passing it to quad to integrate sounds excellent. It uses the accepted SciPy tool for doing this, it's minimal code effort for you, and it's very readable for other people even if they've never seen SciPy. </p> <p>What exactly do you mean by a fixed-width integrator? Do you mean using a different algorithm than whatever QUADPACK is using?</p> <p>Edit: For completeness, here's something like what I'd try for a Gaussian with the mean of 0 and standard deviation of 1 from 0 to +infinity:</p> <pre><code>from scipy.integrate import quad from math import pi, exp mean = 0 sd = 1 quad(lambda x: 1 / ( sd * ( 2 * pi ) ** 0.5 ) * exp( x ** 2 / (-2 * sd ** 2) ), 0, inf ) </code></pre> <p>That's a little ugly because the Gaussian function is a little long, but still pretty trivial to write. </p>
2
2009-02-04T03:59:32Z
[ "python", "scipy", "gaussian", "integral" ]
Best way to write a Python function that integrates a gaussian?
509,994
<p>In attempting to use scipy's quad method to integrate a gaussian (lets say there's a gaussian method named gauss), I was having problems passing needed parameters to gauss and leaving quad to do the integration over the correct variable. Does anyone have a good example of how to use quad w/ a multidimensional function?</p> <p>But this led me to a more grand question about the best way to integrate a gaussian in general. I didn't find a gaussian integrate in scipy (to my surprise). My plan was to write a simple gaussian function and pass it to quad (or maybe now a fixed width integrator). What would you do?</p> <p>Edit: Fixed-width meaning something like trapz that uses a fixed dx to calculate areas under a curve.</p> <p>What I've come to so far is a method make___gauss that returns a lambda function that can then go into quad. This way I can make a normal function with the average and variance I need before integrating.</p> <pre><code>def make_gauss(N, sigma, mu): return (lambda x: N/(sigma * (2*numpy.pi)**.5) * numpy.e ** (-(x-mu)**2/(2 * sigma**2))) quad(make_gauss(N=10, sigma=2, mu=0), -inf, inf) </code></pre> <p>When I tried passing a general gaussian function (that needs to be called with x, N, mu, and sigma) and filling in some of the values using quad like</p> <pre><code>quad(gen_gauss, -inf, inf, (10,2,0)) </code></pre> <p>the parameters 10, 2, and 0 did NOT necessarily match N=10, sigma=2, mu=0, which prompted the more extended definition.</p> <p>The erf(z) in scipy.special would require me to define exactly what t is initially, but it nice to know it is there.</p>
6
2009-02-04T03:49:20Z
510,037
<p>I assume you're handling multivariate Gaussians; if so, SciPy already has the function you're looking for: it's called MVNDIST ("MultiVariate Normal DISTribution). The SciPy documentation is, as ever, terrible, so I can't even find where the function is buried, but <a href="http://www.google.com/search?q=site%3Ascipy.org+MVNDST+&amp;ie=utf-8&amp;oe=utf-8&amp;aq=t" rel="nofollow">it's in there somewhere</a>. The documentation is easily the worst part of SciPy, and has frustrated me to no end in the past.</p> <p>Single-variable Gaussians just use the good old error function, of which many implementations are available.</p> <p>As for attacking the problem in general, yes, as James Thompson mentions, you just want to write your own gaussian distribution function and feed it to quad(). If you can avoid the generalized integration, though, it's a good idea to do so -- specialized integration techniques for a particular function (like MVNDIST uses) are going to be much faster than a standard Monte Carlo multidimensional integration, which can be extremely slow for high accuracy.</p>
3
2009-02-04T04:10:36Z
[ "python", "scipy", "gaussian", "integral" ]
Best way to write a Python function that integrates a gaussian?
509,994
<p>In attempting to use scipy's quad method to integrate a gaussian (lets say there's a gaussian method named gauss), I was having problems passing needed parameters to gauss and leaving quad to do the integration over the correct variable. Does anyone have a good example of how to use quad w/ a multidimensional function?</p> <p>But this led me to a more grand question about the best way to integrate a gaussian in general. I didn't find a gaussian integrate in scipy (to my surprise). My plan was to write a simple gaussian function and pass it to quad (or maybe now a fixed width integrator). What would you do?</p> <p>Edit: Fixed-width meaning something like trapz that uses a fixed dx to calculate areas under a curve.</p> <p>What I've come to so far is a method make___gauss that returns a lambda function that can then go into quad. This way I can make a normal function with the average and variance I need before integrating.</p> <pre><code>def make_gauss(N, sigma, mu): return (lambda x: N/(sigma * (2*numpy.pi)**.5) * numpy.e ** (-(x-mu)**2/(2 * sigma**2))) quad(make_gauss(N=10, sigma=2, mu=0), -inf, inf) </code></pre> <p>When I tried passing a general gaussian function (that needs to be called with x, N, mu, and sigma) and filling in some of the values using quad like</p> <pre><code>quad(gen_gauss, -inf, inf, (10,2,0)) </code></pre> <p>the parameters 10, 2, and 0 did NOT necessarily match N=10, sigma=2, mu=0, which prompted the more extended definition.</p> <p>The erf(z) in scipy.special would require me to define exactly what t is initially, but it nice to know it is there.</p>
6
2009-02-04T03:49:20Z
510,040
<p>scipy ships with the "error function", aka Gaussian integral:</p> <pre><code>import scipy.special help(scipy.special.erf) </code></pre>
12
2009-02-04T04:11:03Z
[ "python", "scipy", "gaussian", "integral" ]
Best way to write a Python function that integrates a gaussian?
509,994
<p>In attempting to use scipy's quad method to integrate a gaussian (lets say there's a gaussian method named gauss), I was having problems passing needed parameters to gauss and leaving quad to do the integration over the correct variable. Does anyone have a good example of how to use quad w/ a multidimensional function?</p> <p>But this led me to a more grand question about the best way to integrate a gaussian in general. I didn't find a gaussian integrate in scipy (to my surprise). My plan was to write a simple gaussian function and pass it to quad (or maybe now a fixed width integrator). What would you do?</p> <p>Edit: Fixed-width meaning something like trapz that uses a fixed dx to calculate areas under a curve.</p> <p>What I've come to so far is a method make___gauss that returns a lambda function that can then go into quad. This way I can make a normal function with the average and variance I need before integrating.</p> <pre><code>def make_gauss(N, sigma, mu): return (lambda x: N/(sigma * (2*numpy.pi)**.5) * numpy.e ** (-(x-mu)**2/(2 * sigma**2))) quad(make_gauss(N=10, sigma=2, mu=0), -inf, inf) </code></pre> <p>When I tried passing a general gaussian function (that needs to be called with x, N, mu, and sigma) and filling in some of the values using quad like</p> <pre><code>quad(gen_gauss, -inf, inf, (10,2,0)) </code></pre> <p>the parameters 10, 2, and 0 did NOT necessarily match N=10, sigma=2, mu=0, which prompted the more extended definition.</p> <p>The erf(z) in scipy.special would require me to define exactly what t is initially, but it nice to know it is there.</p>
6
2009-02-04T03:49:20Z
511,155
<p>Okay, you appear to be pretty confused about several things. Let's start at the beginning: you mentioned a "multidimensional function", but then go on to discuss the usual one-variable Gaussian curve. This is <em>not</em> a multidimensional function: when you integrate it, you only integrate one variable (x). The distinction is important to make, because there <em>is</em> a monster called a "multivariate Gaussian distribution" which is a true multidimensional function and, if integrated, requires integrating over two or more variables (which uses the expensive Monte Carlo technique I mentioned before). But you seem to just be talking about the regular one-variable Gaussian, which is much easier to work with, integrate, and all that.</p> <p>The one-variable Gaussian distribution has two parameters, <code>sigma</code> and <code>mu</code>, and is a function of a single variable we'll denote <code>x</code>. You also appear to be carrying around a normalization parameter <code>n</code> (which is useful in a couple of applications). Normalization parameters are usually <em>not</em> included in calculations, since you can just tack them back on at the end (remember, integration is a linear operator: <code>int(n*f(x), x) = n*int(f(x), x)</code> ). But we can carry it around if you like; the notation I like for a normal distribution is then </p> <p><code>N(x | mu, sigma, n) := (n/(sigma*sqrt(2*pi))) * exp((-(x-mu)^2)/(2*sigma^2))</code></p> <p>(read that as "the normal distribution of <code>x</code> given <code>sigma</code>, <code>mu</code>, and <code>n</code> is given by...") So far, so good; this matches the function you've got. Notice that the only <em>true variable</em> here is <code>x</code>: the other three parameters are <em>fixed</em> for any particular Gaussian.</p> <p>Now for a mathematical fact: it is provably true that all Gaussian curves have the same shape, they're just shifted around a little bit. So we can work with <code>N(x|0,1,1)</code>, called the "standard normal distribution", and just translate our results back to the general Gaussian curve. So if you have the integral of <code>N(x|0,1,1)</code>, you can trivially calculate the integral of any Gaussian. This integral appears so frequently that it has a special name: the <em>error function</em> <code>erf</code>. Because of some old conventions, it's not <em>exactly</em> <code>erf</code>; there are a couple additive and multiplicative factors also being carried around. </p> <p>If <code>Phi(z) = integral(N(x|0,1,1), -inf, z)</code>; that is, <code>Phi(z)</code> is the integral of the standard normal distribution from minus infinity up to <code>z</code>, then it's true by the definition of the error function that</p> <p><code>Phi(z) = 0.5 + 0.5 * erf(z / sqrt(2))</code>.</p> <p>Likewise, if <code>Phi(z | mu, sigma, n) = integral( N(x|sigma, mu, n), -inf, z)</code>; that is, <code>Phi(z | mu, sigma, n)</code> is the integral of the normal distribution given parameters <code>mu</code>, <code>sigma</code>, and <code>n</code> from minus infinity up to <code>z</code>, then it's true by the definition of the error function that</p> <p><code>Phi(z | mu, sigma, n) = (n/2) * (1 + erf((x - mu) / (sigma * sqrt(2))))</code>.</p> <p>Take a look at <a href="http://en.wikipedia.org/wiki/Normal_distribution#Cumulative_distribution_function">the Wikipedia article on the normal CDF</a> if you want more detail or a proof of this fact.</p> <p>Okay, that should be enough background explanation. Back to your (edited) post. You say "The erf(z) in scipy.special would require me to define exactly what t is initially". I have no idea what you mean by this; where does <code>t</code> (time?) enter into this at all? Hopefully the explanation above has demystified the error function a bit and it's clearer now as to why the error function is the right function for the job.</p> <p>Your Python code is OK, but I would prefer a closure over a lambda:</p> <pre><code>def make_gauss(N, sigma, mu): k = N / (sigma * math.sqrt(2*math.pi)) s = -1.0 / (2 * sigma * sigma) def f(x): return k * math.exp(s * (x - mu)*(x - mu)) return f </code></pre> <p>Using a closure enables precomputation of constants <code>k</code> and <code>s</code>, so the returned function will need to do less work each time it's called (which can be important if you're integrating it, which means it'll be called many times). Also, I have avoided any use of the exponentiation operator <code>**</code>, which is slower than just writing the squaring out, and hoisted the divide out of the inner loop and replaced it with a multiply. I haven't looked at all at their implementation in Python, but from my last time tuning an inner loop for pure speed using raw x87 assembly, I seem to remember that adds, subtracts, or multiplies take about 4 CPU cycles each, divides about 36, and exponentiation about 200. That was a couple years ago, so take those numbers with a grain of salt; still, it illustrates their relative complexity. As well, calculating <code>exp(x)</code> the brute-force way is a very bad idea; there are tricks you can take when writing a good implementation of <code>exp(x)</code> that make it significantly faster and more accurate than a general <code>a**b</code> style exponentiation.</p> <p>I've never used the numpy version of the constants pi and e; I've always stuck with the plain old math module's versions. I don't know why you might prefer either one.</p> <p>I'm not sure what you're going for with the <code>quad()</code> call. <code>quad(gen_gauss, -inf, inf, (10,2,0))</code> ought to integrate a renormalized Gaussian from minus infinity to plus infinity, and should always spit out 10 (your normalization factor), since the Gaussian integrates to 1 over the real line. Any answer far from 10 (I wouldn't expect <em>exactly</em> 10 since <code>quad()</code> is only an approximation, after all) means something is screwed up somewhere... hard to say what's screwed up without knowing the actual return value and possibly the inner workings of <code>quad()</code>.</p> <p>Hopefully that has demystified some of the confusion, and explained why the error function is the right answer to your problem, as well as how to do it all yourself if you're curious. If any of my explanation wasn't clear, I suggest taking a quick look at Wikipedia first; if you still have questions, don't hesitate to ask. </p>
27
2009-02-04T12:32:51Z
[ "python", "scipy", "gaussian", "integral" ]
Best way to write a Python function that integrates a gaussian?
509,994
<p>In attempting to use scipy's quad method to integrate a gaussian (lets say there's a gaussian method named gauss), I was having problems passing needed parameters to gauss and leaving quad to do the integration over the correct variable. Does anyone have a good example of how to use quad w/ a multidimensional function?</p> <p>But this led me to a more grand question about the best way to integrate a gaussian in general. I didn't find a gaussian integrate in scipy (to my surprise). My plan was to write a simple gaussian function and pass it to quad (or maybe now a fixed width integrator). What would you do?</p> <p>Edit: Fixed-width meaning something like trapz that uses a fixed dx to calculate areas under a curve.</p> <p>What I've come to so far is a method make___gauss that returns a lambda function that can then go into quad. This way I can make a normal function with the average and variance I need before integrating.</p> <pre><code>def make_gauss(N, sigma, mu): return (lambda x: N/(sigma * (2*numpy.pi)**.5) * numpy.e ** (-(x-mu)**2/(2 * sigma**2))) quad(make_gauss(N=10, sigma=2, mu=0), -inf, inf) </code></pre> <p>When I tried passing a general gaussian function (that needs to be called with x, N, mu, and sigma) and filling in some of the values using quad like</p> <pre><code>quad(gen_gauss, -inf, inf, (10,2,0)) </code></pre> <p>the parameters 10, 2, and 0 did NOT necessarily match N=10, sigma=2, mu=0, which prompted the more extended definition.</p> <p>The erf(z) in scipy.special would require me to define exactly what t is initially, but it nice to know it is there.</p>
6
2009-02-04T03:49:20Z
4,724,815
<p>The gaussian distribution is also called a normal distribution. The cdf function in the scipy norm module does what you want.</p> <pre><code>from scipy.stats import norm print norm.cdf(0.0) &gt;&gt;&gt;0.5 </code></pre> <p><a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.norm.html#scipy.stats.norm" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.norm.html#scipy.stats.norm</a></p>
3
2011-01-18T13:49:59Z
[ "python", "scipy", "gaussian", "integral" ]
How to call a python function from a foreign language thread (C++)
510,085
<p>I am developing a program that use DirectShow to grab audio data from media files. DirectShow use thread to pass audio data to the callback function in my program, and I let that callback function call another function in Python.</p> <p>I use Boost.Python to wrapper my library, the callback function :</p> <pre><code>class PythonCallback { private: object m_Function; public: PythonCallback(object obj) : m_Function(obj) {} void operator() (double time, const AudioData &amp;data) { // Call the callback function in python m_Function(time, data); } }; </code></pre> <p>Here comes the problem, a thread of DirectShow calls my PythonCallback, namely, call the function in Python. Once it calls, my program just crash. I found this should be threading problem. Then I found this document:</p> <p><a href="http://docs.python.org/c-api/init.html" rel="nofollow">http://docs.python.org/c-api/init.html</a></p> <p>It seems that my program can't call to Python's function from thread directly, because there is Global Interpreter Lock. The python's GIL is so complex, I have no idea how it works. I'm sorry, what I can do is to ask. My question is. What should I do before and after I call a Python function from threads?</p> <p>It may looks like this.</p> <pre><code>void operator() (double time, const AudioData &amp;data) { // acquire lock m_Function(time, data); // release lock } </code></pre> <p>Thanks. Victor Lin. </p>
4
2009-02-04T04:39:02Z
510,094
<p>Have the c++ callback place the data in a queue. Have the python code poll the queue to extract the data.</p>
1
2009-02-04T04:42:12Z
[ "c++", "python", "multithreading", "boost", "locking" ]
How to call a python function from a foreign language thread (C++)
510,085
<p>I am developing a program that use DirectShow to grab audio data from media files. DirectShow use thread to pass audio data to the callback function in my program, and I let that callback function call another function in Python.</p> <p>I use Boost.Python to wrapper my library, the callback function :</p> <pre><code>class PythonCallback { private: object m_Function; public: PythonCallback(object obj) : m_Function(obj) {} void operator() (double time, const AudioData &amp;data) { // Call the callback function in python m_Function(time, data); } }; </code></pre> <p>Here comes the problem, a thread of DirectShow calls my PythonCallback, namely, call the function in Python. Once it calls, my program just crash. I found this should be threading problem. Then I found this document:</p> <p><a href="http://docs.python.org/c-api/init.html" rel="nofollow">http://docs.python.org/c-api/init.html</a></p> <p>It seems that my program can't call to Python's function from thread directly, because there is Global Interpreter Lock. The python's GIL is so complex, I have no idea how it works. I'm sorry, what I can do is to ask. My question is. What should I do before and after I call a Python function from threads?</p> <p>It may looks like this.</p> <pre><code>void operator() (double time, const AudioData &amp;data) { // acquire lock m_Function(time, data); // release lock } </code></pre> <p>Thanks. Victor Lin. </p>
4
2009-02-04T04:39:02Z
511,740
<p>Take a look at PyGILState_Ensure()/PyGILState_Release(), from PEP 311 <a href="http://www.python.org/dev/peps/pep-0311/">http://www.python.org/dev/peps/pep-0311/</a></p> <p>Here is an example taken from the PEP itself:</p> <pre><code>void SomeCFunction(void) { /* ensure we hold the lock */ PyGILState_STATE state = PyGILState_Ensure(); /* Use the Python API */ ... /* Restore the state of Python */ PyGILState_Release(state); } </code></pre>
6
2009-02-04T15:06:30Z
[ "c++", "python", "multithreading", "boost", "locking" ]
creating blank field and receving the INTEGER PRIMARY KEY with sqlite, python
510,135
<p>I am using sqlite with python. When i insert into table A i need to feed it an ID from table B. So what i wanted to do is insert default data into B, grab the id (which is auto increment) and use it in table A. Whats the best way receive the key from the table i just inserted into?</p>
3
2009-02-04T05:06:34Z
510,167
<p>Check out <a href="http://www.sqlite.org/c3ref/last_insert_rowid.html" rel="nofollow">sqlite3_last_insert_rowid()</a> -- it's probably what you're looking for:</p> <blockquote> <p>Each entry in an SQLite table has a unique 64-bit signed integer key called the "rowid". The rowid is always available as an undeclared column named ROWID, OID, or _ROWID_ as long as those names are not also used by explicitly declared columns. If the table has a column of type INTEGER PRIMARY KEY then that column is another alias for the rowid.</p> <p>This routine returns the rowid of the most recent successful INSERT into the database from the database connection in the first argument. If no successful INSERTs have ever occurred on that database connection, zero is returned.</p> </blockquote> <p>Hope it helps! (More info on ROWID is available <a href="http://www.sqlite.org/lang_createtable.html#rowid" rel="nofollow">here</a> and <a href="http://www.sqlite.org/lang_corefunc.html" rel="nofollow">here</a>.)</p>
1
2009-02-04T05:28:16Z
[ "python", "sqlite" ]
creating blank field and receving the INTEGER PRIMARY KEY with sqlite, python
510,135
<p>I am using sqlite with python. When i insert into table A i need to feed it an ID from table B. So what i wanted to do is insert default data into B, grab the id (which is auto increment) and use it in table A. Whats the best way receive the key from the table i just inserted into?</p>
3
2009-02-04T05:06:34Z
510,182
<p>As Christian said, <code>sqlite3_last_insert_rowid()</code> is what you want... but that's the C level API, and you're using the Python DB-API bindings for SQLite.</p> <p>It looks like the cursor method <code>lastrowid</code> will do what you want <a href="http://docs.python.org/library/sqlite3.html" rel="nofollow">(search for 'lastrowid' in the documentation for more information)</a>. Insert your row with <code>cursor.execute( ... )</code>, then do something like <code>lastid = cursor.lastrowid</code> to check the last ID inserted.</p> <p>That you say you need "an" ID worries me, though... it doesn't matter <em>which</em> ID you have? Unless you are using the data just inserted into B for something, in which case you need <em>that</em> row ID, your database structure is seriously screwed up if you just need any old row ID for table B.</p>
7
2009-02-04T05:34:27Z
[ "python", "sqlite" ]
creating blank field and receving the INTEGER PRIMARY KEY with sqlite, python
510,135
<p>I am using sqlite with python. When i insert into table A i need to feed it an ID from table B. So what i wanted to do is insert default data into B, grab the id (which is auto increment) and use it in table A. Whats the best way receive the key from the table i just inserted into?</p>
3
2009-02-04T05:06:34Z
511,610
<p>Simply use:</p> <pre><code>SELECT last_insert_rowid(); </code></pre> <p>However, if you have multiple connections writing to the database, you might not get back the key that you expect.</p>
1
2009-02-04T14:36:36Z
[ "python", "sqlite" ]
How do I use django mptt?
510,339
<p>I have a model:</p> <pre><code>class Company(models.Model): name = models.CharField( max_length=100) parent = models.ForeignKey('self', null=True, blank=True, related_name='children') mptt.register(Company, order_insertion_by=['name']) </code></pre> <p>and </p> <pre><code>class Financials(models.Model): year = models.IntegerField() revenue = models.DecimalField(max_digits = 10, decimal_places = 2) </code></pre> <p>So how can I add <code>Financials</code> as a child to <code>Company</code> in the mptt tree structure?</p>
1
2009-02-04T07:01:32Z
510,834
<p>I don't quite follow your question. A tree stores one type of object, in your case Company. To link Financials to Company just add a foreign key from Financials to Company.</p> <p>If this doesn't help please expand your question to give us some more detail about what you are trying to achieve.</p>
1
2009-02-04T10:45:07Z
[ "python", "django", "django-models", "django-mptt" ]
How can I make a time delay in Python?
510,348
<p>I would like to know how to put a time delay in a Python script.</p>
1,061
2009-02-04T07:04:09Z
64,486
<p>You can use the sleep() function in the time module. It can take a float argument for sub second resolution.</p> <pre><code>from time import sleep sleep(0.1) # Time in seconds. </code></pre>
330
2008-09-15T16:34:29Z
[ "python", "sleep", "timedelay" ]
How can I make a time delay in Python?
510,348
<p>I would like to know how to put a time delay in a Python script.</p>
1,061
2009-02-04T07:04:09Z
510,351
<pre><code>import time time.sleep(5) # delays for 5 seconds </code></pre> <p>Here is another example where something is run once a minute:</p> <pre><code>import time while True: print "This prints once a minute." time.sleep(60) # Delay for 1 minute (60 seconds) </code></pre>
1,176
2009-02-04T07:05:59Z
[ "python", "sleep", "timedelay" ]
How can I make a time delay in Python?
510,348
<p>I would like to know how to put a time delay in a Python script.</p>
1,061
2009-02-04T07:04:09Z
510,356
<p>Please read <a href="http://www.faqts.com/knowledge_base/view.phtml/aid/2609/fid/378">http://www.faqts.com/knowledge_base/view.phtml/aid/2609/fid/378</a>, which can help you further:</p> <blockquote> <p>Try the sleep function in the time module.</p> <pre><code>import time time.sleep(60) </code></pre> <p>And put this in a while loop and a statement will only execute on the minute... That allows you to run a statement at predefined intervals regardless of how long the command takes (as long as it takes less than a minute or 5 or 60 or whatever you set it to) For example, I wanted to run a ping once a minute. If I just time.sleep(60) or time.sleep(45) even, the ping will not always take the same amount of time. Here's the code :)</p> <pre><code>time.sleep(time.localtime(time.time())[5]) </code></pre> <p>The [5] just pulls the seconds out of the time.localtime()'s return value.</p> <p>The great thing about time.sleep is that it supports floating point numbers!</p> <pre><code>import time time.sleep(0.1) </code></pre> <p><a href="http://python.org/doc/current/lib/module-time.html">http://python.org/doc/current/lib/module-time.html</a></p> </blockquote>
40
2009-02-04T07:07:32Z
[ "python", "sleep", "timedelay" ]
How can I make a time delay in Python?
510,348
<p>I would like to know how to put a time delay in a Python script.</p>
1,061
2009-02-04T07:04:09Z
6,234,820
<p>What You Need Is </p> <p><code>time.sleep(sec)</code></p> <p>where sec is how many seconds delay you add there</p> <p>you also need to </p> <p><code>import time</code></p>
57
2011-06-04T05:03:16Z
[ "python", "sleep", "timedelay" ]
How can I make a time delay in Python?
510,348
<p>I would like to know how to put a time delay in a Python script.</p>
1,061
2009-02-04T07:04:09Z
22,583,596
<p>There is a built-in Python module called <code>time</code>. Use it like this:</p> <pre><code>import time time.sleep(5) </code></pre> <p>This will make the script wait for 5 seconds.</p>
153
2014-03-22T21:06:10Z
[ "python", "sleep", "timedelay" ]
How can I make a time delay in Python?
510,348
<p>I would like to know how to put a time delay in a Python script.</p>
1,061
2009-02-04T07:04:09Z
23,131,522
<p>There is a built in python module named time. </p> <p>The 2 examples are identical but differ only in the way the method is imported from the module:</p> <p>1 Use This:</p> <pre><code> import time time.sleep(Num of seconds to sleep) </code></pre> <p>2 Use this:</p> <pre><code> from time import sleep sleep(Num of seconds to sleep) </code></pre>
19
2014-04-17T11:08:36Z
[ "python", "sleep", "timedelay" ]
How can I make a time delay in Python?
510,348
<p>I would like to know how to put a time delay in a Python script.</p>
1,061
2009-02-04T07:04:09Z
23,665,492
<p>A bit of fun with sleepy generator.</p> <p>The question is about time delay. It can be fixed time, but in some cases we might need a delay measured since last time. Here is one possible solutions:</p> <h1>Delay measured since last time (waking up regularly)</h1> <p>The situation can be, we want to do something as regularly as possible and we do not want to bother with all the <code>last_time</code>, <code>next_time</code> stuff all around our code.</p> <h2>buzzer generator</h2> <p>Following code (<strong>sleepy.py</strong>) defines <code>buzzergen</code> gerenarator</p> <pre><code>import time from itertools import count def buzzergen(period): nexttime = time.time() + period for i in count(): now = time.time() tosleep = nexttime - now if tosleep &gt; 0: time.sleep(tosleep) nexttime += period else: nexttime = now + period yield i, nexttime </code></pre> <h2>Invoking regular buzzergen</h2> <pre><code>from sleepy import buzzergen import time buzzer = buzzergen(3) # planning to wake up each 3 seconds print time.time() buzzer.next() print time.time() time.sleep(2) buzzer.next() print time.time() time.sleep(5) # sleeping a bit longer than usually buzzer.next() print time.time() buzzer.next() print time.time() </code></pre> <p>and running it we see:</p> <pre><code>1400102636.46 1400102639.46 1400102642.46 1400102647.47 1400102650.47 </code></pre> <p>We can also use it directly in a loop:</p> <pre><code>import random for ring in buzzergen(3): print "now", time.time() print "ring", ring time.sleep(random.choice([0, 2, 4, 6])) </code></pre> <p>and running it we might see:</p> <pre><code>now 1400102751.46 ring (0, 1400102754.461676) now 1400102754.46 ring (1, 1400102757.461676) now 1400102757.46 ring (2, 1400102760.461676) now 1400102760.46 ring (3, 1400102763.461676) now 1400102766.47 ring (4, 1400102769.47115) now 1400102769.47 ring (5, 1400102772.47115) now 1400102772.47 ring (6, 1400102775.47115) now 1400102775.47 ring (7, 1400102778.47115) </code></pre> <p>As we see, this buzzer is not too rigid and allow us to catch up regular sleepy intervals even if we oversleep and get out of regular schedule.</p>
18
2014-05-14T21:30:35Z
[ "python", "sleep", "timedelay" ]
How can I make a time delay in Python?
510,348
<p>I would like to know how to put a time delay in a Python script.</p>
1,061
2009-02-04T07:04:09Z
28,965,832
<p>to halt further execution for defined time, sleep method is available in time package. it easy all you have to do is at the top of your code type in<br> <code>from time import sleep</code><br> then use sleep in your desired code let say 5 seconds:</p> <p><code>sleep(5)</code></p> <p>alternatively you can import time and then use time.sleep(5)</p> <p><code>import time</code><br> then go to the line where you want it to wait<br> and type in<br> <code>time.sleep(5)</code></p>
18
2015-03-10T14:04:40Z
[ "python", "sleep", "timedelay" ]
Python read a single character from the user
510,357
<p>Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like <code>getch()</code>). I know there's a function in Windows for it, but I'd like something that is cross-platform.</p>
157
2009-02-04T07:08:03Z
510,364
<p>Here's a link to a site that says how you can read a single character in Windows, Linux and OSX: <a href="http://code.activestate.com/recipes/134892/">http://code.activestate.com/recipes/134892/</a></p> <pre><code>class _Getch: """Gets a single character from standard input. Does not echo to the screen.""" def __init__(self): try: self.impl = _GetchWindows() except ImportError: self.impl = _GetchUnix() def __call__(self): return self.impl() class _GetchUnix: def __init__(self): import tty, sys def __call__(self): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class _GetchWindows: def __init__(self): import msvcrt def __call__(self): import msvcrt return msvcrt.getch() getch = _Getch() </code></pre>
105
2009-02-04T07:11:04Z
[ "python", "input" ]
Python read a single character from the user
510,357
<p>Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like <code>getch()</code>). I know there's a function in Windows for it, but I'd like something that is cross-platform.</p>
157
2009-02-04T07:08:03Z
510,404
<pre><code>sys.stdin.read(1) </code></pre> <p>will basically read 1 byte from STDIN.</p> <p>If you must use the method which does not wait for the <code>\n</code> you can use this code as suggested in previous answer:</p> <pre><code>class _Getch: """Gets a single character from standard input. Does not echo to the screen.""" def __init__(self): try: self.impl = _GetchWindows() except ImportError: self.impl = _GetchUnix() def __call__(self): return self.impl() class _GetchUnix: def __init__(self): import tty, sys def __call__(self): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class _GetchWindows: def __init__(self): import msvcrt def __call__(self): import msvcrt return msvcrt.getch() getch = _Getch() </code></pre> <p>(<em>taken from</em> <a href="http://code.activestate.com/recipes/134892/"><em>http://code.activestate.com/recipes/134892/</em></a>)</p>
54
2009-02-04T07:30:51Z
[ "python", "input" ]
Python read a single character from the user
510,357
<p>Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like <code>getch()</code>). I know there's a function in Windows for it, but I'd like something that is cross-platform.</p>
157
2009-02-04T07:08:03Z
510,897
<p>I think it gets extremely clunky at this point, and debugging on the different platforms is a big mess.</p> <p>You'd be better off using something like pyglet, pygame, cocos2d - if you are doing something more elaborate than this and will need visuals, OR <strong>curses</strong> if you are going to work with the terminal.</p> <p>Curses is standard: <a href="http://docs.python.org/library/curses.html">http://docs.python.org/library/curses.html</a></p>
12
2009-02-04T11:04:26Z
[ "python", "input" ]
Python read a single character from the user
510,357
<p>Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like <code>getch()</code>). I know there's a function in Windows for it, but I'd like something that is cross-platform.</p>
157
2009-02-04T07:08:03Z
7,259,460
<p>An alternative method:</p> <pre><code>import os import sys import termios import fcntl def getch(): fd = sys.stdin.fileno() oldterm = termios.tcgetattr(fd) newattr = termios.tcgetattr(fd) newattr[3] = newattr[3] &amp; ~termios.ICANON &amp; ~termios.ECHO termios.tcsetattr(fd, termios.TCSANOW, newattr) oldflags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK) try: while 1: try: c = sys.stdin.read(1) break except IOError: pass finally: termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags) return c </code></pre> <p>From <a href="http://love-python.blogspot.com/2010/03/getch-in-python-get-single-character.html">this blog post</a>.</p>
14
2011-08-31T15:30:40Z
[ "python", "input" ]
Python read a single character from the user
510,357
<p>Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like <code>getch()</code>). I know there's a function in Windows for it, but I'd like something that is cross-platform.</p>
157
2009-02-04T07:08:03Z
20,865,751
<p>This code, based off <a href="http://code.activestate.com/recipes/134892/">here</a>, will correctly raise KeyboardInterrupt and EOFError if <kbd>Ctrl</kbd>+<kbd>C</kbd> or <kbd>Ctrl</kbd>+<kbd>D</kbd> are pressed.</p> <p>Should work on Windows and Linux. An OS X version is available from the original source.</p> <pre><code>class _Getch: """Gets a single character from standard input. Does not echo to the screen.""" def __init__(self): try: self.impl = _GetchWindows() except ImportError: self.impl = _GetchUnix() def __call__(self): char = self.impl() if char == '\x03': raise KeyboardInterrupt elif char == '\x04': raise EOFError return char class _GetchUnix: def __init__(self): import tty import sys def __call__(self): import sys import tty import termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class _GetchWindows: def __init__(self): import msvcrt def __call__(self): import msvcrt return msvcrt.getch() getch = _Getch() </code></pre>
9
2014-01-01T05:13:33Z
[ "python", "input" ]
Python read a single character from the user
510,357
<p>Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like <code>getch()</code>). I know there's a function in Windows for it, but I'd like something that is cross-platform.</p>
157
2009-02-04T07:08:03Z
21,659,588
<p>The ActiveState <a href="http://code.activestate.com/recipes/134892/">recipe</a> quoted verbatim in two answers is over-engineered. It can be boiled down to this:</p> <pre><code>def _find_getch(): try: import termios except ImportError: # Non-POSIX. Return msvcrt's (Windows') getch. import msvcrt return msvcrt.getch # POSIX system. Create and return a getch that manipulates the tty. import sys, tty def _getch(): fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(fd) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch return _getch getch = _find_getch() </code></pre>
31
2014-02-09T13:27:42Z
[ "python", "input" ]
Python read a single character from the user
510,357
<p>Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like <code>getch()</code>). I know there's a function in Windows for it, but I'd like something that is cross-platform.</p>
157
2009-02-04T07:08:03Z
24,355,550
<p>This is NON-BLOCKING, reads a key and and stores it in keypress.key. </p> <pre><code>import Tkinter as tk class Keypress: def __init__(self): self.root = tk.Tk() self.root.geometry('300x200') self.root.bind('&lt;KeyPress&gt;', self.onKeyPress) def onKeyPress(self, event): self.key = event.char def __eq__(self, other): return self.key == other def __str__(self): return self.key </code></pre> <p>in your programm</p> <pre><code>keypress = Keypress() while something: do something if keypress == 'c': break elif keypress == 'i': print('info') else: print("i dont understand %s" % keypress) </code></pre>
2
2014-06-22T20:40:36Z
[ "python", "input" ]
Python read a single character from the user
510,357
<p>Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like <code>getch()</code>). I know there's a function in Windows for it, but I'd like something that is cross-platform.</p>
157
2009-02-04T07:08:03Z
25,342,814
<p>Also worth trying is the <a href="https://github.com/magmax/python-readchar">readchar</a> library, which is in part based on the ActiveState recipe mentioned in other answers.</p> <p>Installation:</p> <pre><code>pip install readchar </code></pre> <p>Usage:</p> <pre><code>import readchar print("Reading a char:") print(repr(readchar.readchar())) print("Reading a key:") print(repr(readchar.readkey())) </code></pre> <p>Tested on Windows and Linux with Python 2.7.</p> <p>On Windows, only keys which map to letters or ASCII control codes are supported (<kbd>Backspace</kbd>, <kbd>Enter</kbd>, <kbd>Esc</kbd>, <kbd>Tab</kbd>, <kbd>Ctrl</kbd>+<em>letter</em>). On GNU/Linux (depending on exact terminal, perhaps?) you also get <kbd>Insert</kbd>, <kbd>Delete</kbd>, <kbd>Pg Up</kbd>, <kbd>Pg Dn</kbd>, <kbd>Home</kbd>, <kbd>End</kbd> and <kbd>F <em>n</em></kbd> keys... but then, there's issues separating these special keys from an <kbd>Esc</kbd>.</p> <p>Caveat: Like with most (all?) answers in here, signal keys like <kbd>Ctrl</kbd>+<kbd>C</kbd>, <kbd>Ctrl</kbd>+<kbd>D</kbd> and <kbd>Ctrl</kbd>+<kbd>Z</kbd> are caught and returned (as <code>'\x03'</code>, <code>'\x04'</code> and <code>'\x1a'</code> respectively); your program can be come difficult to abort.</p>
21
2014-08-16T18:47:41Z
[ "python", "input" ]
Python read a single character from the user
510,357
<p>Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like <code>getch()</code>). I know there's a function in Windows for it, but I'd like something that is cross-platform.</p>
157
2009-02-04T07:08:03Z
26,089,126
<p>This might be a use case for a context manager. Leaving aside allowances for Windows OS, here's my suggestion:</p> <pre><code>#!/usr/bin/env python3 # file: 'readchar.py' """ Implementation of a way to get a single character of input without waiting for the user to hit &lt;Enter&gt;. (OS is Linux, Ubuntu 14.04) """ import tty, sys, termios class ReadChar(): def __enter__(self): self.fd = sys.stdin.fileno() self.old_settings = termios.tcgetattr(self.fd) tty.setraw(sys.stdin.fileno()) return sys.stdin.read(1) def __exit__(self, type, value, traceback): termios.tcsetattr(self.fd, termios.TCSADRAIN, self.old_settings) def test(): while True: with ReadChar() as rc: char = rc if ord(char) &lt;= 32: print("You entered character with ordinal {}."\ .format(ord(char))) else: print("You entered character '{}'."\ .format(char)) if char in "^C^D": sys.exit() if __name__ == "__main__": test() </code></pre>
4
2014-09-28T20:07:19Z
[ "python", "input" ]
Python read a single character from the user
510,357
<p>Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like <code>getch()</code>). I know there's a function in Windows for it, but I'd like something that is cross-platform.</p>
157
2009-02-04T07:08:03Z
27,693,470
<p>The <code>curses</code> package in python can be used to enter "raw" mode for character input from the terminal with just a few statements. Curses' main use is to take over the screen for output, which may not be what you want. This code snippet uses <code>print()</code> statements instead, which are usable, but you must be aware of how curses changes line endings attached to output. </p> <pre><code>#!/usr/bin/python3 # Demo of single char terminal input in raw mode with the curses package. import sys, curses def run_one_char(dummy): 'Run until a carriage return is entered' char = ' ' print('Welcome to curses', flush=True) while ord(char) != 13: char = one_char() def one_char(): 'Read one character from the keyboard' print('\r? ', flush= True, end = '') ## A blocking single char read in raw mode. char = sys.stdin.read(1) print('You entered %s\r' % char) return char ## Must init curses before calling any functions curses.initscr() ## To make sure the terminal returns to its initial settings, ## and to set raw mode and guarantee cleanup on exit. curses.wrapper(run_one_char) print('Curses be gone!') </code></pre>
0
2014-12-29T17:38:01Z
[ "python", "input" ]
Python read a single character from the user
510,357
<p>Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like <code>getch()</code>). I know there's a function in Windows for it, but I'd like something that is cross-platform.</p>
157
2009-02-04T07:08:03Z
28,640,609
<p>Try this with pygame:</p> <pre><code>import pygame pygame.init() // eliminate error, pygame.error: video system not initialized keys = pygame.key.get_pressed() if keys[pygame.K_SPACE]: d = "space key" print "You pressed the", d, "." </code></pre>
2
2015-02-21T00:36:21Z
[ "python", "input" ]
Python read a single character from the user
510,357
<p>Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like <code>getch()</code>). I know there's a function in Windows for it, but I'd like something that is cross-platform.</p>
157
2009-02-04T07:08:03Z
31,550,142
<p>Try using this: <a href="http://home.wlu.edu/~levys/software/kbhit.py" rel="nofollow">http://home.wlu.edu/~levys/software/kbhit.py</a> It's non-blocking (that means that you can have a while loop and detect a key press without stopping it) and cross-platform.</p> <pre><code>import os # Windows if os.name == 'nt': import msvcrt # Posix (Linux, OS X) else: import sys import termios import atexit from select import select class KBHit: def __init__(self): '''Creates a KBHit object that you can call to do various keyboard things.''' if os.name == 'nt': pass else: # Save the terminal settings self.fd = sys.stdin.fileno() self.new_term = termios.tcgetattr(self.fd) self.old_term = termios.tcgetattr(self.fd) # New terminal setting unbuffered self.new_term[3] = (self.new_term[3] &amp; ~termios.ICANON &amp; ~termios.ECHO) termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.new_term) # Support normal-terminal reset at exit atexit.register(self.set_normal_term) def set_normal_term(self): ''' Resets to normal terminal. On Windows this is a no-op. ''' if os.name == 'nt': pass else: termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old_term) def getch(self): ''' Returns a keyboard character after kbhit() has been called. Should not be called in the same program as getarrow(). ''' s = '' if os.name == 'nt': return msvcrt.getch().decode('utf-8') else: return sys.stdin.read(1) def getarrow(self): ''' Returns an arrow-key code after kbhit() has been called. Codes are 0 : up 1 : right 2 : down 3 : left Should not be called in the same program as getch(). ''' if os.name == 'nt': msvcrt.getch() # skip 0xE0 c = msvcrt.getch() vals = [72, 77, 80, 75] else: c = sys.stdin.read(3)[2] vals = [65, 67, 66, 68] return vals.index(ord(c.decode('utf-8'))) def kbhit(self): ''' Returns True if keyboard character was hit, False otherwise. ''' if os.name == 'nt': return msvcrt.kbhit() else: dr,dw,de = select([sys.stdin], [], [], 0) return dr != [] </code></pre> <p>An example to use this:</p> <pre><code>import kbhit kb = kbhit.KBHit() while(True): print("Key not pressed") #Do something if kb.kbhit(): #If a key is pressed: k_in = kb.getch() #Detect what key was pressed print("You pressed ", k_in, "!") #Do something kb.set_normal_term() </code></pre> <p>Or you could use the <a href="https://pypi.python.org/pypi/getch" rel="nofollow">getch module from PyPi</a>. But this would block the while loop</p>
2
2015-07-21T21:42:36Z
[ "python", "input" ]
Python read a single character from the user
510,357
<p>Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like <code>getch()</code>). I know there's a function in Windows for it, but I'd like something that is cross-platform.</p>
157
2009-02-04T07:08:03Z
31,749,681
<p>The answers <a href="http://code.activestate.com/recipes/134892-getch-like-unbuffered-character-reading-from-stdin/" rel="nofollow">here</a> were informative, however I also wanted a way to get key presses asynchronously and fire off key presses in separate events, all in a thread-safe, cross-platform way. PyGame was also too bloated for me. So I made the following (in Python 2.7 but I suspect it's easily portable), which I figured I'd share here in case it was useful for anyone else. I stored this in a file named keyPress.py.</p> <pre><code>class _Getch: """Gets a single character from standard input. Does not echo to the screen. From http://code.activestate.com/recipes/134892/""" def __init__(self): try: self.impl = _GetchWindows() except ImportError: try: self.impl = _GetchMacCarbon() except(AttributeError, ImportError): self.impl = _GetchUnix() def __call__(self): return self.impl() class _GetchUnix: def __init__(self): import tty, sys, termios # import termios now or else you'll get the Unix version on the Mac def __call__(self): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class _GetchWindows: def __init__(self): import msvcrt def __call__(self): import msvcrt return msvcrt.getch() class _GetchMacCarbon: """ A function which returns the current ASCII key that is down; if no ASCII key is down, the null string is returned. The page http://www.mactech.com/macintosh-c/chap02-1.html was very helpful in figuring out how to do this. """ def __init__(self): import Carbon Carbon.Evt #see if it has this (in Unix, it doesn't) def __call__(self): import Carbon if Carbon.Evt.EventAvail(0x0008)[0]==0: # 0x0008 is the keyDownMask return '' else: # # The event contains the following info: # (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1] # # The message (msg) contains the ASCII char which is # extracted with the 0x000000FF charCodeMask; this # number is converted to an ASCII character with chr() and # returned # (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1] return chr(msg &amp; 0x000000FF) import threading # From http://stackoverflow.com/a/2022629/2924421 class Event(list): def __call__(self, *args, **kwargs): for f in self: f(*args, **kwargs) def __repr__(self): return "Event(%s)" % list.__repr__(self) def getKey(): inkey = _Getch() import sys for i in xrange(sys.maxint): k=inkey() if k&lt;&gt;'':break return k class KeyCallbackFunction(): callbackParam = None actualFunction = None def __init__(self, actualFunction, callbackParam): self.actualFunction = actualFunction self.callbackParam = callbackParam def doCallback(self, inputKey): if not self.actualFunction is None: if self.callbackParam is None: callbackFunctionThread = threading.Thread(target=self.actualFunction, args=(inputKey,)) else: callbackFunctionThread = threading.Thread(target=self.actualFunction, args=(inputKey,self.callbackParam)) callbackFunctionThread.daemon = True callbackFunctionThread.start() class KeyCapture(): gotKeyLock = threading.Lock() gotKeys = [] gotKeyEvent = threading.Event() keyBlockingSetKeyLock = threading.Lock() addingEventsLock = threading.Lock() keyReceiveEvents = Event() keysGotLock = threading.Lock() keysGot = [] keyBlockingKeyLockLossy = threading.Lock() keyBlockingKeyLossy = None keyBlockingEventLossy = threading.Event() keysBlockingGotLock = threading.Lock() keysBlockingGot = [] keyBlockingGotEvent = threading.Event() wantToStopLock = threading.Lock() wantToStop = False stoppedLock = threading.Lock() stopped = True isRunningEvent = False getKeyThread = None keyFunction = None keyArgs = None # Begin capturing keys. A seperate thread is launched that # captures key presses, and then these can be received via get, # getAsync, and adding an event via addEvent. Note that this # will prevent the system to accept keys as normal (say, if # you are in a python shell) because it overrides that key # capturing behavior. # If you start capture when it's already been started, a # InterruptedError("Keys are still being captured") # will be thrown # Note that get(), getAsync() and events are independent, so if a key is pressed: # # 1: Any calls to get() that are waiting, with lossy on, will return # that key # 2: It will be stored in the queue of get keys, so that get() with lossy # off will return the oldest key pressed not returned by get() yet. # 3: All events will be fired with that key as their input # 4: It will be stored in the list of getAsync() keys, where that list # will be returned and set to empty list on the next call to getAsync(). # get() call with it, aand add it to the getAsync() list. def startCapture(self, keyFunction=None, args=None): # Make sure we aren't already capturing keys self.stoppedLock.acquire() if not self.stopped: self.stoppedLock.release() raise InterruptedError("Keys are still being captured") return self.stopped = False self.stoppedLock.release() # If we have captured before, we need to allow the get() calls to actually # wait for key presses now by clearing the event if self.keyBlockingEventLossy.is_set(): self.keyBlockingEventLossy.clear() # Have one function that we call every time a key is captured, intended for stopping capture # as desired self.keyFunction = keyFunction self.keyArgs = args # Begin capturing keys (in a seperate thread) self.getKeyThread = threading.Thread(target=self._threadProcessKeyPresses) self.getKeyThread.daemon = True self.getKeyThread.start() # Process key captures (in a seperate thread) self.getKeyThread = threading.Thread(target=self._threadStoreKeyPresses) self.getKeyThread.daemon = True self.getKeyThread.start() def capturing(self): self.stoppedLock.acquire() isCapturing = not self.stopped self.stoppedLock.release() return isCapturing # Stops the thread that is capturing keys on the first opporunity # has to do so. It usually can't stop immediately because getting a key # is a blocking process, so this will probably stop capturing after the # next key is pressed. # # However, Sometimes if you call stopCapture it will stop before starting capturing the # next key, due to multithreading race conditions. So if you want to stop capturing # reliably, call stopCapture in a function added via addEvent. Then you are # guaranteed that capturing will stop immediately after the rest of the callback # functions are called (before starting to capture the next key). def stopCapture(self): self.wantToStopLock.acquire() self.wantToStop = True self.wantToStopLock.release() # Takes in a function that will be called every time a key is pressed (with that # key passed in as the first paramater in that function) def addEvent(self, keyPressEventFunction, args=None): self.addingEventsLock.acquire() callbackHolder = KeyCallbackFunction(keyPressEventFunction, args) self.keyReceiveEvents.append(callbackHolder.doCallback) self.addingEventsLock.release() def clearEvents(self): self.addingEventsLock.acquire() self.keyReceiveEvents = Event() self.addingEventsLock.release() # Gets a key captured by this KeyCapture, blocking until a key is pressed. # There is an optional lossy paramater: # If True all keys before this call are ignored, and the next pressed key # will be returned. # If False this will return the oldest key captured that hasn't # been returned by get yet. False is the default. def get(self, lossy=False): if lossy: # Wait for the next key to be pressed self.keyBlockingEventLossy.wait() self.keyBlockingKeyLockLossy.acquire() keyReceived = self.keyBlockingKeyLossy self.keyBlockingKeyLockLossy.release() return keyReceived else: while True: # Wait until a key is pressed self.keyBlockingGotEvent.wait() # Get the key pressed readKey = None self.keysBlockingGotLock.acquire() # Get a key if it exists if len(self.keysBlockingGot) != 0: readKey = self.keysBlockingGot.pop(0) # If we got the last one, tell us to wait if len(self.keysBlockingGot) == 0: self.keyBlockingGotEvent.clear() self.keysBlockingGotLock.release() # Process the key (if it actually exists) if not readKey is None: return readKey # Exit if we are stopping self.wantToStopLock.acquire() if self.wantToStop: self.wantToStopLock.release() return None self.wantToStopLock.release() def clearGetList(self): self.keysBlockingGotLock.acquire() self.keysBlockingGot = [] self.keysBlockingGotLock.release() # Gets a list of all keys pressed since the last call to getAsync, in order # from first pressed, second pressed, .., most recent pressed def getAsync(self): self.keysGotLock.acquire(); keysPressedList = list(self.keysGot) self.keysGot = [] self.keysGotLock.release() return keysPressedList def clearAsyncList(self): self.keysGotLock.acquire(); self.keysGot = [] self.keysGotLock.release(); def _processKey(self, readKey): # Append to list for GetKeyAsync self.keysGotLock.acquire() self.keysGot.append(readKey) self.keysGotLock.release() # Call lossy blocking key events self.keyBlockingKeyLockLossy.acquire() self.keyBlockingKeyLossy = readKey self.keyBlockingEventLossy.set() self.keyBlockingEventLossy.clear() self.keyBlockingKeyLockLossy.release() # Call non-lossy blocking key events self.keysBlockingGotLock.acquire() self.keysBlockingGot.append(readKey) if len(self.keysBlockingGot) == 1: self.keyBlockingGotEvent.set() self.keysBlockingGotLock.release() # Call events added by AddEvent self.addingEventsLock.acquire() self.keyReceiveEvents(readKey) self.addingEventsLock.release() def _threadProcessKeyPresses(self): while True: # Wait until a key is pressed self.gotKeyEvent.wait() # Get the key pressed readKey = None self.gotKeyLock.acquire() # Get a key if it exists if len(self.gotKeys) != 0: readKey = self.gotKeys.pop(0) # If we got the last one, tell us to wait if len(self.gotKeys) == 0: self.gotKeyEvent.clear() self.gotKeyLock.release() # Process the key (if it actually exists) if not readKey is None: self._processKey(readKey) # Exit if we are stopping self.wantToStopLock.acquire() if self.wantToStop: self.wantToStopLock.release() break self.wantToStopLock.release() def _threadStoreKeyPresses(self): while True: # Get a key readKey = getKey() # Run the potential shut down function if not self.keyFunction is None: self.keyFunction(readKey, self.keyArgs) # Add the key to the list of pressed keys self.gotKeyLock.acquire() self.gotKeys.append(readKey) if len(self.gotKeys) == 1: self.gotKeyEvent.set() self.gotKeyLock.release() # Exit if we are stopping self.wantToStopLock.acquire() if self.wantToStop: self.wantToStopLock.release() self.gotKeyEvent.set() break self.wantToStopLock.release() # If we have reached here we stopped capturing # All we need to do to clean up is ensure that # all the calls to .get() now return None. # To ensure no calls are stuck never returning, # we will leave the event set so any tasks waiting # for it immediately exit. This will be unset upon # starting key capturing again. self.stoppedLock.acquire() # We also need to set this to True so we can start up # capturing again. self.stopped = True self.stopped = True self.keyBlockingKeyLockLossy.acquire() self.keyBlockingKeyLossy = None self.keyBlockingEventLossy.set() self.keyBlockingKeyLockLossy.release() self.keysBlockingGotLock.acquire() self.keyBlockingGotEvent.set() self.keysBlockingGotLock.release() self.stoppedLock.release() </code></pre> <p>The idea is that you can either simply call <code>keyPress.getKey()</code>, which will read a key from the keyboard, then return it.</p> <p>If you want something more than that, I made a <code>KeyCapture</code> object. You can create one via something like <code>keys = keyPress.KeyCapture()</code>.</p> <p>Then there are three things you can do:</p> <p><code>addEvent(functionName)</code> takes in any function that takes in one parameter. Then every time a key is pressed, this function will be called with that key's string as it's input. These are ran in a separate thread, so you can block all you want in them and it won't mess up the functionality of the KeyCapturer nor delay the other events.</p> <p><code>get()</code> returns a key in the same blocking way as before. It is now needed here because the keys are being captured via the <code>KeyCapture</code> object now, so <code>keyPress.getKey()</code> would conflict with that behavior and both of them would miss some keys since only one key can be captured at a time. Also, say the user presses 'a', then 'b', you call <code>get()</code>, the the user presses 'c'. That <code>get()</code> call will immediately return 'a', then if you call it again it will return 'b', then 'c'. If you call it again it will block until another key is pressed. This ensures that you don't miss any keys, in a blocking way if desired. So in this way it's a little different than <code>keyPress.getKey()</code> from before</p> <p>If you want the behavior of <code>getKey()</code> back, <code>get(lossy=True)</code> is like <code>get()</code>, except that it only returns keys pressed <em>after</em> the call to <code>get()</code>. So in the above example, <code>get()</code> would block until the user presses 'c', and then if you call it again it will block until another key is pressed.</p> <p><code>getAsync()</code> is a little different. It's designed for something that does a lot of processing, then occasionally comes back and checks which keys were pressed. Thus <code>getAsync()</code> returns a list of all the keys pressed since the last call to <code>getAsync()</code>, in order from oldest key pressed to most recent key pressed. It also doesn't block, meaning that if no keys have been pressed since the last call to <code>getAsync()</code>, an empty <code>[]</code> will be returned.</p> <p>To actually start capturing keys, you need to call <code>keys.startCapture()</code> with your <code>keys</code> object made above. <code>startCapture</code> is non-blocking, and simply starts one thread that just records the key presses, and another thread to process those key presses. There are two threads to ensure that the thread that records key presses doesn't miss any keys.</p> <p>If you want to stop capturing keys, you can call <code>keys.stopCapture()</code> and it will stop capturing keys. However, since capturing a key is a blocking operation, the thread capturing keys might capture one more key after calling <code>stopCapture()</code>.</p> <p>To prevent this, you can pass in an optional parameter(s) into <code>startCapture(functionName, args)</code> of a function that just does something like checks if a key equals 'c' and then exits. It's important that this function does very little before, for example, a sleep here will cause us to miss keys.</p> <p>However, if <code>stopCapture()</code> is called in this function, key captures will be stopped immediately, without trying to capture any more, and that all <code>get()</code> calls will be returned immediately, with None if no keys have been pressed yet.</p> <p>Also, since <code>get()</code> and <code>getAsync()</code> store all the previous keys pressed (until you retrieve them), you can call <code>clearGetList()</code> and <code>clearAsyncList()</code> to forget the keys previously pressed.</p> <p>Note that <code>get()</code>, <code>getAsync()</code> and events are independent, so if a key is pressed: 1. One call to <code>get()</code> that is waiting, with lossy on, will return that key. The other waiting calls (if any) will continue waiting. 2. That key will be stored in the queue of get keys, so that <code>get()</code> with lossy off will return the oldest key pressed not returned by <code>get()</code> yet. 3. All events will be fired with that key as their input 4. That key will be stored in the list of <code>getAsync()</code> keys, where that lis twill be returned and set to empty list on the next call to <code>getAsync()</code></p> <p>If all this is too much, here is an example use case:</p> <pre><code>import keyPress import time import threading def KeyPressed(k, printLock): printLock.acquire() print "Event: " + k printLock.release() time.sleep(4) printLock.acquire() print "Event after delay: " + k printLock.release() def GetKeyBlocking(keys, printLock): while keys.capturing(): keyReceived = keys.get() time.sleep(1) printLock.acquire() if not keyReceived is None: print "Block " + keyReceived else: print "Block None" printLock.release() def GetKeyBlockingLossy(keys, printLock): while keys.capturing(): keyReceived = keys.get(lossy=True) time.sleep(1) printLock.acquire() if not keyReceived is None: print "Lossy: " + keyReceived else: print "Lossy: None" printLock.release() def CheckToClose(k, (keys, printLock)): printLock.acquire() print "Close: " + k printLock.release() if k == "c": keys.stopCapture() printLock = threading.Lock() print "Press a key:" print "You pressed: " + keyPress.getKey() print "" keys = keyPress.KeyCapture() keys.addEvent(KeyPressed, printLock) print "Starting capture" keys.startCapture(CheckToClose, (keys, printLock)) getKeyBlockingThread = threading.Thread(target=GetKeyBlocking, args=(keys, printLock)) getKeyBlockingThread.daemon = True getKeyBlockingThread.start() getKeyBlockingThreadLossy = threading.Thread(target=GetKeyBlockingLossy, args=(keys, printLock)) getKeyBlockingThreadLossy.daemon = True getKeyBlockingThreadLossy.start() while keys.capturing(): keysPressed = keys.getAsync() printLock.acquire() if keysPressed != []: print "Async: " + str(keysPressed) printLock.release() time.sleep(1) print "done capturing" </code></pre> <p>It is working well for me from the simple test I made, but I will happily take others feedback as well if there is something I missed.</p> <p>I posted this <a href="http://stackoverflow.com/a/31736883/2924421">here</a> as well.</p>
4
2015-07-31T15:17:50Z
[ "python", "input" ]
Python read a single character from the user
510,357
<p>Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like <code>getch()</code>). I know there's a function in Windows for it, but I'd like something that is cross-platform.</p>
157
2009-02-04T07:08:03Z
34,299,151
<p>The build-in raw_input should help. </p> <pre><code>for i in range(3): print ("So much work to do!") k = raw_input("Press any key to continue...") print ("Ok, back to work.") </code></pre>
1
2015-12-15T20:51:36Z
[ "python", "input" ]
Python read a single character from the user
510,357
<p>Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like <code>getch()</code>). I know there's a function in Windows for it, but I'd like something that is cross-platform.</p>
157
2009-02-04T07:08:03Z
35,051,309
<p>My solution for python3, not depending on any pip packages.</p> <pre><code># precondition: import tty, sys def query_yes_no(question, default=True): """ Ask the user a yes/no question. Returns immediately upon reading one-char answer. Accepts multiple language characters for yes/no. """ if not sys.stdin.isatty(): return default if default: prompt = "[Y/n]?" other_answers = "n" else: prompt = "[y/N]?" other_answers = "yjosiá" print(question,prompt,flush= True,end=" ") oldttysettings = tty.tcgetattr(sys.stdin.fileno()) try: tty.setraw(sys.stdin.fileno()) return not sys.stdin.read(1).lower() in other_answers except: return default finally: tty.tcsetattr(sys.stdin.fileno(), tty.TCSADRAIN , oldttysettings) sys.stdout.write("\r\n") tty.tcdrain(sys.stdin.fileno()) </code></pre>
0
2016-01-28T01:24:52Z
[ "python", "input" ]
Python read a single character from the user
510,357
<p>Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like <code>getch()</code>). I know there's a function in Windows for it, but I'd like something that is cross-platform.</p>
157
2009-02-04T07:08:03Z
36,974,338
<p>The (currently) top-ranked answer (with the ActiveState code) is overly complicated. I don't see a reason to use classes when a mere function should suffice. Below are two implementations that accomplish the same thing but with more readable code.</p> <p><strong>Both of these implementations:</strong></p> <ol> <li>work just fine in Python 2 or Python 3</li> <li>work on Windows, OSX, and Linux</li> <li>read just one byte (i.e., they don't wait for a newline)</li> <li>don't depend on any external libraries</li> <li>are self-contained (no code outside of the function definition)</li> </ol> <p><strong>Version 1: readable and simple</strong></p> <pre class="lang-python prettyprint-override"><code>def getChar(): try: # for Windows-based systems import msvcrt # If successful, we are on Windows return msvcrt.getch() except ImportError: # for POSIX-based systems (with termios &amp; tty support) import tty, sys, termios # raises ImportError if unsupported fd = sys.stdin.fileno() oldSettings = termios.tcgetattr(fd) try: tty.setraw(fd) answer = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, oldSettings) return answer </code></pre> <p><strong>Version 2: avoid repeated imports and exception handling:</strong></p> <p><strong>[EDIT]</strong> I missed one advantage of the ActiveState code. If you plan to read characters multiple times, that code avoids the (negligible) cost of repeating the Windows import and the ImportError exception handling on Unix-like systems. While you probably should be more concerned about code readability than that negligible optimization, here is an alternative (it is similar to Louis's answer, but getChar() is self-contained) that functions the same as the ActiveState code and is more readable:</p> <pre class="lang-python prettyprint-override"><code>def getChar(): # figure out which function to use once, and store it in _func if "_func" not in getChar.__dict__: try: # for Windows-based systems import msvcrt # If successful, we are on Windows getChar._func=msvcrt.getch() except ImportError: # for POSIX-based systems (with termios &amp; tty support) import tty, sys, termios # raises ImportError if unsupported def _ttyRead(): fd = sys.stdin.fileno() oldSettings = termios.tcgetattr(fd) try: tty.setraw(fd) answer = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, oldSettings) return answer getChar._func=_ttyRead return getChar._func() </code></pre> <p><strong>Example code that exercises either of the getChar() versions above:</strong></p> <pre class="lang-python prettyprint-override"><code>from __future__ import print_function # put at top of file if using Python 2 # Example of a prompt for one character of input promptStr = "Please give me a character:" responseStr = "Thank you for giving me a '{}'." print(promptStr, end="\n&gt; ") answer = getChar() print("\n") print(responseStr.format(answer)) </code></pre>
2
2016-05-02T02:49:47Z
[ "python", "input" ]
Is there a way to get the current ref count of an object in Python?
510,406
<p>Is there a way to get the current ref count of an object in Python?</p>
34
2009-02-04T07:32:51Z
510,411
<p>Using the <code>gc</code> module, the interface to the garbage collector guts, you can call <code>gc.get_referrers(foo)</code> to get a list of everything referring to <code>foo</code>.</p> <p>Hence, <code>len(gc.get_referrers(foo))</code> will give you the length of that list: the number of referrers, which is what you're after.</p> <p>See also the <a href="http://docs.python.org/library/gc.html"><code>gc</code> module documentation</a>.</p>
36
2009-02-04T07:36:25Z
[ "python", "refcounting" ]
Is there a way to get the current ref count of an object in Python?
510,406
<p>Is there a way to get the current ref count of an object in Python?</p>
34
2009-02-04T07:32:51Z
510,417
<p>According to some Python 2.0 reference (<a href="http://www.brunningonline.net/simon/python/quick-ref2_0.html">http://www.brunningonline.net/simon/python/quick-ref2_0.html</a>), the sys module contains a function:</p> <pre><code>import sys sys.getrefcount(object) #-- Returns the reference count of the object. </code></pre> <p>Generally 1 higher than you might expect, because of object arg temp reference. </p>
41
2009-02-04T07:39:03Z
[ "python", "refcounting" ]
Using Python Ctypes for ssdeep's fuzzy.dll but receive error
510,443
<p>I am trying to use Python and ctypes to use the <code>fuzzy.dll</code> from ssdeep. So far everything I have tried fails with an access violation error. Here is what I do after changing to the proper directory which contains the <code>fuzzy.dll</code> and <code>fuzzy.def</code> files:</p> <pre><code>&gt;&gt;&gt; import os,sys &gt;&gt;&gt; from ctypes import * &gt;&gt;&gt; fn = create_string_buffer(os.path.abspath("fuzzy.def")) &gt;&gt;&gt; fuzz = windll.fuzzy &gt;&gt;&gt; chash = c_char_p(512) &gt;&gt;&gt; hstat = fuzz.fuzzy_hash_filename(fn,chash) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; WindowsError: exception: access violation writing 0x00000200 &gt;&gt;&gt; </code></pre> <p>From what I understand, I have passed the proper <code>c_types</code>. From <code>fuzzy.h</code>:</p> <pre><code>extern int fuzzy_hash_filename(char * filename, char * result) </code></pre> <p>I just cannot get past that access violation.</p>
2
2009-02-04T07:52:50Z
511,749
<p>There are two problems with your code:</p> <ol> <li><p>You should not use <code>windll.fuzzy</code>, but <code>cdll.fuzzy</code> -- from <a href="http://docs.python.org/library/ctypes.html#loading-dynamic-link-libraries" rel="nofollow">ctypes documentation</a>:</p> <blockquote> <p>cdll loads libraries which export functions using the standard cdecl calling convention, while windll libraries call functions using the stdcall calling convention.</p> </blockquote></li> <li><p>For return value (<code>chash</code>), you should declare a buffer rather than creating a pointer to <code>0x0000200</code> (=512) -- this is where the access violation comes from. Use <code>create_string_buffer('\000' * 512)</code> instead.</p></li> </ol> <p>So your example should look like this:</p> <pre><code>&gt;&gt;&gt; import os, sys &gt;&gt;&gt; from ctypes import * &gt;&gt;&gt; fn = create_string_buffer(os.path.abspath("fuzzy.def")) &gt;&gt;&gt; fuzz = cdll.fuzzy &gt;&gt;&gt; chash = create_string_buffer('\000' * 512) &gt;&gt;&gt; hstat = fuzz.fuzzy_hash_filename(fn,chash) &gt;&gt;&gt; print hstat 0 # == success </code></pre>
4
2009-02-04T15:09:27Z
[ "python", "ctypes" ]
Spawn subprocess that expects console input without blocking?
510,751
<p>I am trying to do a CVS login from Python by calling the cvs.exe process. When calling cvs.exe by hand, it prints a message to the console and then waits for the user to input the password. </p> <p>When calling it with subprocess.Popen, I've noticed that the call blocks. The code is </p> <pre><code>subprocess.Popen(cvscmd, shell = True, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE) </code></pre> <p>I assume that it blocks because it's waiting for input, but my expectation was that calling Popen would return immediately and then I could call subprocess.communicate() to input the actual password. How can I achieve this behaviour and avoid blocking on Popen?</p> <p>OS: Windows XP<br /> Python: 2.6<br /> cvs.exe: 1.11</p>
4
2009-02-04T10:07:18Z
510,889
<ul> <li>Remove the <code>shell=True</code> part. Your shell has nothing to do with it. Using <code>shell=True</code> is a common cause of trouble.</li> <li>Use a list of parameters for cmd.</li> </ul> <p>Example:</p> <pre><code>cmd = ['cvs', '-d:pserver:anonymous@bayonne.cvs.sourceforge.net:/cvsroot/bayonne', 'login'] p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE) </code></pre> <p>This won't block on my system (my script continues executing). However since cvs reads the password directly from the terminal (not from standard input or output) you <strong>can't</strong> just write the password to the subprocess' stdin.</p> <p>What you could do is pass the password as part of the CVSROOT specification instead, like this:</p> <pre><code>:pserver:&lt;user&gt;[:&lt;passwd&gt;]@&lt;server&gt;:/&lt;path&gt; </code></pre> <p>I.e. a function to login to a sourceforge project:</p> <pre><code>import subprocess def login_to_sourceforge_cvs(project, username='anonymous', password=''): host = '%s.cvs.sourceforge.net' % project path = '/cvsroot/%s' % project cmd = ['cvs', '-d:pserver:%s:%s@%s:%s' % (username, password, host, path), 'login'] p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE stderr=subprocess.STDOUT) return p </code></pre> <p>This works for me. Calling</p> <pre><code>login_to_sourceforge_cvs('bayonne') </code></pre> <p>Will log in anonymously to the bayonne project's cvs.</p>
2
2009-02-04T11:00:35Z
[ "python", "windows", "subprocess" ]
Spawn subprocess that expects console input without blocking?
510,751
<p>I am trying to do a CVS login from Python by calling the cvs.exe process. When calling cvs.exe by hand, it prints a message to the console and then waits for the user to input the password. </p> <p>When calling it with subprocess.Popen, I've noticed that the call blocks. The code is </p> <pre><code>subprocess.Popen(cvscmd, shell = True, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE) </code></pre> <p>I assume that it blocks because it's waiting for input, but my expectation was that calling Popen would return immediately and then I could call subprocess.communicate() to input the actual password. How can I achieve this behaviour and avoid blocking on Popen?</p> <p>OS: Windows XP<br /> Python: 2.6<br /> cvs.exe: 1.11</p>
4
2009-02-04T10:07:18Z
513,521
<p>If you are automating external programs that need input - like password - your best bet would probably be to use <a href="http://www.noah.org/wiki/Pexpect" rel="nofollow">pexpect</a>.</p>
0
2009-02-04T21:50:13Z
[ "python", "windows", "subprocess" ]
How to write a functional test for a DBUS service written in Python?
510,821
<p>(Title was: "How to write a unit test for a DBUS service written in Python?")</p> <p>I've started to write a DBUS service using dbus-python, but I'm having trouble writing a test case for it.</p> <p>Here is an example of the test I am trying to create. Notice that I have put a GLib event loop in the setUp(), this is where the problem hits:</p> <pre><code>import unittest import gobject import dbus import dbus.service import dbus.glib class MyDBUSService(dbus.service.Object): def __init__(self): bus_name = dbus.service.BusName('test.helloservice', bus = dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, '/test/helloservice') @dbus.service.method('test.helloservice') def hello(self): return "Hello World!" class BaseTestCase(unittest.TestCase): def setUp(self): myservice = MyDBUSService() loop = gobject.MainLoop() loop.run() # === Test blocks here === def testHelloService(self): bus = dbus.SessionBus() helloservice = bus.get_object('test.helloservice', '/test/helloservice') hello = helloservice.get_dbus_method('hello', 'test.helloservice') assert hello() == "Hello World!" if __name__ == '__main__': unittest.main() </code></pre> <p>My problem is that the DBUS implementation requires you to start an event loop so that it can start dispatching events. The common approach is to use GLib's gobject.MainLoop().start() (although I'm not married to this approach, if someone has a better suggestion). If you don't start an event loop, the service still blocks, and you also cannot query it.</p> <p>If I start my service in the test, the event loop blocks the test from completing. I know the service is working because I can query the service externally using the qdbus tool, but I can't automate this inside the test that starts it.</p> <p>I'm considering doing some kind of process forking inside the test to handle this, but I was hoping someone might have a neater solution, or at least a good starting place for how I would write a test like this.</p>
12
2009-02-04T10:29:14Z
510,858
<p>Simple solution: don't unit test through dbus.</p> <p>Instead write your unit tests to call your methods directly. That fits in more naturally with the nature of unit tests.</p> <p>You might also want some automated integration tests, that check running through dbus, but they don't need to be so complete, nor run in isolation. You can have setup that starts a real instance of your server, in a separate process.</p>
3
2009-02-04T10:52:45Z
[ "python", "unit-testing", "dbus" ]
How to write a functional test for a DBUS service written in Python?
510,821
<p>(Title was: "How to write a unit test for a DBUS service written in Python?")</p> <p>I've started to write a DBUS service using dbus-python, but I'm having trouble writing a test case for it.</p> <p>Here is an example of the test I am trying to create. Notice that I have put a GLib event loop in the setUp(), this is where the problem hits:</p> <pre><code>import unittest import gobject import dbus import dbus.service import dbus.glib class MyDBUSService(dbus.service.Object): def __init__(self): bus_name = dbus.service.BusName('test.helloservice', bus = dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, '/test/helloservice') @dbus.service.method('test.helloservice') def hello(self): return "Hello World!" class BaseTestCase(unittest.TestCase): def setUp(self): myservice = MyDBUSService() loop = gobject.MainLoop() loop.run() # === Test blocks here === def testHelloService(self): bus = dbus.SessionBus() helloservice = bus.get_object('test.helloservice', '/test/helloservice') hello = helloservice.get_dbus_method('hello', 'test.helloservice') assert hello() == "Hello World!" if __name__ == '__main__': unittest.main() </code></pre> <p>My problem is that the DBUS implementation requires you to start an event loop so that it can start dispatching events. The common approach is to use GLib's gobject.MainLoop().start() (although I'm not married to this approach, if someone has a better suggestion). If you don't start an event loop, the service still blocks, and you also cannot query it.</p> <p>If I start my service in the test, the event loop blocks the test from completing. I know the service is working because I can query the service externally using the qdbus tool, but I can't automate this inside the test that starts it.</p> <p>I'm considering doing some kind of process forking inside the test to handle this, but I was hoping someone might have a neater solution, or at least a good starting place for how I would write a test like this.</p>
12
2009-02-04T10:29:14Z
510,910
<p>I might be a bit out of my league here, since I don't know python and only somewhat understand what this magical "dbus" is, but if I understand correctly, it requires you to create a rather unusual testing environment with runloops, extended setup/teardown, and so on.</p> <p>The answer to your problem is to use <a href="http://en.wikipedia.org/wiki/Mock_object" rel="nofollow">mocking</a>. Create an abstract class which defines your interface, and then build an object from that to use in your actual code. For the purposes of testing, you build a mock object communicates through that same interface, but has behavior which <em>you</em> would define for the purposes of testing. You can use this approach to "simulate" the dbus object running through an event loop, doing some work, etc., and then simply concentrate on testing how your class ought to react to the result of the "work" done by that object.</p>
2
2009-02-04T11:10:34Z
[ "python", "unit-testing", "dbus" ]
How to write a functional test for a DBUS service written in Python?
510,821
<p>(Title was: "How to write a unit test for a DBUS service written in Python?")</p> <p>I've started to write a DBUS service using dbus-python, but I'm having trouble writing a test case for it.</p> <p>Here is an example of the test I am trying to create. Notice that I have put a GLib event loop in the setUp(), this is where the problem hits:</p> <pre><code>import unittest import gobject import dbus import dbus.service import dbus.glib class MyDBUSService(dbus.service.Object): def __init__(self): bus_name = dbus.service.BusName('test.helloservice', bus = dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, '/test/helloservice') @dbus.service.method('test.helloservice') def hello(self): return "Hello World!" class BaseTestCase(unittest.TestCase): def setUp(self): myservice = MyDBUSService() loop = gobject.MainLoop() loop.run() # === Test blocks here === def testHelloService(self): bus = dbus.SessionBus() helloservice = bus.get_object('test.helloservice', '/test/helloservice') hello = helloservice.get_dbus_method('hello', 'test.helloservice') assert hello() == "Hello World!" if __name__ == '__main__': unittest.main() </code></pre> <p>My problem is that the DBUS implementation requires you to start an event loop so that it can start dispatching events. The common approach is to use GLib's gobject.MainLoop().start() (although I'm not married to this approach, if someone has a better suggestion). If you don't start an event loop, the service still blocks, and you also cannot query it.</p> <p>If I start my service in the test, the event loop blocks the test from completing. I know the service is working because I can query the service externally using the qdbus tool, but I can't automate this inside the test that starts it.</p> <p>I'm considering doing some kind of process forking inside the test to handle this, but I was hoping someone might have a neater solution, or at least a good starting place for how I would write a test like this.</p>
12
2009-02-04T10:29:14Z
511,168
<p>You just need to make sure you are handling your main loop properly.</p> <pre><code>def refresh_ui(): while gtk.events_pending(): gtk.main_iteration_do(False) </code></pre> <p>This will run the gtk main loop until it has finished processing everything, rather than just run it and block.</p> <p>For a complete example of it in practise, unit testing a dbus interface, go here: <a href="http://pida.co.uk/trac/browser/pida/editors/vim/test_pidavim.py" rel="nofollow">http://pida.co.uk/trac/browser/pida/editors/vim/test_pidavim.py</a></p>
2
2009-02-04T12:36:02Z
[ "python", "unit-testing", "dbus" ]
How to write a functional test for a DBUS service written in Python?
510,821
<p>(Title was: "How to write a unit test for a DBUS service written in Python?")</p> <p>I've started to write a DBUS service using dbus-python, but I'm having trouble writing a test case for it.</p> <p>Here is an example of the test I am trying to create. Notice that I have put a GLib event loop in the setUp(), this is where the problem hits:</p> <pre><code>import unittest import gobject import dbus import dbus.service import dbus.glib class MyDBUSService(dbus.service.Object): def __init__(self): bus_name = dbus.service.BusName('test.helloservice', bus = dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, '/test/helloservice') @dbus.service.method('test.helloservice') def hello(self): return "Hello World!" class BaseTestCase(unittest.TestCase): def setUp(self): myservice = MyDBUSService() loop = gobject.MainLoop() loop.run() # === Test blocks here === def testHelloService(self): bus = dbus.SessionBus() helloservice = bus.get_object('test.helloservice', '/test/helloservice') hello = helloservice.get_dbus_method('hello', 'test.helloservice') assert hello() == "Hello World!" if __name__ == '__main__': unittest.main() </code></pre> <p>My problem is that the DBUS implementation requires you to start an event loop so that it can start dispatching events. The common approach is to use GLib's gobject.MainLoop().start() (although I'm not married to this approach, if someone has a better suggestion). If you don't start an event loop, the service still blocks, and you also cannot query it.</p> <p>If I start my service in the test, the event loop blocks the test from completing. I know the service is working because I can query the service externally using the qdbus tool, but I can't automate this inside the test that starts it.</p> <p>I'm considering doing some kind of process forking inside the test to handle this, but I was hoping someone might have a neater solution, or at least a good starting place for how I would write a test like this.</p>
12
2009-02-04T10:29:14Z
512,723
<p>With some help from Ali A's post, I have managed to solve my problem. The blocking event loop needed to be launched into a separate process, so that it can listen for events without blocking the test.</p> <p>Please be aware my question title contained some incorrect terminology, I was trying to write a functional test, as opposed to a unit test. I was aware of the distinction, but didn't realise my mistake until later.</p> <p>I've adjusted the example in my question. It loosely resembles the "test_pidavim.py" example, but uses an import for "dbus.glib" to handle the glib loop dependencies instead of coding in all the DBusGMainLoop stuff:</p> <pre><code>import unittest import os import sys import subprocess import time import dbus import dbus.service import dbus.glib import gobject class MyDBUSService(dbus.service.Object): def __init__(self): bus_name = dbus.service.BusName('test.helloservice', bus = dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, '/test/helloservice') def listen(self): loop = gobject.MainLoop() loop.run() @dbus.service.method('test.helloservice') def hello(self): return "Hello World!" class BaseTestCase(unittest.TestCase): def setUp(self): env = os.environ.copy() self.p = subprocess.Popen(['python', './dbus_practice.py', 'server'], env=env) # Wait for the service to become available time.sleep(1) assert self.p.stdout == None assert self.p.stderr == None def testHelloService(self): bus = dbus.SessionBus() helloservice = bus.get_object('test.helloservice', '/test/helloservice') hello = helloservice.get_dbus_method('hello', 'test.helloservice') assert hello() == "Hello World!" def tearDown(self): # terminate() not supported in Python 2.5 #self.p.terminate() os.kill(self.p.pid, 15) if __name__ == '__main__': arg = "" if len(sys.argv) &gt; 1: arg = sys.argv[1] if arg == "server": myservice = MyDBUSService() myservice.listen() else: unittest.main() </code></pre>
6
2009-02-04T18:46:09Z
[ "python", "unit-testing", "dbus" ]
How to write a functional test for a DBUS service written in Python?
510,821
<p>(Title was: "How to write a unit test for a DBUS service written in Python?")</p> <p>I've started to write a DBUS service using dbus-python, but I'm having trouble writing a test case for it.</p> <p>Here is an example of the test I am trying to create. Notice that I have put a GLib event loop in the setUp(), this is where the problem hits:</p> <pre><code>import unittest import gobject import dbus import dbus.service import dbus.glib class MyDBUSService(dbus.service.Object): def __init__(self): bus_name = dbus.service.BusName('test.helloservice', bus = dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, '/test/helloservice') @dbus.service.method('test.helloservice') def hello(self): return "Hello World!" class BaseTestCase(unittest.TestCase): def setUp(self): myservice = MyDBUSService() loop = gobject.MainLoop() loop.run() # === Test blocks here === def testHelloService(self): bus = dbus.SessionBus() helloservice = bus.get_object('test.helloservice', '/test/helloservice') hello = helloservice.get_dbus_method('hello', 'test.helloservice') assert hello() == "Hello World!" if __name__ == '__main__': unittest.main() </code></pre> <p>My problem is that the DBUS implementation requires you to start an event loop so that it can start dispatching events. The common approach is to use GLib's gobject.MainLoop().start() (although I'm not married to this approach, if someone has a better suggestion). If you don't start an event loop, the service still blocks, and you also cannot query it.</p> <p>If I start my service in the test, the event loop blocks the test from completing. I know the service is working because I can query the service externally using the qdbus tool, but I can't automate this inside the test that starts it.</p> <p>I'm considering doing some kind of process forking inside the test to handle this, but I was hoping someone might have a neater solution, or at least a good starting place for how I would write a test like this.</p>
12
2009-02-04T10:29:14Z
762,079
<p>You could also start the mainloop in a separate thread very simply inside your setUp method.</p> <p>Something like this:</p> <pre><code>import threading class BaseTestCase(unittest.TestCase): def setUp(self): myservice = MyDBUSService() self.loop = gobject.MainLoop() threading.Thread(name='glib mainloop', target=self.loop.run) def tearDown(self): self.loop.quit() </code></pre>
2
2009-04-17T20:27:17Z
[ "python", "unit-testing", "dbus" ]
How to write a functional test for a DBUS service written in Python?
510,821
<p>(Title was: "How to write a unit test for a DBUS service written in Python?")</p> <p>I've started to write a DBUS service using dbus-python, but I'm having trouble writing a test case for it.</p> <p>Here is an example of the test I am trying to create. Notice that I have put a GLib event loop in the setUp(), this is where the problem hits:</p> <pre><code>import unittest import gobject import dbus import dbus.service import dbus.glib class MyDBUSService(dbus.service.Object): def __init__(self): bus_name = dbus.service.BusName('test.helloservice', bus = dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, '/test/helloservice') @dbus.service.method('test.helloservice') def hello(self): return "Hello World!" class BaseTestCase(unittest.TestCase): def setUp(self): myservice = MyDBUSService() loop = gobject.MainLoop() loop.run() # === Test blocks here === def testHelloService(self): bus = dbus.SessionBus() helloservice = bus.get_object('test.helloservice', '/test/helloservice') hello = helloservice.get_dbus_method('hello', 'test.helloservice') assert hello() == "Hello World!" if __name__ == '__main__': unittest.main() </code></pre> <p>My problem is that the DBUS implementation requires you to start an event loop so that it can start dispatching events. The common approach is to use GLib's gobject.MainLoop().start() (although I'm not married to this approach, if someone has a better suggestion). If you don't start an event loop, the service still blocks, and you also cannot query it.</p> <p>If I start my service in the test, the event loop blocks the test from completing. I know the service is working because I can query the service externally using the qdbus tool, but I can't automate this inside the test that starts it.</p> <p>I'm considering doing some kind of process forking inside the test to handle this, but I was hoping someone might have a neater solution, or at least a good starting place for how I would write a test like this.</p>
12
2009-02-04T10:29:14Z
19,105,422
<p>Check out <a href="https://pypi.python.org/pypi/python-dbusmock/0.7.2" rel="nofollow">python-dbusmock</a> library.</p> <p>It hides the ugly subprocess logic behind your eyes, so you don't have to worry about it in your tests.</p>
0
2013-09-30T23:13:35Z
[ "python", "unit-testing", "dbus" ]
Getting the class name of an instance in Python
510,972
<p>How do I find out a name of class that created an instance of an object in Python if the function I am doing this from is the base class of which the class of the instance has been derived?</p> <p>Was thinking maybe <a href="https://docs.python.org/2/library/inspect.html">the inspect module</a> might have helped me out here, but it doesn't seem to give me what I want. And short of parsing the <code>__class__</code> member, I'm not sure how to get at this information.</p>
689
2009-02-04T11:37:48Z
510,988
<p>type() ?</p> <pre><code>&gt;&gt;&gt; class A(object): ... def whoami(self): ... print type(self).__name__ ... &gt;&gt;&gt; &gt;&gt;&gt; class B(A): ... pass ... &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; o = B() &gt;&gt;&gt; o.whoami() 'B' &gt;&gt;&gt; </code></pre>
52
2009-02-04T11:42:31Z
[ "python", "introspection", "instanceof", "python-datamodel" ]
Getting the class name of an instance in Python
510,972
<p>How do I find out a name of class that created an instance of an object in Python if the function I am doing this from is the base class of which the class of the instance has been derived?</p> <p>Was thinking maybe <a href="https://docs.python.org/2/library/inspect.html">the inspect module</a> might have helped me out here, but it doesn't seem to give me what I want. And short of parsing the <code>__class__</code> member, I'm not sure how to get at this information.</p>
689
2009-02-04T11:37:48Z
511,059
<p>Have you tried the <code>__name__</code> attribute of the class? ie <code>type(x).__name__</code> will give you the name of the class, which I think is what you want.</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; x = itertools.count(0) &gt;&gt;&gt; type(x).__name__ 'count' </code></pre> <p>This method works with <a href="https://wiki.python.org/moin/NewClassVsClassicClass">new-style classes</a> only. Your code might use some old-style classes. The following works for both:</p> <pre><code>x.__class__.__name__ </code></pre>
948
2009-02-04T12:02:12Z
[ "python", "introspection", "instanceof", "python-datamodel" ]
Getting the class name of an instance in Python
510,972
<p>How do I find out a name of class that created an instance of an object in Python if the function I am doing this from is the base class of which the class of the instance has been derived?</p> <p>Was thinking maybe <a href="https://docs.python.org/2/library/inspect.html">the inspect module</a> might have helped me out here, but it doesn't seem to give me what I want. And short of parsing the <code>__class__</code> member, I'm not sure how to get at this information.</p>
689
2009-02-04T11:37:48Z
511,060
<p>Do you want the name of the class as a string?</p> <pre><code>instance.__class__.__name__ </code></pre>
177
2009-02-04T12:02:16Z
[ "python", "introspection", "instanceof", "python-datamodel" ]
Getting the class name of an instance in Python
510,972
<p>How do I find out a name of class that created an instance of an object in Python if the function I am doing this from is the base class of which the class of the instance has been derived?</p> <p>Was thinking maybe <a href="https://docs.python.org/2/library/inspect.html">the inspect module</a> might have helped me out here, but it doesn't seem to give me what I want. And short of parsing the <code>__class__</code> member, I'm not sure how to get at this information.</p>
689
2009-02-04T11:37:48Z
9,383,568
<p>Good question.</p> <p>Here's a simple example based on GHZ's which might help someone:</p> <pre><code>&gt;&gt;&gt; class person(object): def init(self,name): self.name=name def info(self) print "My name is {0}, I am a {1}".format(self.name,self.__class__.__name__) &gt;&gt;&gt; bob = person(name='Robert') &gt;&gt;&gt; bob.info() My name is Robert, I am a person </code></pre>
9
2012-02-21T19:07:40Z
[ "python", "introspection", "instanceof", "python-datamodel" ]
Getting the class name of an instance in Python
510,972
<p>How do I find out a name of class that created an instance of an object in Python if the function I am doing this from is the base class of which the class of the instance has been derived?</p> <p>Was thinking maybe <a href="https://docs.python.org/2/library/inspect.html">the inspect module</a> might have helped me out here, but it doesn't seem to give me what I want. And short of parsing the <code>__class__</code> member, I'm not sure how to get at this information.</p>
689
2009-02-04T11:37:48Z
16,293,038
<pre><code>type(instance).__name__ != instance.__class__.__name #if class A is defined like class A(): ... type(instance) == instance.__class__ #if class A is defined like class A(object): ... </code></pre> <p>Example:</p> <pre><code>&gt;&gt;&gt; class aclass(object): ... pass ... &gt;&gt;&gt; a = aclass() &gt;&gt;&gt; type(a) &lt;class '__main__.aclass'&gt; &gt;&gt;&gt; a.__class__ &lt;class '__main__.aclass'&gt; &gt;&gt;&gt; &gt;&gt;&gt; type(a).__name__ 'aclass' &gt;&gt;&gt; &gt;&gt;&gt; a.__class__.__name__ 'aclass' &gt;&gt;&gt; &gt;&gt;&gt; class bclass(): ... pass ... &gt;&gt;&gt; b = bclass() &gt;&gt;&gt; &gt;&gt;&gt; type(b) &lt;type 'instance'&gt; &gt;&gt;&gt; b.__class__ &lt;class __main__.bclass at 0xb765047c&gt; &gt;&gt;&gt; type(b).__name__ 'instance' &gt;&gt;&gt; &gt;&gt;&gt; b.__class__.__name__ 'bclass' &gt;&gt;&gt; </code></pre>
16
2013-04-30T05:50:38Z
[ "python", "introspection", "instanceof", "python-datamodel" ]
Getting the class name of an instance in Python
510,972
<p>How do I find out a name of class that created an instance of an object in Python if the function I am doing this from is the base class of which the class of the instance has been derived?</p> <p>Was thinking maybe <a href="https://docs.python.org/2/library/inspect.html">the inspect module</a> might have helped me out here, but it doesn't seem to give me what I want. And short of parsing the <code>__class__</code> member, I'm not sure how to get at this information.</p>
689
2009-02-04T11:37:48Z
24,130,402
<pre><code>class A: pass a = A() str(a.__class__) </code></pre> <p>The sample code above (when input in the interactive interpreter) will produce <code>'__main__.A'</code> as opposed to <code>'A'</code> which is produced if the <code>__name__</code> attribute is invoked. By simply passing the result of <code>A.__class__</code> to the <code>str</code> constructor the parsing is handled for you. However, you could also use the following code if you want something more explicit.</p> <pre><code>"{0}.{1}".format(a.__class__.__module__,a.__class__.__name__) </code></pre> <p>This behavior can be preferable if you have classes with the same name defined in separate modules.</p> <p><strong>The sample code provided above was tested in Python 2.7.5.</strong></p>
12
2014-06-09T23:04:17Z
[ "python", "introspection", "instanceof", "python-datamodel" ]
How can I tell python which version of libmysqlclient.so to use?
511,011
<p>I'm running a python script on a shared hosting server which until this morning had MySQL version 4. Now it has version 5. My python script can no longer connect to MySQL, as it can't find libmysqlclient_r.so.14:</p> <pre><code>$ python my_script.py Traceback (most recent call last): File "my_script.py", line 6, in ? import MySQLdb File "/home/lib/python2.4/site-packages/PIL-1.1.6-py2.4-linux-i686.egg/__init__.py", line 19, in ? File "build/bdist.linux-i686/egg/_mysql.py", line 7, in ? File "build/bdist.linux-i686/egg/_mysql.py", line 6, in __bootstrap__ ImportError: libmysqlclient_r.so.14: cannot open shared object file: No such file or directory </code></pre> <p>There are various other versions of libmysqlclient in /usr/lib:</p> <pre><code>/usr/lib/libmysqlclient.so.15 /usr/lib/libmysqlclient.so.14 /usr/lib/mysql/libmysqlclient.la /usr/lib/mysql/libmysqlclient.so /usr/lib/mysql/libmysqlclient_r.so /usr/lib/mysql/libmysqlclient_r.a /usr/lib/mysql/libmysqlclient_r.la /usr/lib/mysql/libmysqlclient.a /usr/lib/libmysqlclient.so /usr/lib/libmysqlclient_r.so /usr/lib/libmysqlclient_r.so.15 /usr/lib/libmysqlclient_r.so.15.0.0 /usr/lib/libmysqlclient.so.15.0.0 </code></pre> <p>So my question is this: how can I tell python (version 2.4.3) which version of libmysqlclient to use?</p>
2
2009-02-04T11:48:54Z
511,045
<p>One solution is to set your <code>PYTHONPATH</code> environment variable to have some local directory, and copy over (or link, I suppose) the version of the mysql lib you want.</p>
0
2009-02-04T11:56:05Z
[ "python" ]
How can I tell python which version of libmysqlclient.so to use?
511,011
<p>I'm running a python script on a shared hosting server which until this morning had MySQL version 4. Now it has version 5. My python script can no longer connect to MySQL, as it can't find libmysqlclient_r.so.14:</p> <pre><code>$ python my_script.py Traceback (most recent call last): File "my_script.py", line 6, in ? import MySQLdb File "/home/lib/python2.4/site-packages/PIL-1.1.6-py2.4-linux-i686.egg/__init__.py", line 19, in ? File "build/bdist.linux-i686/egg/_mysql.py", line 7, in ? File "build/bdist.linux-i686/egg/_mysql.py", line 6, in __bootstrap__ ImportError: libmysqlclient_r.so.14: cannot open shared object file: No such file or directory </code></pre> <p>There are various other versions of libmysqlclient in /usr/lib:</p> <pre><code>/usr/lib/libmysqlclient.so.15 /usr/lib/libmysqlclient.so.14 /usr/lib/mysql/libmysqlclient.la /usr/lib/mysql/libmysqlclient.so /usr/lib/mysql/libmysqlclient_r.so /usr/lib/mysql/libmysqlclient_r.a /usr/lib/mysql/libmysqlclient_r.la /usr/lib/mysql/libmysqlclient.a /usr/lib/libmysqlclient.so /usr/lib/libmysqlclient_r.so /usr/lib/libmysqlclient_r.so.15 /usr/lib/libmysqlclient_r.so.15.0.0 /usr/lib/libmysqlclient.so.15.0.0 </code></pre> <p>So my question is this: how can I tell python (version 2.4.3) which version of libmysqlclient to use?</p>
2
2009-02-04T11:48:54Z
511,062
<p>You will have to recompile python-mysql (aka MySQLdb) to get it to link to the new version of libmysqlclient.</p> <p>If your host originally set up the environment rather than you compiling it, you'll have to pester them.</p> <blockquote> <p>/usr/lib/libmysqlclient.so.14</p> </blockquote> <p>This looks like a remnant of the old libmysqlclient, and should be removed. The _r and .a (static) versions are gone and you don't really want a mixture of libraries still around, it will only risk confusing automake.</p> <p>Whilst you <em>could</em> make a symbolic link from libmysqlclient_r.so.14 to .15, that'd only work if the new version of the client happened to have the same ABI for the functions you wanted to use as the old - and that's pretty unlikely, as that's the whole point of changing the version number.</p>
1
2009-02-04T12:02:32Z
[ "python" ]
How can I tell python which version of libmysqlclient.so to use?
511,011
<p>I'm running a python script on a shared hosting server which until this morning had MySQL version 4. Now it has version 5. My python script can no longer connect to MySQL, as it can't find libmysqlclient_r.so.14:</p> <pre><code>$ python my_script.py Traceback (most recent call last): File "my_script.py", line 6, in ? import MySQLdb File "/home/lib/python2.4/site-packages/PIL-1.1.6-py2.4-linux-i686.egg/__init__.py", line 19, in ? File "build/bdist.linux-i686/egg/_mysql.py", line 7, in ? File "build/bdist.linux-i686/egg/_mysql.py", line 6, in __bootstrap__ ImportError: libmysqlclient_r.so.14: cannot open shared object file: No such file or directory </code></pre> <p>There are various other versions of libmysqlclient in /usr/lib:</p> <pre><code>/usr/lib/libmysqlclient.so.15 /usr/lib/libmysqlclient.so.14 /usr/lib/mysql/libmysqlclient.la /usr/lib/mysql/libmysqlclient.so /usr/lib/mysql/libmysqlclient_r.so /usr/lib/mysql/libmysqlclient_r.a /usr/lib/mysql/libmysqlclient_r.la /usr/lib/mysql/libmysqlclient.a /usr/lib/libmysqlclient.so /usr/lib/libmysqlclient_r.so /usr/lib/libmysqlclient_r.so.15 /usr/lib/libmysqlclient_r.so.15.0.0 /usr/lib/libmysqlclient.so.15.0.0 </code></pre> <p>So my question is this: how can I tell python (version 2.4.3) which version of libmysqlclient to use?</p>
2
2009-02-04T11:48:54Z
511,103
<p>You can't tell the dynamic linker which version of a library to use, because the SONAME (full name of the library + interface) is part of the binary.</p> <p>In your case, you can try to upload libmysqlclient_r.so.14 to the host and set <code>LD_LIBRARY_PATH</code> accordingly, so tell the dynamic linker which directories to search additionally to the system dirs when resolving shared objects.</p> <p>You can use <code>ldd</code> to see if it <code>LD_LIBRARY_PATH</code> works:</p> <pre><code>$ ldd $path_to/_mysql.so ... libmysqlclient_r.so.14 =&gt; $path_to_lib/libmysqlclient_r.so.14 ... </code></pre> <p>Otherwise, there will be an error message about unresolved shared objects.</p> <p>Of course that can only be a temporary fix until you rebuild MySQLdb to use the new libraries.</p>
5
2009-02-04T12:16:53Z
[ "python" ]
How to print a string without including '\n' in Python
511,204
<p>Suppose my string is:</p> <pre><code>' Hai Hello\nGood eve\n' </code></pre> <p>How do I eliminate the <code>'\n'</code> in between and make a string print like :</p> <pre><code> Hai Hello Good eve </code></pre> <p>?</p>
15
2009-02-04T12:52:14Z
511,208
<p>You can use the <code>replace</code> method:</p> <pre><code>&gt;&gt;&gt; a = "1\n2" &gt;&gt;&gt; print a 1 2 &gt;&gt;&gt; a = a.replace("\n", " ") &gt;&gt;&gt; print a 1 2 </code></pre>
19
2009-02-04T12:53:50Z
[ "python", "string" ]
How to print a string without including '\n' in Python
511,204
<p>Suppose my string is:</p> <pre><code>' Hai Hello\nGood eve\n' </code></pre> <p>How do I eliminate the <code>'\n'</code> in between and make a string print like :</p> <pre><code> Hai Hello Good eve </code></pre> <p>?</p>
15
2009-02-04T12:52:14Z
511,216
<p>If you don't want the newline at the end of the print statement:</p> <pre><code>import sys sys.stdout.write("text") </code></pre>
22
2009-02-04T12:55:43Z
[ "python", "string" ]
How to print a string without including '\n' in Python
511,204
<p>Suppose my string is:</p> <pre><code>' Hai Hello\nGood eve\n' </code></pre> <p>How do I eliminate the <code>'\n'</code> in between and make a string print like :</p> <pre><code> Hai Hello Good eve </code></pre> <p>?</p>
15
2009-02-04T12:52:14Z
511,272
<pre><code>&gt;&gt;&gt; 'Hai Hello\nGood eve\n'.replace('\n', ' ') 'Hai Hello Good eve ' </code></pre>
1
2009-02-04T13:10:24Z
[ "python", "string" ]
How to print a string without including '\n' in Python
511,204
<p>Suppose my string is:</p> <pre><code>' Hai Hello\nGood eve\n' </code></pre> <p>How do I eliminate the <code>'\n'</code> in between and make a string print like :</p> <pre><code> Hai Hello Good eve </code></pre> <p>?</p>
15
2009-02-04T12:52:14Z
513,411
<p>Add a comma after "print":</p> <pre><code>print "Hai Hello", print "Good eve", </code></pre> <p>Altho "print" is gone in Python 3.0</p>
3
2009-02-04T21:21:20Z
[ "python", "string" ]
How to print a string without including '\n' in Python
511,204
<p>Suppose my string is:</p> <pre><code>' Hai Hello\nGood eve\n' </code></pre> <p>How do I eliminate the <code>'\n'</code> in between and make a string print like :</p> <pre><code> Hai Hello Good eve </code></pre> <p>?</p>
15
2009-02-04T12:52:14Z
814,402
<p>Not sure if this is what you're asking for, but you can use the triple-quoted string:</p> <pre><code>print """Hey man And here's a new line you can put multiple lines inside this kind of string without using \\n""" </code></pre> <p>Will print:</p> <pre> Hey man And here's a new line you can put multiple lines inside this kind of string without using \n </pre>
0
2009-05-02T08:12:09Z
[ "python", "string" ]
How to print a string without including '\n' in Python
511,204
<p>Suppose my string is:</p> <pre><code>' Hai Hello\nGood eve\n' </code></pre> <p>How do I eliminate the <code>'\n'</code> in between and make a string print like :</p> <pre><code> Hai Hello Good eve </code></pre> <p>?</p>
15
2009-02-04T12:52:14Z
1,038,910
<p>In Python 2.6:</p> <pre><code>print "Hello.", print "This is on the same line" </code></pre> <p>In Python 3.0</p> <pre><code>print("Hello", end = " ") print("This is on the same line") </code></pre>
11
2009-06-24T15:00:05Z
[ "python", "string" ]
How to print a string without including '\n' in Python
511,204
<p>Suppose my string is:</p> <pre><code>' Hai Hello\nGood eve\n' </code></pre> <p>How do I eliminate the <code>'\n'</code> in between and make a string print like :</p> <pre><code> Hai Hello Good eve </code></pre> <p>?</p>
15
2009-02-04T12:52:14Z
6,063,403
<p>Way old post but nobody seemed to successfully answer your question. Two possible answers:</p> <p>First, either your string is actually <code>Hai Hello\\\\nGood eve\\\\n</code> printing as <code>Hai Hello\\nGood eve\\n</code> due to the escaped <code>\\\\</code>. Simple fix would be <code>mystring.replace("\\\\n","\\n")</code> (See <a href="http://docs.python.org/reference/lexical_analysis.html#string-literals" rel="nofollow">http://docs.python.org/reference/lexical_analysis.html#string-literals</a>)</p> <p>Or, your string isn't a string and possibly a tuple. I just had a similar error when I thought I had a string and never noticed how it was printing as it was a long string. Mine was printing as:</p> <blockquote> <p>("Lorem ipsum dolor sit amet, consectetur adipiscing elit.\nEtiam orci felis, pulvinar id vehicula nec, iaculis eget quam.\nNam sapien eros, hendrerit et ullamcorper nec, mattis at ipsum.\nNulla nisi ante, aliquet nec fermentum non, faucibus vel odio.\nPraesent ac odio vel metus condimentum tincidunt sed vitae magna.\nInteger nulla odio, sagittis id porta commodo, hendrerit vestibulum risus.\n...,"")</p> </blockquote> <p>Easy to miss the brackets at the start and end and just notice the \n's. Printing <code>mystring[0]</code> should solve this (or whatever index it is in the list/tuple etc).</p>
2
2011-05-19T18:45:20Z
[ "python", "string" ]
How to print a string without including '\n' in Python
511,204
<p>Suppose my string is:</p> <pre><code>' Hai Hello\nGood eve\n' </code></pre> <p>How do I eliminate the <code>'\n'</code> in between and make a string print like :</p> <pre><code> Hai Hello Good eve </code></pre> <p>?</p>
15
2009-02-04T12:52:14Z
8,593,347
<p>I realize this is a terribly old post, but I just ran into this also and wanted to add to it for clarity. What the original user is asking, I believe, is how to get the OS to interpret the string "some text\nsome more text" as:</p> <blockquote> <p>some text</p> <p>some more text</p> </blockquote> <p>Instead of just printing:</p> <blockquote> <p>"some text\nsome more text"</p> </blockquote> <p>and the answer is it is already interpreting. In ubuntu I ran into the problem of it escaping the newline characters when putting it into the string without me asking it to. So the string: </p> <blockquote> <p>"some text\nsome more text"</p> </blockquote> <p>is in fact </p> <blockquote> <p>"some text\\nsome more text"</p> </blockquote> <p>All that is required is to use the <code>mystring.replace("\\\n", "\n")</code> and the desired output will be achieved. Hope this is clear and helps some future person.</p>
1
2011-12-21T16:49:50Z
[ "python", "string" ]
Django Installed Apps Location
511,291
<p>I am an experienced PHP programmer using Django for the first time, and I think it is incredible!</p> <p>I have a project that has a lot of apps, so I wanted to group them in an apps folder.</p> <p>So the structure of the project is:</p> <pre><code>/project/ /project/apps/ /project/apps/app1/ /project/apps/app2 </code></pre> <p>Then in Django settings I have put this:</p> <pre><code>INSTALLED_APPS = ( 'project.apps.app1', 'project.apps.app2', ) </code></pre> <p>This does not seem to work?</p> <p>Any ideas on how you can put all your apps into a seprate folder and not in the project root?</p> <p>Many thanks.</p>
13
2009-02-04T13:15:59Z
511,371
<p>As long as your apps are in your PYTHONPATH, everything should work. Try setting that environment variable to the folder containing your apps.</p> <pre><code>PYTHONPATH="/path/to/your/apps/dir/:$PYTHONPATH" </code></pre>
1
2009-02-04T13:33:40Z
[ "python", "django" ]
Django Installed Apps Location
511,291
<p>I am an experienced PHP programmer using Django for the first time, and I think it is incredible!</p> <p>I have a project that has a lot of apps, so I wanted to group them in an apps folder.</p> <p>So the structure of the project is:</p> <pre><code>/project/ /project/apps/ /project/apps/app1/ /project/apps/app2 </code></pre> <p>Then in Django settings I have put this:</p> <pre><code>INSTALLED_APPS = ( 'project.apps.app1', 'project.apps.app2', ) </code></pre> <p>This does not seem to work?</p> <p>Any ideas on how you can put all your apps into a seprate folder and not in the project root?</p> <p>Many thanks.</p>
13
2009-02-04T13:15:59Z
511,372
<p>Your top-level <code>urls.py</code> (also named in your <code>settings.py</code>) must be able to use a simple "import" statement to get your applications.</p> <p>Does <code>import project.apps.app1.urls</code> work? If not, then your <code>PYTHONPATH</code> isn't set up properly, or you didn't install your project in Python's <code>site-packages</code> directory.</p> <p>I suggest using the <code>PYTHONPATH</code> environment variable, instead of installing into site-packages. Django applications (to me, anyway) seem easier to manage when outside site-packages.</p> <p>We do the following:</p> <ul> <li><p>Django projects go in <code>/opt/project/</code>. </p></li> <li><p><code>PYTHONPATH</code> includes <code>/opt/project</code>.</p></li> <li><p>Our <code>settings.py</code> uses <code>apps.this</code> and <code>apps.that</code> (note that the <code>project</code> part of the name is part of the <code>PYTHONPATH</code>, not part of the import.</p></li> </ul>
0
2009-02-04T13:33:42Z
[ "python", "django" ]
Django Installed Apps Location
511,291
<p>I am an experienced PHP programmer using Django for the first time, and I think it is incredible!</p> <p>I have a project that has a lot of apps, so I wanted to group them in an apps folder.</p> <p>So the structure of the project is:</p> <pre><code>/project/ /project/apps/ /project/apps/app1/ /project/apps/app2 </code></pre> <p>Then in Django settings I have put this:</p> <pre><code>INSTALLED_APPS = ( 'project.apps.app1', 'project.apps.app2', ) </code></pre> <p>This does not seem to work?</p> <p>Any ideas on how you can put all your apps into a seprate folder and not in the project root?</p> <p>Many thanks.</p>
13
2009-02-04T13:15:59Z
511,408
<p>Make sure that the '__init__.py' file is in your apps directory, if it's not there it won't be recognized as part of the package.</p> <p>So each of the folders here should have '__init__.py' file in it. (empty is fine).</p> <pre><code>/project/ /project/apps/ /project/apps/app1/ /project/apps/app2 </code></pre> <p>Then as long as your root 'module' folder is in your PYTHONPATH you'll be able to import from your apps.</p> <p>Here's the documentation regarding the python search path for your reading pleasure:</p> <p><a href="http://docs.python.org/install/index.html#modifying-python-s-search-path">http://docs.python.org/install/index.html#modifying-python-s-search-path</a></p> <p>And a nice simple explanation of what __init__.py file is for:</p> <p><a href="http://effbot.org/pyfaq/what-is-init-py-used-for.htm">http://effbot.org/pyfaq/what-is-init-py-used-for.htm</a></p>
35
2009-02-04T13:41:41Z
[ "python", "django" ]
Django Installed Apps Location
511,291
<p>I am an experienced PHP programmer using Django for the first time, and I think it is incredible!</p> <p>I have a project that has a lot of apps, so I wanted to group them in an apps folder.</p> <p>So the structure of the project is:</p> <pre><code>/project/ /project/apps/ /project/apps/app1/ /project/apps/app2 </code></pre> <p>Then in Django settings I have put this:</p> <pre><code>INSTALLED_APPS = ( 'project.apps.app1', 'project.apps.app2', ) </code></pre> <p>This does not seem to work?</p> <p>Any ideas on how you can put all your apps into a seprate folder and not in the project root?</p> <p>Many thanks.</p>
13
2009-02-04T13:15:59Z
34,711,354
<p>In settings.py in project folder </p>
0
2016-01-10T22:08:52Z
[ "python", "django" ]
Combined Python & Ruby extension module
511,412
<p>I have a C extension module for Python and I want to make it available to Rubyists.</p> <p>The source has a number of C modules, with only one being Python-dependent. The rest depend only on each other and the standard library. I can build it with <code>python setup.py build</code> in the usual way.</p> <p>I've been experimenting with adding Ruby support using <code>newgem</code> and I can build a version of the extension with <code>rake gem</code>. However, the combined source has an ugly directory layout (mixing Gem-style and Setuptools-style structures) and the build process is a kludge.</p> <p>I can't just keep all the sources in the same directory because <code>mkmf</code> automatically picks up the Python-dependent module and tries to build that, and users shouldn't have to install Python to compile a module that won't be used. My current hack is for <code>extconf.rb</code> to copy the Python-independent source-files into the same directory as the Ruby-dependent extension module.</p> <p>Is there a saner way to make the code available to both languages? Should I just duplicate the Python-independent code in a separate Gem? Should I release the independent code as a separate lib built with autotools? Is there a version of <code>mkmf</code> that can skip the unwanted module?</p>
7
2009-02-04T13:42:04Z
511,871
<p>One way to solve it is to create three different projects:</p> <ul> <li>The library itself, independent on python &amp; ruby</li> <li>Python bindings</li> <li>Ruby bindings</li> </ul> <p>That's probably the cleanest solution, albeit it requires a bit more work when doing releases, but it has the advantage that you can release a new version of the Ruby bindings without having to ship a new library/python bindings version.</p>
5
2009-02-04T15:35:56Z
[ "python", "ruby", "setuptools", "newgem" ]
Combined Python & Ruby extension module
511,412
<p>I have a C extension module for Python and I want to make it available to Rubyists.</p> <p>The source has a number of C modules, with only one being Python-dependent. The rest depend only on each other and the standard library. I can build it with <code>python setup.py build</code> in the usual way.</p> <p>I've been experimenting with adding Ruby support using <code>newgem</code> and I can build a version of the extension with <code>rake gem</code>. However, the combined source has an ugly directory layout (mixing Gem-style and Setuptools-style structures) and the build process is a kludge.</p> <p>I can't just keep all the sources in the same directory because <code>mkmf</code> automatically picks up the Python-dependent module and tries to build that, and users shouldn't have to install Python to compile a module that won't be used. My current hack is for <code>extconf.rb</code> to copy the Python-independent source-files into the same directory as the Ruby-dependent extension module.</p> <p>Is there a saner way to make the code available to both languages? Should I just duplicate the Python-independent code in a separate Gem? Should I release the independent code as a separate lib built with autotools? Is there a version of <code>mkmf</code> that can skip the unwanted module?</p>
7
2009-02-04T13:42:04Z
514,483
<p>Complementing on what Johan said, I've used a couple c/c++ support libraries in Python thanks to swig. You write your code in c/c++ then make an intermediary template for each language that you want to support. Its rather painless for Python, but some considerations must be made for Ruby... namely I don't think pthread support is to happy with ruby or vice versa.</p> <p><a href="http://www.swig.org/" rel="nofollow">http://www.swig.org/</a> It's got a somewhat steep learning curve so it might be best to find an example project out there that demonstrates how to use the wrapper for your target languages.</p> <p>This is definitely a useful tool as it makes your code a lot cleaner while still providing robust bindings to multiple languages (PHP, Python, Ruby, and I believe c#)</p>
0
2009-02-05T03:54:55Z
[ "python", "ruby", "setuptools", "newgem" ]
Why doesn't PyRun_String evaluate bool literals?
512,036
<p>I need to evaluate a Python expression from C++. This code seems to work:</p> <pre><code>PyObject * dict = PyDict_New(); PyObject * val = PyRun_String(expression, Py_eval_input, dict, 0); Py_DECREF(dict); </code></pre> <p>Unfortunately, it fails horribly if expression is "True" of "False" (that is, val is 0 and PyErr_Occurred() returns true). What am I doing wrong? Shouldn't they evaluate to Py_True and Py_False respectively?</p>
4
2009-02-04T16:10:14Z
512,815
<pre><code>PyObject* PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals); </code></pre> <p>If you want True and False they will have to be in the <code>*globals</code> dict passed to the interpreter. You might be able to fix that by calling <code>PyEval_GetBuiltins</code>.</p> <p>From the Python 2.6 source code:</p> <pre><code>if (PyDict_GetItemString(globals, "__builtins__") == NULL) { if (PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins()) != 0) return NULL; } </code></pre> <p>If that doesn't work, you could try to <code>PyRun_String("import __builtin__ as __builtins__", globals, locals)</code> before calling <code>PyRun_String("True", ...)</code>.</p> <p>You might notice the Python interactive interpreter always runs code in the <code>__main__</code> module which we haven't bothered to create here. I don't know whether you need to have a <code>__main__</code> module, except that there are a lot of scripts that contain <code>if __name__ == "__main__"</code>.</p>
4
2009-02-04T19:07:32Z
[ "python", "boolean", "cpython" ]
How to copy a directory and its contents to an existing location using Python?
512,173
<p>I'm trying to copy a directory and all its contents to a path that already exists. The problem is, between the os module and the shutil module, there doesn't seem to be a way to do this. the <code>shutil.copytree()</code> function expects that the destination path not exist beforehand.</p> <p>The exact result I'm looking for is to copy an entire folder structure on top of another, overwriting silently on any duplicates found. Before I jump in and start writing my own function to do this I thought I'd ask if anyone knows of an existing recipe or snippet that does this.</p>
32
2009-02-04T16:41:12Z
512,232
<p>Why not implement it on your own using <code>os.walk</code>?</p>
0
2009-02-04T16:56:19Z
[ "python", "operating-system", "filesystems", "copy" ]
How to copy a directory and its contents to an existing location using Python?
512,173
<p>I'm trying to copy a directory and all its contents to a path that already exists. The problem is, between the os module and the shutil module, there doesn't seem to be a way to do this. the <code>shutil.copytree()</code> function expects that the destination path not exist beforehand.</p> <p>The exact result I'm looking for is to copy an entire folder structure on top of another, overwriting silently on any duplicates found. Before I jump in and start writing my own function to do this I thought I'd ask if anyone knows of an existing recipe or snippet that does this.</p>
32
2009-02-04T16:41:12Z
512,273
<p><a href="http://docs.python.org/distutils/apiref.html#distutils.dir_util.copy_tree"><code>distutils.dir_util.copy_tree</code></a> does what you want.</p> <blockquote> <p>Copy an entire directory tree src to a new location dst. Both src and dst must be directory names. If src is not a directory, raise DistutilsFileError. If dst does not exist, it is created with mkpath(). The end result of the copy is that every file in src is copied to dst, and directories under src are recursively copied to dst. Return the list of files that were copied or might have been copied, using their output name. The return value is unaffected by update or dry_run: it is simply the list of all files under src, with the names changed to be under dst.</p> </blockquote> <p>(more documentation at the above url)</p>
41
2009-02-04T17:03:21Z
[ "python", "operating-system", "filesystems", "copy" ]
How to copy a directory and its contents to an existing location using Python?
512,173
<p>I'm trying to copy a directory and all its contents to a path that already exists. The problem is, between the os module and the shutil module, there doesn't seem to be a way to do this. the <code>shutil.copytree()</code> function expects that the destination path not exist beforehand.</p> <p>The exact result I'm looking for is to copy an entire folder structure on top of another, overwriting silently on any duplicates found. Before I jump in and start writing my own function to do this I thought I'd ask if anyone knows of an existing recipe or snippet that does this.</p>
32
2009-02-04T16:41:12Z
513,588
<p>For highlevel file operations like that use the <a href="http://docs.python.org/library/shutil.html" rel="nofollow">shutil</a> module and in your case the copytree function. I think that is cleaner than "abusing" distutils.</p> <p><strong>UPDATE:</strong>: Forget the answer, I overlooked that the OP did try shutil.</p>
1
2009-02-04T22:06:33Z
[ "python", "operating-system", "filesystems", "copy" ]
How to copy a directory and its contents to an existing location using Python?
512,173
<p>I'm trying to copy a directory and all its contents to a path that already exists. The problem is, between the os module and the shutil module, there doesn't seem to be a way to do this. the <code>shutil.copytree()</code> function expects that the destination path not exist beforehand.</p> <p>The exact result I'm looking for is to copy an entire folder structure on top of another, overwriting silently on any duplicates found. Before I jump in and start writing my own function to do this I thought I'd ask if anyone knows of an existing recipe or snippet that does this.</p>
32
2009-02-04T16:41:12Z
615,450
<p>Are you gettting the error that says "Cannot create a directory when its already present"? I am not sure how much silly is this, but all i did was to insert a single line into copytree module: I changed :</p> <pre><code>def copytree(src, dst, symlinks=False): names = os.listdir(src) os.makedirs(dst) </code></pre> <p>into:</p> <pre><code>def copytree(src, dst, symlinks=False): names = os.listdir(src) if (os.path.isdir(dst)==False): os.makedirs(dst) </code></pre> <p>I guess i did some bluder. If so, could someone point me out that? Sorry, i am very new to python :P</p>
0
2009-03-05T16:08:51Z
[ "python", "operating-system", "filesystems", "copy" ]
How to access templates in Python?
512,499
<p>Sometimes, for a program with a lot of data, it is common to place the data in an external file. An example is a script that produces an HTML report, using an external file to hold a template.</p> <p>In Java, the most recommended way to retrieve a resource of the program is to use <code>getClass().getClassLoader().getResource()</code> or <code>getClass().getClassLoader().getResourceAsStream()</code> for a stream.</p> <p>The advantage is that this is independent of the file system. Also, it works whether the classes are in the file system or the application is distributed as a Jar file.</p> <p>How do you achieve the same in Python ? What if you're using <a href="http://www.py2exe.org/" rel="nofollow">py2exe</a> or <a href="http://wiki.python.org/moin/Freeze" rel="nofollow">Freeze</a> to generate a stand-alone running app, as seen in <a href="http://stackoverflow.com/questions/331377/how-to-pack-python-libs-im-using-so-i-can-distribute-them-with-my-app-and-have-a">this question</a> ?</p>
2
2009-02-04T17:45:28Z
512,676
<p>You can use <code>os.path.dirname(__file__)</code> to get the directory of the current module. Then use the <a href="http://docs.python.org/library/os.path.html" rel="nofollow">path manipulation</a> functions (specifically, os.path.join) and <a href="http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files" rel="nofollow">file input/output</a> to open a file under the current module.</p>
2
2009-02-04T18:34:38Z
[ "python", "templates" ]
How to access templates in Python?
512,499
<p>Sometimes, for a program with a lot of data, it is common to place the data in an external file. An example is a script that produces an HTML report, using an external file to hold a template.</p> <p>In Java, the most recommended way to retrieve a resource of the program is to use <code>getClass().getClassLoader().getResource()</code> or <code>getClass().getClassLoader().getResourceAsStream()</code> for a stream.</p> <p>The advantage is that this is independent of the file system. Also, it works whether the classes are in the file system or the application is distributed as a Jar file.</p> <p>How do you achieve the same in Python ? What if you're using <a href="http://www.py2exe.org/" rel="nofollow">py2exe</a> or <a href="http://wiki.python.org/moin/Freeze" rel="nofollow">Freeze</a> to generate a stand-alone running app, as seen in <a href="http://stackoverflow.com/questions/331377/how-to-pack-python-libs-im-using-so-i-can-distribute-them-with-my-app-and-have-a">this question</a> ?</p>
2
2009-02-04T17:45:28Z
512,868
<p>What Daniel said. :-) Also, py2exe can be told to include external files (this is often used for images etc).</p>
1
2009-02-04T19:19:38Z
[ "python", "templates" ]
gedit plugin development in python
512,600
<p>Does anyone know where information about writing gedit plugins can be found ? I'm interested in writing them in Python. I know of <a href="http://live.gnome.org/Gedit/PythonPluginHowTo">Gedit/PythonPluginHowTo</a> , but it isn't very good . Besides the code of writing a plugin that does nothing , I can't seem to find more information . I started to look at other people's code , but I think this shouldn't be the natural way of writing plugins . Can someone help ?</p>
10
2009-02-04T18:15:16Z
513,696
<p>Have you checked out <a href="http://sp2hari.com/gedit-plugin/" rel="nofollow">http://sp2hari.com/gedit-plugin/</a> ? I think this is as thorough as you're going to get, without poring through other people's code. </p>
4
2009-02-04T22:31:32Z
[ "python", "plugins", "gedit" ]
gedit plugin development in python
512,600
<p>Does anyone know where information about writing gedit plugins can be found ? I'm interested in writing them in Python. I know of <a href="http://live.gnome.org/Gedit/PythonPluginHowTo">Gedit/PythonPluginHowTo</a> , but it isn't very good . Besides the code of writing a plugin that does nothing , I can't seem to find more information . I started to look at other people's code , but I think this shouldn't be the natural way of writing plugins . Can someone help ?</p>
10
2009-02-04T18:15:16Z
536,198
<p>When I started working on my gedit plugin, I used the howto you gave a link to, also startign with <a href="http://www.russellbeattie.com/blog/my-first-gedit-plugin">this URL</a>. Then it was looking at other plugins code... I'm sorry to say that, but for me this topic is poorly documented and best and fastest way is to get a pluging done that actually does something.</p>
7
2009-02-11T10:08:36Z
[ "python", "plugins", "gedit" ]
memory use in large data-structures manipulation/processing
512,893
<p>I have a number of large (~100 Mb) files which I'm regularly processing. While I'm trying to delete unneeded data structures during processing, memory consumption is a bit too high. I was wondering if there is a way to efficiently manipulate large data, e.g.:</p> <pre><code>def read(self, filename): fc = read_100_mb_file(filename) self.process(fc) def process(self, content): # do some processing of file content </code></pre> <p>Is there a duplication of data structures? Isn't it more memory efficient to use a class-wide attribute like self.fc?</p> <p>When should I use garbage collection? I know about the gc module, but do I call it after I <code>del fc</code> for example?</p> <p><strong>update</strong><br> p.s. 100 Mb is not a problem in itself. but float conversion, further processing add significantly more to both working set and virtual size (I'm on Windows).</p>
4
2009-02-04T19:25:03Z
512,921
<p>Before you start tearing your hair out over the garbage collector, you might be able to avoid that 100mb hit of loading the entire file into memory by using a memory-mapped file object. See the <a href="http://docs.python.org/library/mmap.html" rel="nofollow">mmap</a> module.</p>
3
2009-02-04T19:29:07Z
[ "python", "data-structures", "memory-leaks", "garbage-collection" ]
memory use in large data-structures manipulation/processing
512,893
<p>I have a number of large (~100 Mb) files which I'm regularly processing. While I'm trying to delete unneeded data structures during processing, memory consumption is a bit too high. I was wondering if there is a way to efficiently manipulate large data, e.g.:</p> <pre><code>def read(self, filename): fc = read_100_mb_file(filename) self.process(fc) def process(self, content): # do some processing of file content </code></pre> <p>Is there a duplication of data structures? Isn't it more memory efficient to use a class-wide attribute like self.fc?</p> <p>When should I use garbage collection? I know about the gc module, but do I call it after I <code>del fc</code> for example?</p> <p><strong>update</strong><br> p.s. 100 Mb is not a problem in itself. but float conversion, further processing add significantly more to both working set and virtual size (I'm on Windows).</p>
4
2009-02-04T19:25:03Z
512,931
<p>Don't read the entire 100 meg file in at a time. Use streams to process a little bit at a time. Check out this blog post that talks about handling large csv and xml files. <a href="http://lethain.com/entry/2009/jan/22/handling-very-large-csv-and-xml-files-in-python/" rel="nofollow">http://lethain.com/entry/2009/jan/22/handling-very-large-csv-and-xml-files-in-python/</a></p> <p>Here is a sample of the code from the article.</p> <pre><code>from __future__ import with_statement # for python 2.5 with open('data.in','r') as fin: with open('data.out','w') as fout: for line in fin: fout.write(','.join(line.split(' '))) </code></pre>
3
2009-02-04T19:32:48Z
[ "python", "data-structures", "memory-leaks", "garbage-collection" ]
memory use in large data-structures manipulation/processing
512,893
<p>I have a number of large (~100 Mb) files which I'm regularly processing. While I'm trying to delete unneeded data structures during processing, memory consumption is a bit too high. I was wondering if there is a way to efficiently manipulate large data, e.g.:</p> <pre><code>def read(self, filename): fc = read_100_mb_file(filename) self.process(fc) def process(self, content): # do some processing of file content </code></pre> <p>Is there a duplication of data structures? Isn't it more memory efficient to use a class-wide attribute like self.fc?</p> <p>When should I use garbage collection? I know about the gc module, but do I call it after I <code>del fc</code> for example?</p> <p><strong>update</strong><br> p.s. 100 Mb is not a problem in itself. but float conversion, further processing add significantly more to both working set and virtual size (I'm on Windows).</p>
4
2009-02-04T19:25:03Z
513,000
<p>So, from your comments I assume that your file looks something like this:</p> <pre><code>item1,item2,item3,item4,item5,item6,item7,...,itemn </code></pre> <p>which you all reduce to a single value by repeated application of some combination function. As a solution, only read a single value at a time:</p> <pre><code>def read_values(f): buf = [] while True: c = f.read(1) if c == ",": yield parse("".join(buf)) buf = [] elif c == "": yield parse("".join(buf)) return else: buf.append(c) with open("some_file", "r") as f: agg = initial for v in read_values(f): agg = combine(agg, v) </code></pre> <p>This way, memory consumption stays constant, unless <code>agg</code> grows in time. </p> <ol> <li>Provide appropriate implementations of <code>initial</code>, <code>parse</code> and <code>combine</code></li> <li>Don't read the file byte-by-byte, but read in a fixed buffer, parse from the buffer and read more as you need it</li> <li><p>This is basically what the builtin <code>reduce</code> function does, but I've used an explicit for loop here for clarity. Here's the same thing using <code>reduce</code>:</p> <pre><code>with open("some_file", "r") as f: agg = reduce(combine, read_values(f), initial) </code></pre></li> </ol> <p>I hope I interpreted your problem correctly.</p>
2
2009-02-04T19:56:08Z
[ "python", "data-structures", "memory-leaks", "garbage-collection" ]
memory use in large data-structures manipulation/processing
512,893
<p>I have a number of large (~100 Mb) files which I'm regularly processing. While I'm trying to delete unneeded data structures during processing, memory consumption is a bit too high. I was wondering if there is a way to efficiently manipulate large data, e.g.:</p> <pre><code>def read(self, filename): fc = read_100_mb_file(filename) self.process(fc) def process(self, content): # do some processing of file content </code></pre> <p>Is there a duplication of data structures? Isn't it more memory efficient to use a class-wide attribute like self.fc?</p> <p>When should I use garbage collection? I know about the gc module, but do I call it after I <code>del fc</code> for example?</p> <p><strong>update</strong><br> p.s. 100 Mb is not a problem in itself. but float conversion, further processing add significantly more to both working set and virtual size (I'm on Windows).</p>
4
2009-02-04T19:25:03Z
513,996
<p>First of all, don't touch the garbage collector. That's not the problem, nor the solution.</p> <p>It sounds like the real problem you're having is not with the file reading at all, but with the data structures that you're allocating as you process the files. Condering using <i>del</i> to remove structures that you no longer need during processing. Also, you might consider using <i>marshal</i> to dump some of the processed data to disk while you work through the next 100mb of input files.</p> <p>For file reading, you have basically two options: unix-style files as streams, or memory mapped files. For streams-based files, the default python file object is already buffered, so the simplest code is also probably the most efficient:</p> <pre> with open("filename", "r") as f: for line in f: # do something with a line of the files </pre> <p>Alternately, you can use f.read([size]) to read blocks of the file. However, usually you do this to gain CPU performance, by multithreading the processing part of your script, so that you can read and process at the same time. But it doesn't help with memory usage; in fact, it uses more memory.</p> <p>The other option is mmap, which looks like this:</p> <pre> with open("filename", "r+") as f: map = mmap.mmap(f.fileno(), 0) line = map.readline() while line != '': # process a line line = map.readline() </pre> <p>This sometimes outperforms streams, but it also won't improve memory usage.</p>
0
2009-02-05T00:22:10Z
[ "python", "data-structures", "memory-leaks", "garbage-collection" ]
memory use in large data-structures manipulation/processing
512,893
<p>I have a number of large (~100 Mb) files which I'm regularly processing. While I'm trying to delete unneeded data structures during processing, memory consumption is a bit too high. I was wondering if there is a way to efficiently manipulate large data, e.g.:</p> <pre><code>def read(self, filename): fc = read_100_mb_file(filename) self.process(fc) def process(self, content): # do some processing of file content </code></pre> <p>Is there a duplication of data structures? Isn't it more memory efficient to use a class-wide attribute like self.fc?</p> <p>When should I use garbage collection? I know about the gc module, but do I call it after I <code>del fc</code> for example?</p> <p><strong>update</strong><br> p.s. 100 Mb is not a problem in itself. but float conversion, further processing add significantly more to both working set and virtual size (I'm on Windows).</p>
4
2009-02-04T19:25:03Z
515,820
<p>I'd suggest looking at the <a href="http://www.dabeaz.com/generators/">presentation by David Beazley</a> on using generators in Python. This technique allows you to handle a lot of data, and do complex processing, quickly and without blowing up your memory use. IMO, the trick isn't holding a huge amount of data in memory as efficiently as possible; the trick is avoiding loading a huge amount of data into memory at the same time.</p>
7
2009-02-05T13:09:36Z
[ "python", "data-structures", "memory-leaks", "garbage-collection" ]
memory use in large data-structures manipulation/processing
512,893
<p>I have a number of large (~100 Mb) files which I'm regularly processing. While I'm trying to delete unneeded data structures during processing, memory consumption is a bit too high. I was wondering if there is a way to efficiently manipulate large data, e.g.:</p> <pre><code>def read(self, filename): fc = read_100_mb_file(filename) self.process(fc) def process(self, content): # do some processing of file content </code></pre> <p>Is there a duplication of data structures? Isn't it more memory efficient to use a class-wide attribute like self.fc?</p> <p>When should I use garbage collection? I know about the gc module, but do I call it after I <code>del fc</code> for example?</p> <p><strong>update</strong><br> p.s. 100 Mb is not a problem in itself. but float conversion, further processing add significantly more to both working set and virtual size (I'm on Windows).</p>
4
2009-02-04T19:25:03Z
544,113
<p>In your example code, data is being stored in the <code>fc</code> variable. If you don't keep a reference to <code>fc</code> around, your entire file contents will be removed from memory when the <code>read</code> method ends. </p> <p>If they are not, then <strong>you are keeping a reference somewhere</strong>. Maybe the reference is being created in <code>read_100_mb_file</code>, maybe in <code>process</code>. If there is no reference, CPython implementation will deallocate it almost immediatelly.</p> <p>There are some tools to help you find where this reference is, <a href="http://guppy-pe.sourceforge.net/" rel="nofollow">guppy</a>, <a href="http://www.aminus.net/wiki/Dowser" rel="nofollow">dowser</a>, <a href="http://pysizer.8325.org/" rel="nofollow">pysizer</a>...</p>
0
2009-02-12T23:54:11Z
[ "python", "data-structures", "memory-leaks", "garbage-collection" ]
Invoking Wine From Apache
513,023
<p>I have Apache/2.2.11 using mod_python 3.3.1/Python 2.5 running under Gentoo linux. In my python script I invoke a win32 exe using wine (os.popen2 call). This works fine outside of Apache but under mod_python I get:</p> <p>wine: cannot open /root/.wine : Permission denied</p> <p>in /var/log/apache/error_log. My apache install is not running as the root user/group. Any ideas why it's looking into /root/.wine?</p> <p>Thanks,</p> <p>LarsenMTL</p>
0
2009-02-04T20:01:09Z
513,031
<p>It's probably because <code>$HOME</code> isn't set correctly...</p> <p>Btw. Are you really sure invoking wine from mod_python is a good idea?</p> <p>If you are sure, something like that could work...</p> <pre><code>from subprocess import Popen HOME = '/the/home/of/www-data' #PLEASE edit proc = Popen(cmd, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True, cwd=HOME, env={"HOME":HOME) </code></pre>
3
2009-02-04T20:03:02Z
[ "python", "apache", "mod-python", "wine" ]
Invoking Wine From Apache
513,023
<p>I have Apache/2.2.11 using mod_python 3.3.1/Python 2.5 running under Gentoo linux. In my python script I invoke a win32 exe using wine (os.popen2 call). This works fine outside of Apache but under mod_python I get:</p> <p>wine: cannot open /root/.wine : Permission denied</p> <p>in /var/log/apache/error_log. My apache install is not running as the root user/group. Any ideas why it's looking into /root/.wine?</p> <p>Thanks,</p> <p>LarsenMTL</p>
0
2009-02-04T20:01:09Z
6,263,440
<p>I was also having very hard time and did lots of researched but failed. Finally found the simplest way by adding <code>'WINEPREFIX="/srv/www/.wine"'</code> in <code>/etc/init.d/httpd</code> file as:</p> <pre><code>case $ARGV in start|stop|restart|graceful|graceful-stop) WINEPREFIX="/srv/www/.wine" $HTTPD -k $ARGV ERROR=$? ;; </code></pre> <p>Copy <code>/root/.wine to /srv/www/.wine</code> and change the owner to apache (from root). Hope this will solve the problem.</p>
1
2011-06-07T09:46:32Z
[ "python", "apache", "mod-python", "wine" ]
pure web based versioning system
513,173
<p>My hosting service does not currently run/allow svn, git, cvs on their server. I would really like to be able to 'sync' my current source on my development machine with my production server. </p> <p>I am looking for a <strong>pure php/python/ruby version control system</strong> (not just a <em>client</em> for a version control system) that does not require any services running on the server machine, something that could use the http interface to upload/download and sync files - basically offering a back end into my 'live' site for version control.</p> <p>Additionally, I would think that such a system would be easy to develop an 'online' ide for, so that I could develop directly on the production server. (issues of testing aside of course)</p> <p>Does anyone know if such a system exists?</p> <p>==Edit==</p> <p>Really, I want a wiki front end for a version control / development system - Basically look like a wiki and edit development files so that I could easily make and roll back changes via the web. I doubt this exists, but it would be easy to extend an existing php port of svn... </p>
3
2009-02-04T20:34:13Z
513,211
<p>You could look into <a href="http://www.selenic.com/mercurial/wiki/" rel="nofollow">mercurial</a> or <a href="http://bazaar-vcs.org/" rel="nofollow">bazaar-ng</a> they are both written in python and support at least http downloads afaik, not really web based but written in one of the languages your hoster supports if the tags are correct. HTH</p>
1
2009-02-04T20:41:30Z
[ "php", "python", "version-control", "web-applications" ]
pure web based versioning system
513,173
<p>My hosting service does not currently run/allow svn, git, cvs on their server. I would really like to be able to 'sync' my current source on my development machine with my production server. </p> <p>I am looking for a <strong>pure php/python/ruby version control system</strong> (not just a <em>client</em> for a version control system) that does not require any services running on the server machine, something that could use the http interface to upload/download and sync files - basically offering a back end into my 'live' site for version control.</p> <p>Additionally, I would think that such a system would be easy to develop an 'online' ide for, so that I could develop directly on the production server. (issues of testing aside of course)</p> <p>Does anyone know if such a system exists?</p> <p>==Edit==</p> <p>Really, I want a wiki front end for a version control / development system - Basically look like a wiki and edit development files so that I could easily make and roll back changes via the web. I doubt this exists, but it would be easy to extend an existing php port of svn... </p>
3
2009-02-04T20:34:13Z
513,231
<p>Get a better hosting service. Seriously. Even if you found something that worked in PHP/Ruby/Perl/Whatever, it would still be a sub-par solution. It most likely wouldn't integrate with any IDE you have, and wouldn't have a good tool set available for working with it. It would be really clunky to do correctly.</p> <p>The other option is to get a free SVN host, or host SVN on your own machine, and then just push updates from your SVN host to your web site via ftp.</p>
7
2009-02-04T20:45:06Z
[ "php", "python", "version-control", "web-applications" ]
pure web based versioning system
513,173
<p>My hosting service does not currently run/allow svn, git, cvs on their server. I would really like to be able to 'sync' my current source on my development machine with my production server. </p> <p>I am looking for a <strong>pure php/python/ruby version control system</strong> (not just a <em>client</em> for a version control system) that does not require any services running on the server machine, something that could use the http interface to upload/download and sync files - basically offering a back end into my 'live' site for version control.</p> <p>Additionally, I would think that such a system would be easy to develop an 'online' ide for, so that I could develop directly on the production server. (issues of testing aside of course)</p> <p>Does anyone know if such a system exists?</p> <p>==Edit==</p> <p>Really, I want a wiki front end for a version control / development system - Basically look like a wiki and edit development files so that I could easily make and roll back changes via the web. I doubt this exists, but it would be easy to extend an existing php port of svn... </p>
3
2009-02-04T20:34:13Z
513,251
<p><a href="http://www.selenic.com/mercurial/" rel="nofollow">Mercurial</a> has a web-interface and allows commits via http. It uses a couple of C extensions, but I would guess that all of them have pure-Python counterparts.</p> <p>You can also just use WebDAV, when your hoster provides it.</p>
1
2009-02-04T20:47:51Z
[ "php", "python", "version-control", "web-applications" ]
pure web based versioning system
513,173
<p>My hosting service does not currently run/allow svn, git, cvs on their server. I would really like to be able to 'sync' my current source on my development machine with my production server. </p> <p>I am looking for a <strong>pure php/python/ruby version control system</strong> (not just a <em>client</em> for a version control system) that does not require any services running on the server machine, something that could use the http interface to upload/download and sync files - basically offering a back end into my 'live' site for version control.</p> <p>Additionally, I would think that such a system would be easy to develop an 'online' ide for, so that I could develop directly on the production server. (issues of testing aside of course)</p> <p>Does anyone know if such a system exists?</p> <p>==Edit==</p> <p>Really, I want a wiki front end for a version control / development system - Basically look like a wiki and edit development files so that I could easily make and roll back changes via the web. I doubt this exists, but it would be easy to extend an existing php port of svn... </p>
3
2009-02-04T20:34:13Z
513,253
<p>you could try the reverse way</p> <ul> <li>use e.g. a free online svn/git Service to version control the sources on your dev machine</li> <li>use usual ways to update the "production" machine aka site, like FTP</li> </ul>
0
2009-02-04T20:48:38Z
[ "php", "python", "version-control", "web-applications" ]
pure web based versioning system
513,173
<p>My hosting service does not currently run/allow svn, git, cvs on their server. I would really like to be able to 'sync' my current source on my development machine with my production server. </p> <p>I am looking for a <strong>pure php/python/ruby version control system</strong> (not just a <em>client</em> for a version control system) that does not require any services running on the server machine, something that could use the http interface to upload/download and sync files - basically offering a back end into my 'live' site for version control.</p> <p>Additionally, I would think that such a system would be easy to develop an 'online' ide for, so that I could develop directly on the production server. (issues of testing aside of course)</p> <p>Does anyone know if such a system exists?</p> <p>==Edit==</p> <p>Really, I want a wiki front end for a version control / development system - Basically look like a wiki and edit development files so that I could easily make and roll back changes via the web. I doubt this exists, but it would be easy to extend an existing php port of svn... </p>
3
2009-02-04T20:34:13Z
513,306
<p>for the time you've spent researching this you could have just gone out and got a much better hosting company. Is there some sort of special relationship or something? </p> <p>I've never heard of any decent hosting company not offering cvs at a bare minimum. </p> <p>(Rant Over). </p> <p>You will save yourself a ton of time if you just get another hosting company. </p> <p>Here's how I look at it. </p> <p>Your hourly rate: at least 15-20$ an hour (For me, I say 100$). How long it'll take you to figure out merurial or webdav or whatever: at least 10 good hours (if you are like me: 30 hours). </p> <p>How much money will you waste? 150-200$. </p> <p>How much will a new host cost: A2 hosting starts at 6/month prepaid for two years: 144$. How long to set up: 5 mins. </p> <p>Take your business elsewhere. Professionalism from your vendors will go a long way for your mental health in the long run.</p>
3
2009-02-04T20:56:12Z
[ "php", "python", "version-control", "web-applications" ]
pure web based versioning system
513,173
<p>My hosting service does not currently run/allow svn, git, cvs on their server. I would really like to be able to 'sync' my current source on my development machine with my production server. </p> <p>I am looking for a <strong>pure php/python/ruby version control system</strong> (not just a <em>client</em> for a version control system) that does not require any services running on the server machine, something that could use the http interface to upload/download and sync files - basically offering a back end into my 'live' site for version control.</p> <p>Additionally, I would think that such a system would be easy to develop an 'online' ide for, so that I could develop directly on the production server. (issues of testing aside of course)</p> <p>Does anyone know if such a system exists?</p> <p>==Edit==</p> <p>Really, I want a wiki front end for a version control / development system - Basically look like a wiki and edit development files so that I could easily make and roll back changes via the web. I doubt this exists, but it would be easy to extend an existing php port of svn... </p>
3
2009-02-04T20:34:13Z
513,322
<p>Don't host your repository on your web server. Deploy from your server to the ftp/sftp - whatever.</p>
2
2009-02-04T20:59:22Z
[ "php", "python", "version-control", "web-applications" ]
pure web based versioning system
513,173
<p>My hosting service does not currently run/allow svn, git, cvs on their server. I would really like to be able to 'sync' my current source on my development machine with my production server. </p> <p>I am looking for a <strong>pure php/python/ruby version control system</strong> (not just a <em>client</em> for a version control system) that does not require any services running on the server machine, something that could use the http interface to upload/download and sync files - basically offering a back end into my 'live' site for version control.</p> <p>Additionally, I would think that such a system would be easy to develop an 'online' ide for, so that I could develop directly on the production server. (issues of testing aside of course)</p> <p>Does anyone know if such a system exists?</p> <p>==Edit==</p> <p>Really, I want a wiki front end for a version control / development system - Basically look like a wiki and edit development files so that I could easily make and roll back changes via the web. I doubt this exists, but it would be easy to extend an existing php port of svn... </p>
3
2009-02-04T20:34:13Z
513,366
<p>I think it's actually a pretty good idea, but don't believe such a versioning system exists (yet) so hopefully you'll go ahead and make one.</p> <p>I don't think adapting an existing solution is going to be easy, but it's probably worth looking into because if you use an existing solution you'll have all the client support done, and most of the versioning difficulties taken care of.</p> <p>Starting from scratch is not going to be trivial.</p>
1
2009-02-04T21:10:53Z
[ "php", "python", "version-control", "web-applications" ]
pure web based versioning system
513,173
<p>My hosting service does not currently run/allow svn, git, cvs on their server. I would really like to be able to 'sync' my current source on my development machine with my production server. </p> <p>I am looking for a <strong>pure php/python/ruby version control system</strong> (not just a <em>client</em> for a version control system) that does not require any services running on the server machine, something that could use the http interface to upload/download and sync files - basically offering a back end into my 'live' site for version control.</p> <p>Additionally, I would think that such a system would be easy to develop an 'online' ide for, so that I could develop directly on the production server. (issues of testing aside of course)</p> <p>Does anyone know if such a system exists?</p> <p>==Edit==</p> <p>Really, I want a wiki front end for a version control / development system - Basically look like a wiki and edit development files so that I could easily make and roll back changes via the web. I doubt this exists, but it would be easy to extend an existing php port of svn... </p>
3
2009-02-04T20:34:13Z
513,899
<p>Why dont you want a client..? A simple client that you can run on your production machine which then syncs to your repository running on another server somewhere.</p> <p>SVN is available over HTTP so writing a client that is able to sync your code is really easy in python or php.</p>
0
2009-02-04T23:34:14Z
[ "php", "python", "version-control", "web-applications" ]
pure web based versioning system
513,173
<p>My hosting service does not currently run/allow svn, git, cvs on their server. I would really like to be able to 'sync' my current source on my development machine with my production server. </p> <p>I am looking for a <strong>pure php/python/ruby version control system</strong> (not just a <em>client</em> for a version control system) that does not require any services running on the server machine, something that could use the http interface to upload/download and sync files - basically offering a back end into my 'live' site for version control.</p> <p>Additionally, I would think that such a system would be easy to develop an 'online' ide for, so that I could develop directly on the production server. (issues of testing aside of course)</p> <p>Does anyone know if such a system exists?</p> <p>==Edit==</p> <p>Really, I want a wiki front end for a version control / development system - Basically look like a wiki and edit development files so that I could easily make and roll back changes via the web. I doubt this exists, but it would be easy to extend an existing php port of svn... </p>
3
2009-02-04T20:34:13Z
515,956
<p>Use Bazaar:</p> <blockquote> <p>Lightweight. No dedicated server with Bazaar installed is needed, just FTP access to a web server. A smart server is available for those requiring additional performance or security but it is not required in many cases - Bazaar 1.x over plain http performs well.</p> </blockquote>
1
2009-02-05T13:52:10Z
[ "php", "python", "version-control", "web-applications" ]
Various Python datetime issues
513,291
<p>I have two methods that I'm using as custom tags in a template engine:</p> <pre><code># Renders a &lt;select&gt; form field def select_field(options, selected_item, field_name): options = [(str(v),str(v)) for v in options] html = ['&lt;select name="%s"&gt;' % field_name] for k,v in options: tmp = '&lt;option ' if k == selected_item: tmp += 'selected ' tmp += 'value="%s"&gt;%s&lt;/option&gt;' % (k,v) html.append(tmp) html.append('&lt;/select&gt;') return '\n'.join(html) # Renders a collection of &lt;select&gt; fields for datetime values def datetime_field(current_dt, field_name): if current_dt == None: current_dt = datetime.datetime.now() day = select_field(range(1, 32), current_dt.day, field_name + "_day") month = select_field(range(1, 13), current_dt.month, field_name + "_month") year = select_field(range(datetime.datetime.now().year, datetime.datetime.now().year + 10), current_dt.year, field_name + "_year") hour = select_field(range(1, 13), current_dt.hour, field_name + "_hour") minute = select_field(range(1, 60), current_dt.minute, field_name + "_minute") period = select_field(['AM', 'PM'], 'AM', field_name + "_period") return "\n".join([day, '/', month, '/', year, ' at ', hour, ':', minute, period]) </code></pre> <p>As you can see in the comments, I'm attempting to generate select fields for building a date and time value.</p> <p>My first question is, how do I make the day, month, hour, and minute ranges use two digits? For example, the code generates "1, 2, 3..." while I would like "01, 02, 03".</p> <p>Next, when the fields get generated, the values of the supplied datetime are not selected automatically, even though I'm telling the select_field method to add a "selected" attribute when the value is equal to the supplied datetime's value.</p> <p>Finally, how do I get the 12-hour period identifier (AM/PM) for the supplied datetime? For the moment, I'm simply selecting 'AM' by default, but I would like to supply this value from the datetime itself.</p>
2
2009-02-04T20:54:50Z
513,318
<p>Question 1:</p> <pre><code>&gt;&gt;&gt; '%02d' % 2 '02' &gt;&gt;&gt; '%02d' % 59 '59' </code></pre>
1
2009-02-04T20:58:52Z
[ "python", "datetime" ]
Various Python datetime issues
513,291
<p>I have two methods that I'm using as custom tags in a template engine:</p> <pre><code># Renders a &lt;select&gt; form field def select_field(options, selected_item, field_name): options = [(str(v),str(v)) for v in options] html = ['&lt;select name="%s"&gt;' % field_name] for k,v in options: tmp = '&lt;option ' if k == selected_item: tmp += 'selected ' tmp += 'value="%s"&gt;%s&lt;/option&gt;' % (k,v) html.append(tmp) html.append('&lt;/select&gt;') return '\n'.join(html) # Renders a collection of &lt;select&gt; fields for datetime values def datetime_field(current_dt, field_name): if current_dt == None: current_dt = datetime.datetime.now() day = select_field(range(1, 32), current_dt.day, field_name + "_day") month = select_field(range(1, 13), current_dt.month, field_name + "_month") year = select_field(range(datetime.datetime.now().year, datetime.datetime.now().year + 10), current_dt.year, field_name + "_year") hour = select_field(range(1, 13), current_dt.hour, field_name + "_hour") minute = select_field(range(1, 60), current_dt.minute, field_name + "_minute") period = select_field(['AM', 'PM'], 'AM', field_name + "_period") return "\n".join([day, '/', month, '/', year, ' at ', hour, ':', minute, period]) </code></pre> <p>As you can see in the comments, I'm attempting to generate select fields for building a date and time value.</p> <p>My first question is, how do I make the day, month, hour, and minute ranges use two digits? For example, the code generates "1, 2, 3..." while I would like "01, 02, 03".</p> <p>Next, when the fields get generated, the values of the supplied datetime are not selected automatically, even though I'm telling the select_field method to add a "selected" attribute when the value is equal to the supplied datetime's value.</p> <p>Finally, how do I get the 12-hour period identifier (AM/PM) for the supplied datetime? For the moment, I'm simply selecting 'AM' by default, but I would like to supply this value from the datetime itself.</p>
2
2009-02-04T20:54:50Z
513,339
<p>To turn an integer range into two digit strings:</p> <pre><code>&gt;&gt;&gt; range(13) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] &gt;&gt;&gt; [ '%02d' % i for i in range(13) ] ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'] </code></pre> <p>Then to get the AM/PM indicator:</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; current_dt = datetime.datetime.now() &gt;&gt;&gt; current_dt datetime.datetime(2009, 2, 4, 22, 2, 14, 390000) &gt;&gt;&gt; ['AM','PM'][current_dt.hour&gt;=12] 'PM' </code></pre> <p>Voila!</p>
5
2009-02-04T21:03:45Z
[ "python", "datetime" ]
Various Python datetime issues
513,291
<p>I have two methods that I'm using as custom tags in a template engine:</p> <pre><code># Renders a &lt;select&gt; form field def select_field(options, selected_item, field_name): options = [(str(v),str(v)) for v in options] html = ['&lt;select name="%s"&gt;' % field_name] for k,v in options: tmp = '&lt;option ' if k == selected_item: tmp += 'selected ' tmp += 'value="%s"&gt;%s&lt;/option&gt;' % (k,v) html.append(tmp) html.append('&lt;/select&gt;') return '\n'.join(html) # Renders a collection of &lt;select&gt; fields for datetime values def datetime_field(current_dt, field_name): if current_dt == None: current_dt = datetime.datetime.now() day = select_field(range(1, 32), current_dt.day, field_name + "_day") month = select_field(range(1, 13), current_dt.month, field_name + "_month") year = select_field(range(datetime.datetime.now().year, datetime.datetime.now().year + 10), current_dt.year, field_name + "_year") hour = select_field(range(1, 13), current_dt.hour, field_name + "_hour") minute = select_field(range(1, 60), current_dt.minute, field_name + "_minute") period = select_field(['AM', 'PM'], 'AM', field_name + "_period") return "\n".join([day, '/', month, '/', year, ' at ', hour, ':', minute, period]) </code></pre> <p>As you can see in the comments, I'm attempting to generate select fields for building a date and time value.</p> <p>My first question is, how do I make the day, month, hour, and minute ranges use two digits? For example, the code generates "1, 2, 3..." while I would like "01, 02, 03".</p> <p>Next, when the fields get generated, the values of the supplied datetime are not selected automatically, even though I'm telling the select_field method to add a "selected" attribute when the value is equal to the supplied datetime's value.</p> <p>Finally, how do I get the 12-hour period identifier (AM/PM) for the supplied datetime? For the moment, I'm simply selecting 'AM' by default, but I would like to supply this value from the datetime itself.</p>
2
2009-02-04T20:54:50Z
513,345
<ol> <li><p>Supply a format string to the <code>select_field</code> method to show leading zeros.</p> <pre><code>&gt;&gt;&gt; print "%02i" % (1, ) 01 </code></pre></li> <li><p>datetime.hour is 0-23, so you have to adapt it when setting the field. This is also the answer on how to detect AM/PM. Make sure to convert it back correctly.</p></li> </ol>
0
2009-02-04T21:04:52Z
[ "python", "datetime" ]