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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Calculating formulae in Excel with Python | 1,116,725 | <p>I would like to insert a calculation in Excel using Python.
Generally it can be done by inserting a formula string into the relevant cell.
However, if i need to calculate a formula multiple times for the whole column
the formula must be updated for each individual cell. For example, if i need to
calculate the sum of two cells, then for cell C(k) the computation would be A(k)+B(k).
In excel it is possible to calculate C1=A1+B1 and then automatically expand the
calculation by dragging the mouse from C1 downwards.
My question is: Is it possible to the same thing with Python, i.e. to define a formula in only one cell and then to use Excel capabilities to extend the calculation for the whole column/row?</p>
<p>Thank you in advance,
Sasha</p>
| 1 | 2009-07-12T19:36:54Z | 5,479,903 | <p>If you want to iterate in the horizontal direction, here is a function I use. 0 -> a, 26 -> aa, 723 -> aav </p>
<pre><code>def _num_to_let(num):
if num > 25:
return _num_to_let(num/26-1) + chr(97+ num % 26)
return chr(97+num)
</code></pre>
| 0 | 2011-03-29T22:57:54Z | [
"python",
"excel",
"formula"
] |
Calculating formulae in Excel with Python | 1,116,725 | <p>I would like to insert a calculation in Excel using Python.
Generally it can be done by inserting a formula string into the relevant cell.
However, if i need to calculate a formula multiple times for the whole column
the formula must be updated for each individual cell. For example, if i need to
calculate the sum of two cells, then for cell C(k) the computation would be A(k)+B(k).
In excel it is possible to calculate C1=A1+B1 and then automatically expand the
calculation by dragging the mouse from C1 downwards.
My question is: Is it possible to the same thing with Python, i.e. to define a formula in only one cell and then to use Excel capabilities to extend the calculation for the whole column/row?</p>
<p>Thank you in advance,
Sasha</p>
| 1 | 2009-07-12T19:36:54Z | 36,379,409 | <p>If you want to iterate in xlwt for columns (in formulas) you can use Utils module from xlwt like this:</p>
<pre><code>from xlwt import Utils
print Utils.rowcol_pair_to_cellrange(2,2,12,2)
print Utils.rowcol_to_cell(13,2)
>>>
C3:C13
C14
</code></pre>
| 0 | 2016-04-02T22:24:16Z | [
"python",
"excel",
"formula"
] |
html form submission in python and php is simple, can a novice do it in java? | 1,116,921 | <p>I've made two versions of a script that submits a (https) web page form and collects the results. One version uses Snoopy.class in php, and the other uses urllib and urllib2 in python. Now I would like to make a java version.</p>
<p>Snoopy makes the php version exceedingly easy to write, and it runs fine on my own (OS X) machine. But it allocated too much memory, and was killed at the same point (during curl execution), when run on the pair.com web hosting service. Runs fine on dreamhost.com web hosting service.</p>
<p>So I decided to try a python version while I looked into what could cause the memory problem, and urllib and urllib2 made this very easy. The script runs fine. Gets about 70,000 database records, using several hundred form submissions, saving to a file of about 10MB, in about 7 minutes.</p>
<p>Looking into how to do this with java, I get the feeling it will not be the same walk-in-the-park as it was with php and python. Is form submission in java not for mere mortals?</p>
<p>I spent most of the day just trying to figure out how to set up Apache HttpClient. That is, before I gave up. If it takes me more than a few more days to sort that out, then it will be the subject of another question, I suppose.</p>
<p>HttpClient innovation.ch does not support https.</p>
<p>And WebClient looks like it will take me at least a few days to figure out.</p>
<p>So, php and python versions were a breeze. Can a java version be made in a few simple lines as well? If not, I'll leave it for a later day since I'm only a novice. If so, can some kind soul please point me toward the light?</p>
<p>Thanks.</p>
<p>For comparison, the essential lines of code from the two versions:</p>
<p><hr /></p>
<p>python version</p>
<pre><code>import urllib
import urllib2
submitVars['firstName'] = "John"
submitVars['lastName'] = "Doe"
submitUrl = "https URL of form action goes here"
referer = "URL of referring web page goes here"
submitVarsUrlencoded = urllib.urlencode(submitVars)
req = urllib2.Request(submitUrl, submitVarsUrlencoded)
req.add_header('Referer', referer)
response = urllib2.urlopen(req)
thePage = response.read()
</code></pre>
<p><hr /></p>
<p>php version</p>
<pre><code>require('Snoopy.class.php');
$snoopy = new Snoopy;
$submit_vars["first_name"] = "John";
$submit_vars["last_name"] = "Doe";
$submit_url = "https URL of form action goes here";
$snoopy->referer = "URL of referring web page goes here";
$snoopy->submit($submit_url,$submit_vars);
$the_page = $snoopy->results;
</code></pre>
| 2 | 2009-07-12T21:07:58Z | 1,116,934 | <p>Use HttpComponents <a href="http://hc.apache.org/" rel="nofollow">http://hc.apache.org/</a>. You need:</p>
<ul>
<li>HttpComponents Core, <a href="http://mirrors.hostingromania.ro/apache.org/httpcomponents/httpcore/binary/httpcomponents-core-4.0.1-bin.zip" rel="nofollow">direct download</a></li>
<li>HttpComponents Client, <a href="http://mirrors.hostingromania.ro/apache.org/httpcomponents/httpclient/binary/httpcomponents-client-4.0-beta2-bin.zip" rel="nofollow">direct download</a></li>
<li>Commons Logging</li>
</ul>
<p>Example code:</p>
<pre><code>import org.apache.http.message.BasicNameValuePair;
import org.apache.http.NameValuePair;
import org.apache.http.HttpResponse;
import org.apache.http.HttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.HttpClient;
import java.util.ArrayList;
import java.util.List;
import java.io.OutputStream;
import java.io.ByteArrayOutputStream;
public class HttpClientTest {
public static void main(String[] args) throws Exception {
// request parameters
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("q", "quality"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
HttpPost httppost = new HttpPost("http://stackoverflow.com/search");
httppost.setEntity(entity);
// execute the request
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// display the response status code
System.out.println(response.getStatusLine().getStatusCode());
// display the response body
HttpEntity responseEntity = response.getEntity();
OutputStream out = new ByteArrayOutputStream();
responseEntity.writeTo(out);
System.out.println(out);
}
}
</code></pre>
<p>Save it to HttpClientTest.java. Have this java file, httpcore-4.0.1.jar and httpclient-4.0-alpha4.jar in the same directory Supposing you have the sun java 1.6 jdk installed, compile it:</p>
<pre><code>javac HttpClientTest.java -cp httpcore-4.0.1.jar;httpclient-4.0-alpha4.jar;commons-logging-1.1.1.jar
</code></pre>
<p>Execute it</p>
<pre><code>java HttpClientTest.class -cp httpcore-4.0.1.jar;httpclient-4.0-alpha4.jar;commons-logging-1.1.1.jar
</code></pre>
<p>I would argue that is as simple in java as it is in php or python (your examples). In all cases you need:</p>
<ul>
<li>the sdk configured</li>
<li>a library (with dependencies)</li>
<li>sample code</li>
</ul>
| 3 | 2009-07-12T21:13:15Z | [
"java",
"php",
"python",
"http"
] |
html form submission in python and php is simple, can a novice do it in java? | 1,116,921 | <p>I've made two versions of a script that submits a (https) web page form and collects the results. One version uses Snoopy.class in php, and the other uses urllib and urllib2 in python. Now I would like to make a java version.</p>
<p>Snoopy makes the php version exceedingly easy to write, and it runs fine on my own (OS X) machine. But it allocated too much memory, and was killed at the same point (during curl execution), when run on the pair.com web hosting service. Runs fine on dreamhost.com web hosting service.</p>
<p>So I decided to try a python version while I looked into what could cause the memory problem, and urllib and urllib2 made this very easy. The script runs fine. Gets about 70,000 database records, using several hundred form submissions, saving to a file of about 10MB, in about 7 minutes.</p>
<p>Looking into how to do this with java, I get the feeling it will not be the same walk-in-the-park as it was with php and python. Is form submission in java not for mere mortals?</p>
<p>I spent most of the day just trying to figure out how to set up Apache HttpClient. That is, before I gave up. If it takes me more than a few more days to sort that out, then it will be the subject of another question, I suppose.</p>
<p>HttpClient innovation.ch does not support https.</p>
<p>And WebClient looks like it will take me at least a few days to figure out.</p>
<p>So, php and python versions were a breeze. Can a java version be made in a few simple lines as well? If not, I'll leave it for a later day since I'm only a novice. If so, can some kind soul please point me toward the light?</p>
<p>Thanks.</p>
<p>For comparison, the essential lines of code from the two versions:</p>
<p><hr /></p>
<p>python version</p>
<pre><code>import urllib
import urllib2
submitVars['firstName'] = "John"
submitVars['lastName'] = "Doe"
submitUrl = "https URL of form action goes here"
referer = "URL of referring web page goes here"
submitVarsUrlencoded = urllib.urlencode(submitVars)
req = urllib2.Request(submitUrl, submitVarsUrlencoded)
req.add_header('Referer', referer)
response = urllib2.urlopen(req)
thePage = response.read()
</code></pre>
<p><hr /></p>
<p>php version</p>
<pre><code>require('Snoopy.class.php');
$snoopy = new Snoopy;
$submit_vars["first_name"] = "John";
$submit_vars["last_name"] = "Doe";
$submit_url = "https URL of form action goes here";
$snoopy->referer = "URL of referring web page goes here";
$snoopy->submit($submit_url,$submit_vars);
$the_page = $snoopy->results;
</code></pre>
| 2 | 2009-07-12T21:07:58Z | 1,116,949 | <p>What would be so wrong with Apache HttpClient?</p>
<p>Just make sure you add the dependencies also to classpath, that is <a href="http://hc.apache.org/downloads.cgi" rel="nofollow">HttpComponents</a>.</p>
<pre><code>PostMethod post = new PostMethod("https URL of form action goes here");
NameValuePair[] data = {
new NameValuePair("first_name", "joe"),
new NameValuePair("last_name", "Doe")
};
post.setRequestBody(data);
post.addRequestHeader("Referer", "URL of referring web page goes here");
// TODO: execute method and handle any error responses.
...
InputStream inPage = post.getResponseBodyAsStream();
// handle response.
</code></pre>
| 2 | 2009-07-12T21:20:03Z | [
"java",
"php",
"python",
"http"
] |
html form submission in python and php is simple, can a novice do it in java? | 1,116,921 | <p>I've made two versions of a script that submits a (https) web page form and collects the results. One version uses Snoopy.class in php, and the other uses urllib and urllib2 in python. Now I would like to make a java version.</p>
<p>Snoopy makes the php version exceedingly easy to write, and it runs fine on my own (OS X) machine. But it allocated too much memory, and was killed at the same point (during curl execution), when run on the pair.com web hosting service. Runs fine on dreamhost.com web hosting service.</p>
<p>So I decided to try a python version while I looked into what could cause the memory problem, and urllib and urllib2 made this very easy. The script runs fine. Gets about 70,000 database records, using several hundred form submissions, saving to a file of about 10MB, in about 7 minutes.</p>
<p>Looking into how to do this with java, I get the feeling it will not be the same walk-in-the-park as it was with php and python. Is form submission in java not for mere mortals?</p>
<p>I spent most of the day just trying to figure out how to set up Apache HttpClient. That is, before I gave up. If it takes me more than a few more days to sort that out, then it will be the subject of another question, I suppose.</p>
<p>HttpClient innovation.ch does not support https.</p>
<p>And WebClient looks like it will take me at least a few days to figure out.</p>
<p>So, php and python versions were a breeze. Can a java version be made in a few simple lines as well? If not, I'll leave it for a later day since I'm only a novice. If so, can some kind soul please point me toward the light?</p>
<p>Thanks.</p>
<p>For comparison, the essential lines of code from the two versions:</p>
<p><hr /></p>
<p>python version</p>
<pre><code>import urllib
import urllib2
submitVars['firstName'] = "John"
submitVars['lastName'] = "Doe"
submitUrl = "https URL of form action goes here"
referer = "URL of referring web page goes here"
submitVarsUrlencoded = urllib.urlencode(submitVars)
req = urllib2.Request(submitUrl, submitVarsUrlencoded)
req.add_header('Referer', referer)
response = urllib2.urlopen(req)
thePage = response.read()
</code></pre>
<p><hr /></p>
<p>php version</p>
<pre><code>require('Snoopy.class.php');
$snoopy = new Snoopy;
$submit_vars["first_name"] = "John";
$submit_vars["last_name"] = "Doe";
$submit_url = "https URL of form action goes here";
$snoopy->referer = "URL of referring web page goes here";
$snoopy->submit($submit_url,$submit_vars);
$the_page = $snoopy->results;
</code></pre>
| 2 | 2009-07-12T21:07:58Z | 1,117,351 | <p>Using HttpClient is certainly the more robust solution, but this can be done without an external library dependency. See <a href="http://www.xyzws.com/javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139" rel="nofollow" title="How to use HttpURLConnection POST data to web server?">here</a> for an example of how.</p>
| 2 | 2009-07-13T00:51:08Z | [
"java",
"php",
"python",
"http"
] |
html form submission in python and php is simple, can a novice do it in java? | 1,116,921 | <p>I've made two versions of a script that submits a (https) web page form and collects the results. One version uses Snoopy.class in php, and the other uses urllib and urllib2 in python. Now I would like to make a java version.</p>
<p>Snoopy makes the php version exceedingly easy to write, and it runs fine on my own (OS X) machine. But it allocated too much memory, and was killed at the same point (during curl execution), when run on the pair.com web hosting service. Runs fine on dreamhost.com web hosting service.</p>
<p>So I decided to try a python version while I looked into what could cause the memory problem, and urllib and urllib2 made this very easy. The script runs fine. Gets about 70,000 database records, using several hundred form submissions, saving to a file of about 10MB, in about 7 minutes.</p>
<p>Looking into how to do this with java, I get the feeling it will not be the same walk-in-the-park as it was with php and python. Is form submission in java not for mere mortals?</p>
<p>I spent most of the day just trying to figure out how to set up Apache HttpClient. That is, before I gave up. If it takes me more than a few more days to sort that out, then it will be the subject of another question, I suppose.</p>
<p>HttpClient innovation.ch does not support https.</p>
<p>And WebClient looks like it will take me at least a few days to figure out.</p>
<p>So, php and python versions were a breeze. Can a java version be made in a few simple lines as well? If not, I'll leave it for a later day since I'm only a novice. If so, can some kind soul please point me toward the light?</p>
<p>Thanks.</p>
<p>For comparison, the essential lines of code from the two versions:</p>
<p><hr /></p>
<p>python version</p>
<pre><code>import urllib
import urllib2
submitVars['firstName'] = "John"
submitVars['lastName'] = "Doe"
submitUrl = "https URL of form action goes here"
referer = "URL of referring web page goes here"
submitVarsUrlencoded = urllib.urlencode(submitVars)
req = urllib2.Request(submitUrl, submitVarsUrlencoded)
req.add_header('Referer', referer)
response = urllib2.urlopen(req)
thePage = response.read()
</code></pre>
<p><hr /></p>
<p>php version</p>
<pre><code>require('Snoopy.class.php');
$snoopy = new Snoopy;
$submit_vars["first_name"] = "John";
$submit_vars["last_name"] = "Doe";
$submit_url = "https URL of form action goes here";
$snoopy->referer = "URL of referring web page goes here";
$snoopy->submit($submit_url,$submit_vars);
$the_page = $snoopy->results;
</code></pre>
| 2 | 2009-07-12T21:07:58Z | 1,150,746 | <p>MercerTraieste and Tarnschaf kindly offered partial solutions to the problem. It took me a few more days, and untold hours of brain-splitting nightmare, before I gave up trying to figure out how to add a referer to the http post, and sent a new question to stackoverflow.</p>
<p>Jon Skeet answered instantly that I only needed...</p>
<pre><code>httppost.addHeader("Referer", referer);
</code></pre>
<p>...which makes me look pretty dumb. How did I overlook that one?</p>
<p>Here is the resulting code, based almost entirely on MercerTraieste's suggestion. In my case, I needed to download, and place in my classpath:</p>
<p><a href="http://hc.apache.org/downloads.cgi" rel="nofollow">HttpComponents</a></p>
<ul>
<li>httpclient-4.0-beta2.jar</li>
<li>httpcore-4.0.1.jar</li>
</ul>
<p><a href="http://commons.apache.org/downloads/download%5Flogging.cgi" rel="nofollow">Apache Commons</a></p>
<ul>
<li>commons-logging-1.1.1.jar</li>
</ul>
<p><hr /></p>
<pre><code>import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpRequest;
import org.apache.http.HttpException;
import org.apache.http.NameValuePair;
import org.apache.http.HttpResponse;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.HttpClient;
import org.apache.http.protocol.HttpContext;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.impl.client.DefaultHttpClient;
import java.util.ArrayList;
import java.util.List;
import java.io.OutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class HttpClientTest
{
public static void main(String[] args) throws Exception
{
// initialize some variables
String referer = "URL of referring web page goes here";
String submitUrl = "https URL of form action goes here";
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("firstName", "John"));
formparams.add(new BasicNameValuePair("lastName", "Doe"));
// set up httppost
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
HttpPost httppost = new HttpPost(submitUrl);
httppost.setEntity(entity);
// add referer
httppost.addHeader("Referer", referer);
// create httpclient
DefaultHttpClient httpclient = new DefaultHttpClient();
// execute the request
HttpResponse response = httpclient.execute(httppost);
// display the response body
HttpEntity responseEntity = response.getEntity();
OutputStream out = new ByteArrayOutputStream();
responseEntity.writeTo(out);
System.out.println(out);
}
}
</code></pre>
| 2 | 2009-07-19T20:04:43Z | [
"java",
"php",
"python",
"http"
] |
Django Initialization | 1,116,948 | <p>I have a big array, that I would like to load into memory only once when django starts up and then treat it as a read only global variable. What is the best place to put the code for the initialization of that array?</p>
<p>If I put it in settings.py it will be reinitialized every time the settings module is imported, correct?</p>
| 9 | 2009-07-12T21:19:42Z | 1,117,100 | <p>settings.py is the right place for that. Settings.py is, like any other module, loaded once. There is still the problem of the fact that a module must be imported once for each process, so a respawning style of web server (like apache) will reload it once for each instance in question. For mod_python this will be once per process. for mod_wsgi, this is likely to be just one time, unless you have to restart.</p>
<p>tl;dr modules are imported once, even if multiple import statements are used. put it in settings.py</p>
| 9 | 2009-07-12T22:35:25Z | [
"python",
"django"
] |
Django Initialization | 1,116,948 | <p>I have a big array, that I would like to load into memory only once when django starts up and then treat it as a read only global variable. What is the best place to put the code for the initialization of that array?</p>
<p>If I put it in settings.py it will be reinitialized every time the settings module is imported, correct?</p>
| 9 | 2009-07-12T21:19:42Z | 1,117,692 | <p>settings.py is for Django settings; it's fine to put your own settings in there, but using it for arbitrary non-configuration data structures isn't good practice.</p>
<p>Just put it in the module it logically belongs to, and it'll be run just once per instance. If you want to guarantee that the module is loaded on startup and not on first use later on, import that module from your top-level <code>__init__.py</code> to force it to be loaded immediately.</p>
| 14 | 2009-07-13T04:23:30Z | [
"python",
"django"
] |
lucene / python | 1,116,967 | <p>Can I use lucene directly from python, preferably without using a binary module?</p>
<p>I am interested mainly in read access -- being able to perform queries from python over existing lucene indexes.</p>
| 5 | 2009-07-12T21:29:23Z | 1,116,984 | <p>You can't use Lucene itself from CPython without using a binary module, no.</p>
<p>You could use it directly from <a href="http://jython.org/">Jython</a>, or you could use a Python port of Lucene, eg. <a href="http://pypi.python.org/pypi/Lupy/0.2.1">Lupy</a> (though Lupy is no longer under development).</p>
<p>If you're prepared to relax your non-binary requirement, <a href="http://lucene.apache.org/pylucene/">PyLucene</a> is a wrapper that embeds Java Lucene into Python.</p>
<p>This similar question offers some options: <a href="http://stackoverflow.com/questions/438315/is-there-a-pure-python-lucene">Is there a pure Python Lucene?</a></p>
| 8 | 2009-07-12T21:33:35Z | [
"python",
"lucene"
] |
lucene / python | 1,116,967 | <p>Can I use lucene directly from python, preferably without using a binary module?</p>
<p>I am interested mainly in read access -- being able to perform queries from python over existing lucene indexes.</p>
| 5 | 2009-07-12T21:29:23Z | 1,116,989 | <p><a href="http://lucene.apache.org/pylucene/">PyLucene</a> is a Python wrapper around Lucene. Therefore, you have to install Lucene as well, and its installation may be a bit complex (especially on Windows!)</p>
| 7 | 2009-07-12T21:34:49Z | [
"python",
"lucene"
] |
Is there any way to get the repeating decimal section of a fraction in Python? | 1,116,990 | <p>I'm working with fractions using Python's decimal module and I'd like to get just the repeating part of a certain fraction. For example: if I had 1/3 I'd like to get 3, if I had 1/7 I'd like to get 142857. Is there any standard function to do this?</p>
| 3 | 2009-07-12T21:35:10Z | 1,117,033 | <p>Find the first number of the form 10**k - 1 that divides exactly by the denominator of the fraction, divide it by the denominator and multiply by the numerator and you get your repeating part.</p>
| 0 | 2009-07-12T21:51:17Z | [
"python",
"decimal",
"precision"
] |
Is there any way to get the repeating decimal section of a fraction in Python? | 1,116,990 | <p>I'm working with fractions using Python's decimal module and I'd like to get just the repeating part of a certain fraction. For example: if I had 1/3 I'd like to get 3, if I had 1/7 I'd like to get 142857. Is there any standard function to do this?</p>
| 3 | 2009-07-12T21:35:10Z | 1,117,059 | <p>Since giving the answer could be a spoiler for project euler (which is generally not done here at stackoverflow), I'd like to give this hint: read <a href="http://en.wikipedia.org/wiki/Repeating%5Fdecimal">this</a> (section 1.2 should ring a bell).</p>
| 5 | 2009-07-12T22:07:56Z | [
"python",
"decimal",
"precision"
] |
Is there any way to get the repeating decimal section of a fraction in Python? | 1,116,990 | <p>I'm working with fractions using Python's decimal module and I'd like to get just the repeating part of a certain fraction. For example: if I had 1/3 I'd like to get 3, if I had 1/7 I'd like to get 142857. Is there any standard function to do this?</p>
| 3 | 2009-07-12T21:35:10Z | 20,875,524 | <p>I know this question was a long time ago, but I figured people probably still search something like this so I figured I'd mention some things to keep in mind when doing it since I tried coding and eventually changed my mind to using long division and finding where repetition occurs when you get a remainder after dividing into it. I was actually originally trying to use the method suggested by Ants Aasma.</p>
<p>I was trying to get output such as this for 1/7, since my function was trying to output a string which could be used as an answer to a question;
"0.142857 142857..."</p>
<p>Decimals such as 1/7 are very easily found using the method provided by Ants Aasma, however it gets painful when you try something such as 1/35 - this cant be divided into a number full of 9s. First of all, any denominators will have to have any factors of 10 divided out - i.e. divide out all the 5s and 2s, converting a fraction such as 1/35 to 0.2/7</p>
<p>For a fraction such as 1/70, I believe the best way is to actually find 1/7 and then stick a 0 right after the decimal place. For 1/35, you would convert it to 0.2/7 and then to 2/7 with a 0 between the repeating part and the decimal place.</p>
<p>Just a couple of tips to keep in mind if using Ants Aasma's suggested method.</p>
| 0 | 2014-01-02T02:39:37Z | [
"python",
"decimal",
"precision"
] |
How to package a command line Python script | 1,117,041 | <p>I've created a python script that's intended to be used from the command line. How do I go about packaging it? This is my first python package and I've read a bit about setuptools, but I'm still not sure the best way to do this.</p>
<p><hr /></p>
<h1>Solution</h1>
<p>I ended up using <a href="http://peak.telecommunity.com/DevCenter/setuptools">setup.py</a> with the key configurations noted below:</p>
<pre><code>setup(
....
entry_points="""
[console_scripts]
mycommand = mypackage.mymodule:main
""",
....
)
</code></pre>
<p>Here's a good <a href="http://github.com/jsmits/github-cli/blob/c5b4166976bbf94fc3f929cc369ce094bc02b88e/setup.py">example</a> in context.</p>
| 25 | 2009-07-12T21:55:09Z | 1,117,081 | <p>What do you mean by packaging? If it is a single script to be run on a box that already has python installed, you just need to put a <a href="http://en.wikipedia.org/wiki/Shebang%5F%28Unix%29" rel="nofollow">shebang</a> into the first line of the file and that's it.</p>
<p>If you want it to be executed under Windows or on a box without python, though, you will need something external, like <a href="http://www.pyinstaller.org/" rel="nofollow">pyinstaller</a>.</p>
<p>If your question is about where to put configuration/data files, you'll need to work platform-dependently (like writing into the <a href="http://python.active-venture.com/lib/module--winreg.html" rel="nofollow">registry</a> or the <a href="http://ubuntuforums.org/showthread.php?t=820043" rel="nofollow">home folder</a>), as far as I know.</p>
| 2 | 2009-07-12T22:19:30Z | [
"python",
"command-line",
"packaging"
] |
How to package a command line Python script | 1,117,041 | <p>I've created a python script that's intended to be used from the command line. How do I go about packaging it? This is my first python package and I've read a bit about setuptools, but I'm still not sure the best way to do this.</p>
<p><hr /></p>
<h1>Solution</h1>
<p>I ended up using <a href="http://peak.telecommunity.com/DevCenter/setuptools">setup.py</a> with the key configurations noted below:</p>
<pre><code>setup(
....
entry_points="""
[console_scripts]
mycommand = mypackage.mymodule:main
""",
....
)
</code></pre>
<p>Here's a good <a href="http://github.com/jsmits/github-cli/blob/c5b4166976bbf94fc3f929cc369ce094bc02b88e/setup.py">example</a> in context.</p>
| 25 | 2009-07-12T21:55:09Z | 1,117,528 | <p>@Zach, given your clarification in your comment to @soulmerge's answer, it looks like what you need is to write a setup.py as per the instructions regarding the <a href="http://docs.python.org/distutils/index.html#distutils-index" rel="nofollow">distutils</a> -- <a href="http://docs.python.org/distutils/packageindex.html" rel="nofollow">here</a> in particular is how you register on pypi, and <a href="http://docs.python.org/distutils/uploading.html" rel="nofollow">here</a> on how to upload to pypi once you are registrered -- and possibly (if you need some extra functionality wrt what the distutils supply on their own) add setuptools, of which <code>easy_install</code> is part, via the instructions <a href="http://peak.telecommunity.com/dist/ez%5Fsetup.py" rel="nofollow">here</a>.</p>
| 3 | 2009-07-13T02:38:15Z | [
"python",
"command-line",
"packaging"
] |
How to package a command line Python script | 1,117,041 | <p>I've created a python script that's intended to be used from the command line. How do I go about packaging it? This is my first python package and I've read a bit about setuptools, but I'm still not sure the best way to do this.</p>
<p><hr /></p>
<h1>Solution</h1>
<p>I ended up using <a href="http://peak.telecommunity.com/DevCenter/setuptools">setup.py</a> with the key configurations noted below:</p>
<pre><code>setup(
....
entry_points="""
[console_scripts]
mycommand = mypackage.mymodule:main
""",
....
)
</code></pre>
<p>Here's a good <a href="http://github.com/jsmits/github-cli/blob/c5b4166976bbf94fc3f929cc369ce094bc02b88e/setup.py">example</a> in context.</p>
| 25 | 2009-07-12T21:55:09Z | 7,065,072 | <p>Rather than using setuptools non standard way of proceeding, it is possible to directly rely on <code>distutils</code> setup's function, using the <code>scripts</code> argument, as stated here: <a href="http://docs.python.org/distutils/setupscript.html#installing-scripts" rel="nofollow">http://docs.python.org/distutils/setupscript.html#installing-scripts</a></p>
<pre><code>from distutils import setup
setup(
...,
scripts=['path/to/your/script',],
...
)
</code></pre>
<p>It allows you to stay compatible a) with all python versions and b) not having to rely on a setuptools as an external dependency.</p>
| 3 | 2011-08-15T12:46:26Z | [
"python",
"command-line",
"packaging"
] |
How to package a command line Python script | 1,117,041 | <p>I've created a python script that's intended to be used from the command line. How do I go about packaging it? This is my first python package and I've read a bit about setuptools, but I'm still not sure the best way to do this.</p>
<p><hr /></p>
<h1>Solution</h1>
<p>I ended up using <a href="http://peak.telecommunity.com/DevCenter/setuptools">setup.py</a> with the key configurations noted below:</p>
<pre><code>setup(
....
entry_points="""
[console_scripts]
mycommand = mypackage.mymodule:main
""",
....
)
</code></pre>
<p>Here's a good <a href="http://github.com/jsmits/github-cli/blob/c5b4166976bbf94fc3f929cc369ce094bc02b88e/setup.py">example</a> in context.</p>
| 25 | 2009-07-12T21:55:09Z | 22,440,072 | <p>Last month, I have written an article answering exactly your question. You can find it here: <a href="http://gehrcke.de/2014/02/distributing-a-python-command-line-application/" rel="nofollow">http://gehrcke.de/2014/02/distributing-a-python-command-line-application/</a></p>
<p>There, I am using only currently recommended methods (twine, pure setuptools instead of distutils, the <code>console_scripts</code> key in the <code>entry_points</code> dictionary, ...), which work for Python 2 and 3.</p>
| 1 | 2014-03-16T17:12:51Z | [
"python",
"command-line",
"packaging"
] |
How to package a command line Python script | 1,117,041 | <p>I've created a python script that's intended to be used from the command line. How do I go about packaging it? This is my first python package and I've read a bit about setuptools, but I'm still not sure the best way to do this.</p>
<p><hr /></p>
<h1>Solution</h1>
<p>I ended up using <a href="http://peak.telecommunity.com/DevCenter/setuptools">setup.py</a> with the key configurations noted below:</p>
<pre><code>setup(
....
entry_points="""
[console_scripts]
mycommand = mypackage.mymodule:main
""",
....
)
</code></pre>
<p>Here's a good <a href="http://github.com/jsmits/github-cli/blob/c5b4166976bbf94fc3f929cc369ce094bc02b88e/setup.py">example</a> in context.</p>
| 25 | 2009-07-12T21:55:09Z | 32,006,336 | <p>For those who are beginners in Python Packaging, I suggest going through this <a href="http://www.scotttorborg.com/python-packaging/index.html" rel="nofollow">Python Packaging Tutorial</a>.</p>
<p>Note about the tutorial:</p>
<blockquote>
<p>At this time, this documentation focuses on Python 2.x only, and may not be as applicable to packages targeted to Python 3.x</p>
</blockquote>
| 0 | 2015-08-14T09:07:31Z | [
"python",
"command-line",
"packaging"
] |
Error running twisted application | 1,117,072 | <p>I am trying to run a simple twisted application echo bot that metajack blogged about, everything looks like it is going to load fine, but at the very end I get an error:</p>
<pre><code>2009/07/12 15:46 -0600 [-] ImportError: cannot import name toResponse
2009/07/12 15:46 -0600 [-] Failed to load application: cannot import name toResponse
</code></pre>
<p>Any ideas on what might be causing this?</p>
<p>I've not played with wokkel/twisted/python at all and dont know where to start to look.</p>
<p>It is worth nothing that I've tried another wokkel/twisted app and got this very same error.</p>
| 1 | 2009-07-12T22:12:55Z | 1,117,077 | <p>There's not really enough information to go on, but if I had to guess, I'd say that you've given your program the same name as one of the modules that it relies on. Try renaming it to <code>anthonys_echo_bot.py</code> and re-running it. Do this:</p>
<pre><code>rm *.pyc
</code></pre>
<p>in the directory in which you're running it first.</p>
<p>If that doesn't help, you'll need to track down the piece of code that's trying import <code>toResponse</code> - is that all the error you get? No traceback, pointing to lines of code?</p>
| 1 | 2009-07-12T22:15:59Z | [
"python",
"twisted"
] |
Error running twisted application | 1,117,072 | <p>I am trying to run a simple twisted application echo bot that metajack blogged about, everything looks like it is going to load fine, but at the very end I get an error:</p>
<pre><code>2009/07/12 15:46 -0600 [-] ImportError: cannot import name toResponse
2009/07/12 15:46 -0600 [-] Failed to load application: cannot import name toResponse
</code></pre>
<p>Any ideas on what might be causing this?</p>
<p>I've not played with wokkel/twisted/python at all and dont know where to start to look.</p>
<p>It is worth nothing that I've tried another wokkel/twisted app and got this very same error.</p>
| 1 | 2009-07-12T22:12:55Z | 1,117,217 | <p>This error is caused because I have an outdated version of Twisted. Off to find a way to update twisted itself as the installer doesnt seem to be doing the trick.</p>
| 2 | 2009-07-12T23:42:05Z | [
"python",
"twisted"
] |
does python have conversion operators? | 1,117,149 | <p>I don't think so, but I thought I'd ask just in case. For example, for use in a class that encapsulates an int:</p>
<pre><code>i = IntContainer(3)
i + 5
</code></pre>
<p>And I'm not just interested in this int example, I was looking for something clean and general, not overriding every int and string method.</p>
<p>Thanks, sunqiang. That's just what I wanted. I didn't realize you could subclass these immutable types (coming from C++). </p>
<pre><code>class IntContainer(int):
def __init__(self,i):
#do stuff here
self.f = 4
def MultiplyBy4(self):
#some member function
self *= self.f
return self
print 3+IntContainer(3).MultiplyBy4()
</code></pre>
| 5 | 2009-07-12T22:59:00Z | 1,117,157 | <p>Is this what you need?</p>
<pre><code>In [1]: class IntContainer(object):
...: def __init__(self, val):
...: self.val = val
...: def __add__(self, val):
...: return self.val + val
...: def __radd__(self, val):
...: return self.val + val
...:
...:
In [2]: i = IntContainer(3)
In [3]: i + 5
Out[3]: 8
In [4]:
</code></pre>
| 3 | 2009-07-12T23:03:49Z | [
"python",
"operators"
] |
does python have conversion operators? | 1,117,149 | <p>I don't think so, but I thought I'd ask just in case. For example, for use in a class that encapsulates an int:</p>
<pre><code>i = IntContainer(3)
i + 5
</code></pre>
<p>And I'm not just interested in this int example, I was looking for something clean and general, not overriding every int and string method.</p>
<p>Thanks, sunqiang. That's just what I wanted. I didn't realize you could subclass these immutable types (coming from C++). </p>
<pre><code>class IntContainer(int):
def __init__(self,i):
#do stuff here
self.f = 4
def MultiplyBy4(self):
#some member function
self *= self.f
return self
print 3+IntContainer(3).MultiplyBy4()
</code></pre>
| 5 | 2009-07-12T22:59:00Z | 1,117,163 | <p>This should do what you need:</p>
<pre><code>class IntContainer(object):
def __init__(self, x):
self.x = x
def __add__(self, other):
# do some type checking on other
return self.x + other
def __radd__(self, other):
# do some type checking on other
return self.x + other
</code></pre>
<p>Output:</p>
<pre><code>In [6]: IntContainer(3) + 6
Out[6]: 9
In [7]: 6 + IntContainer(3)
Out[7]: 9
</code></pre>
<p>For more information search for "radd" in the following docs:</p>
<ul>
<li><a href="http://docs.python.org/reference/datamodel.html#special-method-names">http://docs.python.org/reference/datamodel.html#special-method-names</a></li>
</ul>
<p>You'll find other such methods for "right addition", "right subtraction", etc.</p>
<p>Here's another link covering the same operators:</p>
<ul>
<li><a href="http://www.siafoo.net/article/57#reversed-binary-operations">http://www.siafoo.net/article/57#reversed-binary-operations</a></li>
</ul>
<p>By the way, Python does have casting operators:</p>
<ul>
<li><a href="http://www.siafoo.net/article/57#casts">http://www.siafoo.net/article/57#casts</a></li>
</ul>
<p>But, they won't accomplish what you need in your example (basically because methods don't have any type annotation for parameters, so there's no good way to cast implicitly). So you can do this:</p>
<pre><code>class IntContainer2(object):
def __init__(self, x):
self.x = x
def __int__(self):
return self.x
ic = IntContainer2(3)
print int(ic) + 6
print 6 + int(ic)
</code></pre>
<p>But this will fail:</p>
<pre><code>print ic + 6 # error: no implicit coercion
</code></pre>
| 10 | 2009-07-12T23:09:13Z | [
"python",
"operators"
] |
does python have conversion operators? | 1,117,149 | <p>I don't think so, but I thought I'd ask just in case. For example, for use in a class that encapsulates an int:</p>
<pre><code>i = IntContainer(3)
i + 5
</code></pre>
<p>And I'm not just interested in this int example, I was looking for something clean and general, not overriding every int and string method.</p>
<p>Thanks, sunqiang. That's just what I wanted. I didn't realize you could subclass these immutable types (coming from C++). </p>
<pre><code>class IntContainer(int):
def __init__(self,i):
#do stuff here
self.f = 4
def MultiplyBy4(self):
#some member function
self *= self.f
return self
print 3+IntContainer(3).MultiplyBy4()
</code></pre>
| 5 | 2009-07-12T22:59:00Z | 1,117,174 | <p>You won't get conversion operators like in C++ because Python does not have this kind of strong static type system. The only automatic conversion operators are those which handle default numeric values (int/float); they are predefined in the language and cannot be changed.</p>
<p>Type "conversion" is usually done by constructors/factories. You can then overload standard methods like <code>__add__</code> to make it work more like other classes.</p>
| 3 | 2009-07-12T23:13:43Z | [
"python",
"operators"
] |
does python have conversion operators? | 1,117,149 | <p>I don't think so, but I thought I'd ask just in case. For example, for use in a class that encapsulates an int:</p>
<pre><code>i = IntContainer(3)
i + 5
</code></pre>
<p>And I'm not just interested in this int example, I was looking for something clean and general, not overriding every int and string method.</p>
<p>Thanks, sunqiang. That's just what I wanted. I didn't realize you could subclass these immutable types (coming from C++). </p>
<pre><code>class IntContainer(int):
def __init__(self,i):
#do stuff here
self.f = 4
def MultiplyBy4(self):
#some member function
self *= self.f
return self
print 3+IntContainer(3).MultiplyBy4()
</code></pre>
| 5 | 2009-07-12T22:59:00Z | 1,117,456 | <p>sometimes maybe just subclass from int directly is enough. then <code>__add__</code> and <code>__radd__</code> need not costuming.</p>
<pre><code>class IntContainer(int):
pass
i = IntContainer(3)
print i + 5 # 8
print 4 + i # 7
class StrContainer(str):
pass
s = StrContainer(3)
print s + '5' # 35
print '4' + s # 43
</code></pre>
| 2 | 2009-07-13T01:50:25Z | [
"python",
"operators"
] |
How to find the number of parameters to a Python function from C? | 1,117,164 | <p>I'm using the Python C API to call Python functions from my application. I'd like to present a list of functions that could be called and would like to be able to limit this list to just the ones with the expected number of parameters.</p>
<p>I'm happy that I can walk the dictionary to extract a list of functions and use <code>PyCallable_Check</code> to find out if they're callable, but I'm not sure how I can find out how many parameters each function is expecting?</p>
<p>I've found one technique involving Boost::Python, but would rather not add that for what (I hope!) will be a minor addition.</p>
<p>Thanks :)</p>
| 3 | 2009-07-12T23:09:18Z | 1,117,179 | <p><a href="http://mail.python.org/pipermail/cplusplus-sig/2008-February/013027.html" rel="nofollow">Maybe this is helpful?</a> (not tested, there could be relevant pieces of information along this thread)...</p>
| 1 | 2009-07-12T23:18:43Z | [
"python",
"c"
] |
How to find the number of parameters to a Python function from C? | 1,117,164 | <p>I'm using the Python C API to call Python functions from my application. I'd like to present a list of functions that could be called and would like to be able to limit this list to just the ones with the expected number of parameters.</p>
<p>I'm happy that I can walk the dictionary to extract a list of functions and use <code>PyCallable_Check</code> to find out if they're callable, but I'm not sure how I can find out how many parameters each function is expecting?</p>
<p>I've found one technique involving Boost::Python, but would rather not add that for what (I hope!) will be a minor addition.</p>
<p>Thanks :)</p>
| 3 | 2009-07-12T23:09:18Z | 1,117,518 | <p>Your C code can call <a href="http://docs.python.org/library/inspect.html?highlight=getargspec#inspect.getargspec" rel="nofollow">inspect.getargspec</a> just like any Python code would (e.g. via <a href="http://docs.python.org/c-api/object.html?highlight=pyobject%5Fcallmethod#PyObject%5FCallMethod" rel="nofollow">PyObject_CallMethod</a> or other equivalent ways) and get all the scoop about the signature of each function or other callable that it may care about.</p>
| 0 | 2009-07-13T02:30:21Z | [
"python",
"c"
] |
How to find the number of parameters to a Python function from C? | 1,117,164 | <p>I'm using the Python C API to call Python functions from my application. I'd like to present a list of functions that could be called and would like to be able to limit this list to just the ones with the expected number of parameters.</p>
<p>I'm happy that I can walk the dictionary to extract a list of functions and use <code>PyCallable_Check</code> to find out if they're callable, but I'm not sure how I can find out how many parameters each function is expecting?</p>
<p>I've found one technique involving Boost::Python, but would rather not add that for what (I hope!) will be a minor addition.</p>
<p>Thanks :)</p>
| 3 | 2009-07-12T23:09:18Z | 1,117,735 | <p>Okay, so in the end I've discovered how to do it. User-defined Python functions have a member called <code>func_code</code> (in Python 3.0+ it's <code>__code__</code>), which itself has a member <code>co_argcount</code>, which is presumably what Boost::Python extracts in the example given by Christophe.</p>
<p>The code I'm using looks like this (it's heavily based on a documentation example of how to walk a Python dictionary):</p>
<pre><code> PyObject *key, *value;
int pos = 0;
while(PyDict_Next(pyDictionary, &pos, &key, &value)) {
if(PyCallable_Check(value)) {
PyObject* fc = PyObject_GetAttrString(value, "func_code");
if(fc) {
PyObject* ac = PyObject_GetAttrString(fc, "co_argcount");
if(ac) {
const int count = PyInt_AsLong(ac);
// we now have the argument count, do something with this function
Py_DECREF(ac);
}
Py_DECREF(fc);
}
}
}
</code></pre>
<p>Thanks anyway - that thread did indeed lead me in the right direction :)</p>
| 3 | 2009-07-13T04:48:57Z | [
"python",
"c"
] |
How to update the twisted framework | 1,117,255 | <p>I can see from the latest 8.2 (almost 1200 lines of code) twisted that I am missing something:
<a href="http://twistedmatrix.com/trac/browser/trunk/twisted/words/protocols/jabber/xmlstream.py" rel="nofollow">http://twistedmatrix.com/trac/browser/trunk/twisted/words/protocols/jabber/xmlstream.py</a></p>
<p>My copy (697 lines from 3 years ago) is in:
/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/twisted/words/protocols/jabber/xmlstream.py</p>
<p>I ran the mac installer found on the website, all looked like it installed fine, but obviously something I am missing:
<a href="http://twistedmatrix.com/trac/wiki/Downloads" rel="nofollow">http://twistedmatrix.com/trac/wiki/Downloads</a></p>
<p>Can someone tell me how to update twisted properly on my mac?</p>
| 3 | 2009-07-12T23:59:35Z | 1,117,318 | <p>You can download that file you mentioned by scrolling to the bottom and click "Download in other formats"</p>
<p>Otherwise just do svn update.</p>
| 1 | 2009-07-13T00:35:53Z | [
"python",
"twisted"
] |
How to update the twisted framework | 1,117,255 | <p>I can see from the latest 8.2 (almost 1200 lines of code) twisted that I am missing something:
<a href="http://twistedmatrix.com/trac/browser/trunk/twisted/words/protocols/jabber/xmlstream.py" rel="nofollow">http://twistedmatrix.com/trac/browser/trunk/twisted/words/protocols/jabber/xmlstream.py</a></p>
<p>My copy (697 lines from 3 years ago) is in:
/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/twisted/words/protocols/jabber/xmlstream.py</p>
<p>I ran the mac installer found on the website, all looked like it installed fine, but obviously something I am missing:
<a href="http://twistedmatrix.com/trac/wiki/Downloads" rel="nofollow">http://twistedmatrix.com/trac/wiki/Downloads</a></p>
<p>Can someone tell me how to update twisted properly on my mac?</p>
| 3 | 2009-07-12T23:59:35Z | 1,124,217 | <p>The answer was hidden away here:
<a href="http://twistedmatrix.com/trac/wiki/FrequentlyAskedQuestions#WhyamIgettingImportErrorsforTwistedsubpackagesonOSX10.5" rel="nofollow">http://twistedmatrix.com/trac/wiki/FrequentlyAskedQuestions#WhyamIgettingImportErrorsforTwistedsubpackagesonOSX10.5</a></p>
<p>Not really clear on exactly how/where to fix the issue though.</p>
<p>After some digging I was able to solve it with this: </p>
<p>From the command prompt type: pico ~/.bash_profile
Add to the top of that file: export PYTHONPATH=~/Library/Python/2.5/site-packages/</p>
<p>Save and exit the file and you will finally be running the latest and greatest version twisted. (assuming that you have already downloaded and installed it from the twisted site)</p>
| 1 | 2009-07-14T08:47:21Z | [
"python",
"twisted"
] |
How to update the twisted framework | 1,117,255 | <p>I can see from the latest 8.2 (almost 1200 lines of code) twisted that I am missing something:
<a href="http://twistedmatrix.com/trac/browser/trunk/twisted/words/protocols/jabber/xmlstream.py" rel="nofollow">http://twistedmatrix.com/trac/browser/trunk/twisted/words/protocols/jabber/xmlstream.py</a></p>
<p>My copy (697 lines from 3 years ago) is in:
/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/twisted/words/protocols/jabber/xmlstream.py</p>
<p>I ran the mac installer found on the website, all looked like it installed fine, but obviously something I am missing:
<a href="http://twistedmatrix.com/trac/wiki/Downloads" rel="nofollow">http://twistedmatrix.com/trac/wiki/Downloads</a></p>
<p>Can someone tell me how to update twisted properly on my mac?</p>
| 3 | 2009-07-12T23:59:35Z | 1,257,261 | <p>Try using <code>virtualenv</code> and <code>pip</code> (<code>sudo easy_install virtualenv pip</code>), which are great ways to avoid the dependency hell that you are experiencing.</p>
<p>With <code>virtualenv</code> you can create isolated Python environments, and then using <code>pip</code> you can directly install new packages into you <code>virtualenv</code>s.</p>
<p>Here is a complete example:</p>
<pre><code>
#create fresh virtualenv, void of old packages, and install latest Twisted
virtualenv --no-site-packages twisted_env
pip -E twisted_env install -U twisted
#now activate the virtualenv
cd twisted_env
source bin/activate
#test to see you have latest Twisted:
python -c "import twisted; print twisted.__version__"
</code></pre>
| 16 | 2009-08-10T21:15:38Z | [
"python",
"twisted"
] |
How do I tell a Python script (cygwin) to work in current (or relative) directories? | 1,117,414 | <p>I have lots of directories with text files written using (g)vim, and I have written a handful of utilities that I find useful in Python. I start off the utilities with a pound-bang-/usr/bin/env python line in order to use the Python that is installed under cygwin. I would like to type commands like this:</p>
<p>%cd ~/SomeBook</p>
<p>%which pythonUtil</p>
<p>/usr/local/bin/pythonUtil</p>
<p>%pythonUtil ./infile.txt ./outfile.txt</p>
<p>(or % pythonUtil someRelPath/infile.txt somePossiblyDifferentRelPath/outfile.txt)</p>
<p>pythonUtil: Found infile.txt; Writing outfile.txt; Done (or some such, if anything)</p>
<p>However, my pythonUtil programs keep telling me that they can't find infile.txt. If I copy the utility into the current working directory, all is well, but then I have copies of my utilities littering the landscape. What should I be doing?</p>
<p>Yet Another Edit: To summarize --- what I wanted was os.path.abspath('filename'). That returns the absolute pathname as a string, and then all ambiguity has been removed.</p>
<p>BUT: IF the Python being used is the one installed under cygwin, THEN the absolute pathname will be a CYGWIN-relative pathname, like /home/someUser/someDir/someFile.txt. HOWEVER, IF the Python has been installed under Windows (and is here being called from a cygwin terminal commandline), THEN the absolute pathname will be the complete Windows path, from 'drive' on down, like D:\cygwin\home\someUser\someDir\someFile.txt.</p>
<p>Moral: Don't expect the cygwin Python to generate a Windows-complete absolute pathname for a file not rooted at /; it's beyond its event horizon. However, you can reach out to any file on a WinXP system with the cygwin-python if you specify the file's path using the "/cygdrive/driveLetter" leadin convention.</p>
<p>Remark: Don't use '\'s for separators in the WinXP path on the cygwin commandline; use '/'s and trust the snake. No idea why, but some separators may be dropped and the path may be modified to include extra levels, such as "Documents and Settings\someUser" and other Windows nonsense.</p>
<p>Thanks to the responders for shoving me in the right direction.</p>
| 1 | 2009-07-13T01:29:44Z | 1,117,425 | <p>Look at os.getcwd:</p>
<ul>
<li><a href="http://docs.python.org/library/os.html#os-file-dir" rel="nofollow">http://docs.python.org/library/os.html#os-file-dir</a></li>
</ul>
<p>Edit: For relative paths, please take a look at the os.path module:</p>
<ul>
<li><a href="http://docs.python.org/library/os.path.html" rel="nofollow">http://docs.python.org/library/os.path.html</a></li>
</ul>
<p>in particular, os.path.join and os.path.normpath. For instance:</p>
<pre><code>import os
print os.path.normpath(os.path.join(os.getcwd(), '../AnotherBook/Chap2.txt'))
</code></pre>
| 4 | 2009-07-13T01:35:42Z | [
"python",
"filesystems",
"cygwin",
"path",
"utilities"
] |
How do I tell a Python script (cygwin) to work in current (or relative) directories? | 1,117,414 | <p>I have lots of directories with text files written using (g)vim, and I have written a handful of utilities that I find useful in Python. I start off the utilities with a pound-bang-/usr/bin/env python line in order to use the Python that is installed under cygwin. I would like to type commands like this:</p>
<p>%cd ~/SomeBook</p>
<p>%which pythonUtil</p>
<p>/usr/local/bin/pythonUtil</p>
<p>%pythonUtil ./infile.txt ./outfile.txt</p>
<p>(or % pythonUtil someRelPath/infile.txt somePossiblyDifferentRelPath/outfile.txt)</p>
<p>pythonUtil: Found infile.txt; Writing outfile.txt; Done (or some such, if anything)</p>
<p>However, my pythonUtil programs keep telling me that they can't find infile.txt. If I copy the utility into the current working directory, all is well, but then I have copies of my utilities littering the landscape. What should I be doing?</p>
<p>Yet Another Edit: To summarize --- what I wanted was os.path.abspath('filename'). That returns the absolute pathname as a string, and then all ambiguity has been removed.</p>
<p>BUT: IF the Python being used is the one installed under cygwin, THEN the absolute pathname will be a CYGWIN-relative pathname, like /home/someUser/someDir/someFile.txt. HOWEVER, IF the Python has been installed under Windows (and is here being called from a cygwin terminal commandline), THEN the absolute pathname will be the complete Windows path, from 'drive' on down, like D:\cygwin\home\someUser\someDir\someFile.txt.</p>
<p>Moral: Don't expect the cygwin Python to generate a Windows-complete absolute pathname for a file not rooted at /; it's beyond its event horizon. However, you can reach out to any file on a WinXP system with the cygwin-python if you specify the file's path using the "/cygdrive/driveLetter" leadin convention.</p>
<p>Remark: Don't use '\'s for separators in the WinXP path on the cygwin commandline; use '/'s and trust the snake. No idea why, but some separators may be dropped and the path may be modified to include extra levels, such as "Documents and Settings\someUser" and other Windows nonsense.</p>
<p>Thanks to the responders for shoving me in the right direction.</p>
| 1 | 2009-07-13T01:29:44Z | 1,117,427 | <p>What happens when you type "ls"? Do you see "infile.txt" listed there?</p>
| 0 | 2009-07-13T01:36:45Z | [
"python",
"filesystems",
"cygwin",
"path",
"utilities"
] |
How do I tell a Python script (cygwin) to work in current (or relative) directories? | 1,117,414 | <p>I have lots of directories with text files written using (g)vim, and I have written a handful of utilities that I find useful in Python. I start off the utilities with a pound-bang-/usr/bin/env python line in order to use the Python that is installed under cygwin. I would like to type commands like this:</p>
<p>%cd ~/SomeBook</p>
<p>%which pythonUtil</p>
<p>/usr/local/bin/pythonUtil</p>
<p>%pythonUtil ./infile.txt ./outfile.txt</p>
<p>(or % pythonUtil someRelPath/infile.txt somePossiblyDifferentRelPath/outfile.txt)</p>
<p>pythonUtil: Found infile.txt; Writing outfile.txt; Done (or some such, if anything)</p>
<p>However, my pythonUtil programs keep telling me that they can't find infile.txt. If I copy the utility into the current working directory, all is well, but then I have copies of my utilities littering the landscape. What should I be doing?</p>
<p>Yet Another Edit: To summarize --- what I wanted was os.path.abspath('filename'). That returns the absolute pathname as a string, and then all ambiguity has been removed.</p>
<p>BUT: IF the Python being used is the one installed under cygwin, THEN the absolute pathname will be a CYGWIN-relative pathname, like /home/someUser/someDir/someFile.txt. HOWEVER, IF the Python has been installed under Windows (and is here being called from a cygwin terminal commandline), THEN the absolute pathname will be the complete Windows path, from 'drive' on down, like D:\cygwin\home\someUser\someDir\someFile.txt.</p>
<p>Moral: Don't expect the cygwin Python to generate a Windows-complete absolute pathname for a file not rooted at /; it's beyond its event horizon. However, you can reach out to any file on a WinXP system with the cygwin-python if you specify the file's path using the "/cygdrive/driveLetter" leadin convention.</p>
<p>Remark: Don't use '\'s for separators in the WinXP path on the cygwin commandline; use '/'s and trust the snake. No idea why, but some separators may be dropped and the path may be modified to include extra levels, such as "Documents and Settings\someUser" and other Windows nonsense.</p>
<p>Thanks to the responders for shoving me in the right direction.</p>
| 1 | 2009-07-13T01:29:44Z | 1,117,450 | <pre><code>os.chdir(my_dir)
</code></pre>
<p>or</p>
<pre><code>os.chdir(os.getcwd())
</code></pre>
| 0 | 2009-07-13T01:46:58Z | [
"python",
"filesystems",
"cygwin",
"path",
"utilities"
] |
Efficiently importing modules in Django views | 1,117,451 | <p>I was wondering - how do people handle importing large numbers of commonly used modules within django views? And whats the best method to do this efficiently?</p>
<p>For instance, I've got some views like,</p>
<pre><code>admin_views.py
search_views.py
.
.
</code></pre>
<p>and from what I've seen, every one of them needs to use HttpResponse or other such commonly used modules. Moreover, some of them need things like BeautifulSoup, and others need other things (md5, auth, et al).</p>
<p>What I did when starting the project was to make an <code>include_all.py</code> which contained most of my common imports, and then added these specific things in the <em>view</em> itself. So, I had something like,</p>
<p><strong>admin_views.py</strong></p>
<pre><code>from include_all import *
...
[list of specific module imports for admin]
...
</code></pre>
<p><strong>search_views.py</strong> </p>
<pre><code>from include_all import *
...
[list of specific module imports for search]
...
</code></pre>
<p>As time progressed, the include_all became a misc file with anything being needed put into it - as a result, a number of views end up importing modules they don't need.</p>
<p>Is this going to affect efficiency? That is, does python (django?) import all the modules once and store/cache them such that any other view needing them doesn't have to import it again? Or is my method of calling this long file a very inefficient one - and I would be better of sticking to individually importing these modules in each view?</p>
<p>Are there any best practices for this sort of thing too?</p>
<p>Thanks!</p>
| 3 | 2009-07-13T01:46:59Z | 1,117,496 | <p>Python itself guarantees that a module is loaded just once (unless <code>reload</code> is explicitly called, which is not the case here): after the first time, <code>import</code> of that module just binds its name directly from <code>sys.modules[themodulename]</code>, an extremely fast operation. So Django does not have to do any further optimization, and neither do you.</p>
<p>Best practice is avoiding <code>from ... import *</code> in production code (making it clearer and more maintainable where each name is coming from, facilitating testing, etc, etc) and importing modules, "individually" as you put it, exactly where they're needed (by possibly binding fewer names that may save a few microseconds and definitely won't waste any, but "explicit is better than implicit" -- clarity, readability, maintainability -- is the main consideration anyway).</p>
| 6 | 2009-07-13T02:14:18Z | [
"python",
"django",
"performance",
"import",
"python-module"
] |
Efficiently importing modules in Django views | 1,117,451 | <p>I was wondering - how do people handle importing large numbers of commonly used modules within django views? And whats the best method to do this efficiently?</p>
<p>For instance, I've got some views like,</p>
<pre><code>admin_views.py
search_views.py
.
.
</code></pre>
<p>and from what I've seen, every one of them needs to use HttpResponse or other such commonly used modules. Moreover, some of them need things like BeautifulSoup, and others need other things (md5, auth, et al).</p>
<p>What I did when starting the project was to make an <code>include_all.py</code> which contained most of my common imports, and then added these specific things in the <em>view</em> itself. So, I had something like,</p>
<p><strong>admin_views.py</strong></p>
<pre><code>from include_all import *
...
[list of specific module imports for admin]
...
</code></pre>
<p><strong>search_views.py</strong> </p>
<pre><code>from include_all import *
...
[list of specific module imports for search]
...
</code></pre>
<p>As time progressed, the include_all became a misc file with anything being needed put into it - as a result, a number of views end up importing modules they don't need.</p>
<p>Is this going to affect efficiency? That is, does python (django?) import all the modules once and store/cache them such that any other view needing them doesn't have to import it again? Or is my method of calling this long file a very inefficient one - and I would be better of sticking to individually importing these modules in each view?</p>
<p>Are there any best practices for this sort of thing too?</p>
<p>Thanks!</p>
| 3 | 2009-07-13T01:46:59Z | 1,117,498 | <p>I guess you could slap your frequently used imports into your __init__.py file.</p>
| 0 | 2009-07-13T02:14:45Z | [
"python",
"django",
"performance",
"import",
"python-module"
] |
Efficiently importing modules in Django views | 1,117,451 | <p>I was wondering - how do people handle importing large numbers of commonly used modules within django views? And whats the best method to do this efficiently?</p>
<p>For instance, I've got some views like,</p>
<pre><code>admin_views.py
search_views.py
.
.
</code></pre>
<p>and from what I've seen, every one of them needs to use HttpResponse or other such commonly used modules. Moreover, some of them need things like BeautifulSoup, and others need other things (md5, auth, et al).</p>
<p>What I did when starting the project was to make an <code>include_all.py</code> which contained most of my common imports, and then added these specific things in the <em>view</em> itself. So, I had something like,</p>
<p><strong>admin_views.py</strong></p>
<pre><code>from include_all import *
...
[list of specific module imports for admin]
...
</code></pre>
<p><strong>search_views.py</strong> </p>
<pre><code>from include_all import *
...
[list of specific module imports for search]
...
</code></pre>
<p>As time progressed, the include_all became a misc file with anything being needed put into it - as a result, a number of views end up importing modules they don't need.</p>
<p>Is this going to affect efficiency? That is, does python (django?) import all the modules once and store/cache them such that any other view needing them doesn't have to import it again? Or is my method of calling this long file a very inefficient one - and I would be better of sticking to individually importing these modules in each view?</p>
<p>Are there any best practices for this sort of thing too?</p>
<p>Thanks!</p>
| 3 | 2009-07-13T01:46:59Z | 1,117,556 | <p>Django isn't CGI (or PHP). Your app is a single (or a few) long-running Python process. It doesn't matter how long it takes to start, each HTTP request will simply call your (already loaded) view functions.</p>
| 0 | 2009-07-13T03:01:43Z | [
"python",
"django",
"performance",
"import",
"python-module"
] |
Cleaning up nested Try/Excepts | 1,117,460 | <p>I've just written a chunk of code that strikes me as being far more nested than is optimal. I'd like advice on how to improve the style of this, particularly so that it conforms more with "Flat is better than nested."</p>
<pre><code>for app in apps:
if app.split('.', 1)[0] == 'zc': #only look for cron in zc apps
try:
a = app + '.cron'
__import__(a)
m = sys.modules[a]
try:
min = m.cron_minute()
for job in min:
k.add_interval_task(job[0], 'minute task', r(M_LB, M_UB),
60*job[1],
kronos.method.threaded, (), ())
except AttributeError: #no minute tasks
pass
try:
hour = m.cron_hour()
for job in hour:
k.add_daytime_task(job[0], 'day task', range(1, 8), None,
(job[1], r(H_LB, H_UB)),
kronos.method.threaded, (), ())
except AttributeError: #no hour tasks
pass
except ImportError: #no cron jobs for this module
pass
</code></pre>
<p>Edit:
<strong>Combining the suggestions from below, here's my rewritten form.</strong></p>
<pre><code>for app in apps:
if app.split('.', 1)[0] != 'zc': #only look for cron in zc apps
continue
try:
a = app + '.cron'
__import__(a)
except ImportError: #no cron jobs for this module, continue to next one
continue
m = sys.modules[a]
if hasattr(m, 'cron_minute'):
min = m.cron_minute()
for job in min:
k.add_interval_task(job[0], 'minute task', r(M_LB, M_UB),
60*job[1],
kronos.method.threaded, (), ())
if hasattr(m, 'cron_hour'):
hour = m.cron_hour()
for job in hour:
k.add_daytime_task(job[0], 'day task', range(1, 8), None,
(job[1], r(H_LB, H_UB)),
kronos.method.threaded, (), ())
</code></pre>
| 4 | 2009-07-13T01:51:59Z | 1,117,473 | <p>You can create a function that performs the main logic, and another function which invokes that function, wrapping it with the try...except statements. Then, in the main application, you can just invoke those function which already handle the exceptions. (Based on the recommendations of the "Clean Code" book).</p>
| 0 | 2009-07-13T02:00:51Z | [
"python"
] |
Cleaning up nested Try/Excepts | 1,117,460 | <p>I've just written a chunk of code that strikes me as being far more nested than is optimal. I'd like advice on how to improve the style of this, particularly so that it conforms more with "Flat is better than nested."</p>
<pre><code>for app in apps:
if app.split('.', 1)[0] == 'zc': #only look for cron in zc apps
try:
a = app + '.cron'
__import__(a)
m = sys.modules[a]
try:
min = m.cron_minute()
for job in min:
k.add_interval_task(job[0], 'minute task', r(M_LB, M_UB),
60*job[1],
kronos.method.threaded, (), ())
except AttributeError: #no minute tasks
pass
try:
hour = m.cron_hour()
for job in hour:
k.add_daytime_task(job[0], 'day task', range(1, 8), None,
(job[1], r(H_LB, H_UB)),
kronos.method.threaded, (), ())
except AttributeError: #no hour tasks
pass
except ImportError: #no cron jobs for this module
pass
</code></pre>
<p>Edit:
<strong>Combining the suggestions from below, here's my rewritten form.</strong></p>
<pre><code>for app in apps:
if app.split('.', 1)[0] != 'zc': #only look for cron in zc apps
continue
try:
a = app + '.cron'
__import__(a)
except ImportError: #no cron jobs for this module, continue to next one
continue
m = sys.modules[a]
if hasattr(m, 'cron_minute'):
min = m.cron_minute()
for job in min:
k.add_interval_task(job[0], 'minute task', r(M_LB, M_UB),
60*job[1],
kronos.method.threaded, (), ())
if hasattr(m, 'cron_hour'):
hour = m.cron_hour()
for job in hour:
k.add_daytime_task(job[0], 'day task', range(1, 8), None,
(job[1], r(H_LB, H_UB)),
kronos.method.threaded, (), ())
</code></pre>
| 4 | 2009-07-13T01:51:59Z | 1,117,477 | <p>Well, the trick here is to figure out if they are broken. That is the <strong><em>handling</em></strong> part of <strong>exception <em>handling</em></strong>. I mean, at least print a warning that states the comment's assumption. Worrying about excessive nesting before the actual handling seems like you are getting ahead of yourself. Worry about being right before being stylish.</p>
| 0 | 2009-07-13T02:01:38Z | [
"python"
] |
Cleaning up nested Try/Excepts | 1,117,460 | <p>I've just written a chunk of code that strikes me as being far more nested than is optimal. I'd like advice on how to improve the style of this, particularly so that it conforms more with "Flat is better than nested."</p>
<pre><code>for app in apps:
if app.split('.', 1)[0] == 'zc': #only look for cron in zc apps
try:
a = app + '.cron'
__import__(a)
m = sys.modules[a]
try:
min = m.cron_minute()
for job in min:
k.add_interval_task(job[0], 'minute task', r(M_LB, M_UB),
60*job[1],
kronos.method.threaded, (), ())
except AttributeError: #no minute tasks
pass
try:
hour = m.cron_hour()
for job in hour:
k.add_daytime_task(job[0], 'day task', range(1, 8), None,
(job[1], r(H_LB, H_UB)),
kronos.method.threaded, (), ())
except AttributeError: #no hour tasks
pass
except ImportError: #no cron jobs for this module
pass
</code></pre>
<p>Edit:
<strong>Combining the suggestions from below, here's my rewritten form.</strong></p>
<pre><code>for app in apps:
if app.split('.', 1)[0] != 'zc': #only look for cron in zc apps
continue
try:
a = app + '.cron'
__import__(a)
except ImportError: #no cron jobs for this module, continue to next one
continue
m = sys.modules[a]
if hasattr(m, 'cron_minute'):
min = m.cron_minute()
for job in min:
k.add_interval_task(job[0], 'minute task', r(M_LB, M_UB),
60*job[1],
kronos.method.threaded, (), ())
if hasattr(m, 'cron_hour'):
hour = m.cron_hour()
for job in hour:
k.add_daytime_task(job[0], 'day task', range(1, 8), None,
(job[1], r(H_LB, H_UB)),
kronos.method.threaded, (), ())
</code></pre>
| 4 | 2009-07-13T01:51:59Z | 1,117,507 | <p>The main problem is that your try clauses are too broad, particularly the outermost one: with that kind of habit, you WILL sooner or later run into a mysterious bug because one of your try/except has accidentally hidden an unexpected exception "bubbling up" from some other function you're calling.</p>
<p>So I'd suggest, instead:</p>
<pre><code>for app in apps:
if app.split('.', 1)[0] != 'zc': #only look for cron in zc apps
continue
try:
a = app + '.cron'
__import__(a)
except ImportError: #no cron jobs for this module
continue
# etc etc
</code></pre>
<p>As an aside, I'm also applying "flat is better than nested" in another way (not dependent on any try/except) which is "if I have nothing more to do on this leg of the loop, continue [i.e. move on to the next leg of the loop] instead of "if I have something to do:" followed by a substantial amount of nested code. I've always preferred this style (of if/continue or if/return) to nested if's in languages that supply functionality such as <code>continue</code> (essentially all modern ones, since C has it;-).</p>
<p>But this is a simple "flat vs nested" style preference, and the meat of the issue is: <em>keep your try clauses small</em>! Worst case, when you just can't simply continue or return in the except clause, you can use try/except/else: put in the try clause only what absolutely MUST be there -- the tiny piece of code that's likely and expected to raise -- and put the rest of the following code (the part that's NOT supposed nor expected to raise) in the else clause. This doesn't change the nesting, but DOES make a huge difference in lowering the risk of accidentally hiding exceptions that are NOT expected!</p>
| 9 | 2009-07-13T02:25:23Z | [
"python"
] |
Cleaning up nested Try/Excepts | 1,117,460 | <p>I've just written a chunk of code that strikes me as being far more nested than is optimal. I'd like advice on how to improve the style of this, particularly so that it conforms more with "Flat is better than nested."</p>
<pre><code>for app in apps:
if app.split('.', 1)[0] == 'zc': #only look for cron in zc apps
try:
a = app + '.cron'
__import__(a)
m = sys.modules[a]
try:
min = m.cron_minute()
for job in min:
k.add_interval_task(job[0], 'minute task', r(M_LB, M_UB),
60*job[1],
kronos.method.threaded, (), ())
except AttributeError: #no minute tasks
pass
try:
hour = m.cron_hour()
for job in hour:
k.add_daytime_task(job[0], 'day task', range(1, 8), None,
(job[1], r(H_LB, H_UB)),
kronos.method.threaded, (), ())
except AttributeError: #no hour tasks
pass
except ImportError: #no cron jobs for this module
pass
</code></pre>
<p>Edit:
<strong>Combining the suggestions from below, here's my rewritten form.</strong></p>
<pre><code>for app in apps:
if app.split('.', 1)[0] != 'zc': #only look for cron in zc apps
continue
try:
a = app + '.cron'
__import__(a)
except ImportError: #no cron jobs for this module, continue to next one
continue
m = sys.modules[a]
if hasattr(m, 'cron_minute'):
min = m.cron_minute()
for job in min:
k.add_interval_task(job[0], 'minute task', r(M_LB, M_UB),
60*job[1],
kronos.method.threaded, (), ())
if hasattr(m, 'cron_hour'):
hour = m.cron_hour()
for job in hour:
k.add_daytime_task(job[0], 'day task', range(1, 8), None,
(job[1], r(H_LB, H_UB)),
kronos.method.threaded, (), ())
</code></pre>
| 4 | 2009-07-13T01:51:59Z | 1,117,531 | <p>I wonder, if the jobs for each time unit is actually broken, would they raise an AttibuteError, or some other exception? In particular, if there's something about a job that is really busted, you probably aught not to catch them. </p>
<p>Another option that can help is to wrap only the offending code with a try-catch, putting the exception handler as close to the exception as possible. Here's a stab: </p>
<pre><code>for app in apps:
if app.split('.', 1)[0] == 'zc': #only look for cron in zc apps
try:
a = app + '.cron'
__import__(a)
m = sys.modules[a]
except ImportError: #no cron jobs for this module
#exception is silently ignored
#since no jobs is not an error
continue
if hasattr(m, "cron_minute"):
min = m.cron_minute()
for job in min:
k.add_interval_task(job[0], 'minute task', r(M_LB, M_UB),
60*job[1],
kronos.method.threaded, (), ())
if hasattr(m, "cron_hour"):
hour = m.cron_hour()
for job in hour:
k.add_daytime_task(job[0], 'day task', range(1, 8), None,
(job[1], r(H_LB, H_UB)),
kronos.method.threaded, (), ())
</code></pre>
<p>notice there is only one exception handler here, which we handle by correctly ignoring.
since we can predict the possibility of there not being one attribute or another, we
check for it explicitly, which helps to make the code a bit clearer. Otherwise, it's not
really obvious why you are catching the AttributeError, or what is even raising it. </p>
| 1 | 2009-07-13T02:41:18Z | [
"python"
] |
Fake a cookie to scrape a site in python | 1,117,491 | <p>The site that I'm trying to scrape uses js to create a cookie. What I was thinking was that I can create a cookie in python and then use that cookie to scrape the site. However, I don't know any way of doing that. Does anybody have any ideas?</p>
| 2 | 2009-07-13T02:11:20Z | 1,117,495 | <p>Please see <a href="http://www.testingreflections.com/node/view/5919" rel="nofollow">Python httplib2 - Handling Cookies in HTTP Form Posts</a> for an example of adding a cookie to a request.</p>
<blockquote>
<p>I often need to automate tasks in web
based applications. I like to do this
at the protocol level by simulating a
real user's interactions via HTTP.
Python comes with two built-in modules
for this: urllib (higher level Web
interface) and httplib (lower level
HTTP interface).</p>
</blockquote>
| 2 | 2009-07-13T02:13:49Z | [
"python",
"cookies",
"cookiejar"
] |
Fake a cookie to scrape a site in python | 1,117,491 | <p>The site that I'm trying to scrape uses js to create a cookie. What I was thinking was that I can create a cookie in python and then use that cookie to scrape the site. However, I don't know any way of doing that. Does anybody have any ideas?</p>
| 2 | 2009-07-13T02:11:20Z | 1,118,060 | <p>If you want to do more involved browser emulation (including setting cookies) take a look at <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">mechanize</a>. It's simulation capabilities are almost complete (no Javascript support unfortunately): I've used it to build several scrapers with much success.</p>
| 2 | 2009-07-13T07:14:21Z | [
"python",
"cookies",
"cookiejar"
] |
python sqlalchemy parallel operation | 1,117,538 | <p>HIï¼i got a multi-threading program which all threads will operate on oracle
DB. So, can sqlalchemy support parallel operation on oracle?</p>
<p>tks!</p>
| 0 | 2009-07-13T02:44:56Z | 1,117,592 | <p>As long as each concurrent thread has it's own session you should be fine. Trying to use one shared session is where you'll get into trouble.</p>
| 1 | 2009-07-13T03:29:59Z | [
"python",
"sqlalchemy"
] |
python sqlalchemy parallel operation | 1,117,538 | <p>HIï¼i got a multi-threading program which all threads will operate on oracle
DB. So, can sqlalchemy support parallel operation on oracle?</p>
<p>tks!</p>
| 0 | 2009-07-13T02:44:56Z | 1,175,578 | <p>OCI (oracle client interface) has a parameter OCI_THREADED which has the effect of connections being mutexed, such that concurrent access via multiple threads is safe. This is likely the setting the document you saw was referring to.</p>
<p><code>cx_oracle</code>, which is essentially a Python->OCI bridge, provides access to this setting in its connection function using the keyword argument "threaded", described at <a href="http://cx-oracle.sourceforge.net/html/module.html#cx_Oracle.connect" rel="nofollow">http://cx-oracle.sourceforge.net/html/module.html#cx_Oracle.connect</a> . The docs state that it is False by default due to its resulting in a "10-15% performance penalty", though no source is given for this information (and performance stats should always be viewed suspiciously as a rule).</p>
<p>As far as SQLAlchemy, the <code>cx_oracle</code> dialect provided with SQLAlchemy sets this value to True by default, with the option to set it back to False when setting up the engine via create_engine() - so at that level there's no issue. </p>
<p>But beyond that, SQLAlchemy's recommended usage patterns (i.e. one Session per thread, keeping connections local to a pool where they are checked out by a function as needed) prevent concurrent access to a connection in any case. So you can likely turn off the "threaded" setting on create_engine() and enjoy the possibly-tangible performance increases provided regular usage patterns are followed.</p>
| 3 | 2009-07-24T03:09:36Z | [
"python",
"sqlalchemy"
] |
Set Django IntegerField by choices=... name | 1,117,564 | <p>When you have a model field with a choices option you tend to have some magic values associated with human readable names. Is there in Django a convenient way to set these fields by the human readable name instead of the value?</p>
<p>Consider this model:</p>
<pre><code>class Thing(models.Model):
PRIORITIES = (
(0, 'Low'),
(1, 'Normal'),
(2, 'High'),
)
priority = models.IntegerField(default=0, choices=PRIORITIES)
</code></pre>
<p>At some point we have a Thing instance and we want to set its priority. Obviously you could do,</p>
<pre><code>thing.priority = 1
</code></pre>
<p>But that forces you to memorize the Value-Name mapping of PRIORITIES. This doesn't work:</p>
<pre><code>thing.priority = 'Normal' # Throws ValueError on .save()
</code></pre>
<p>Currently I have this silly workaround:</p>
<pre><code>thing.priority = dict((key,value) for (value,key) in Thing.PRIORITIES)['Normal']
</code></pre>
<p>but that's clunky. Given how common this scenario could be I was wondering if anyone had a better solution. Is there some field method for setting fields by choice name which I totally overlooked?</p>
| 62 | 2009-07-13T03:05:15Z | 1,117,581 | <p>Simply replace your numbers with the human readable values you would like. As such:</p>
<pre><code>PRIORITIES = (
('LOW', 'Low'),
('NORMAL', 'Normal'),
('HIGH', 'High'),
)
</code></pre>
<p>This makes it human readable, however, you'd have to define your own ordering.</p>
| 1 | 2009-07-13T03:19:16Z | [
"python",
"django",
"django-models"
] |
Set Django IntegerField by choices=... name | 1,117,564 | <p>When you have a model field with a choices option you tend to have some magic values associated with human readable names. Is there in Django a convenient way to set these fields by the human readable name instead of the value?</p>
<p>Consider this model:</p>
<pre><code>class Thing(models.Model):
PRIORITIES = (
(0, 'Low'),
(1, 'Normal'),
(2, 'High'),
)
priority = models.IntegerField(default=0, choices=PRIORITIES)
</code></pre>
<p>At some point we have a Thing instance and we want to set its priority. Obviously you could do,</p>
<pre><code>thing.priority = 1
</code></pre>
<p>But that forces you to memorize the Value-Name mapping of PRIORITIES. This doesn't work:</p>
<pre><code>thing.priority = 'Normal' # Throws ValueError on .save()
</code></pre>
<p>Currently I have this silly workaround:</p>
<pre><code>thing.priority = dict((key,value) for (value,key) in Thing.PRIORITIES)['Normal']
</code></pre>
<p>but that's clunky. Given how common this scenario could be I was wondering if anyone had a better solution. Is there some field method for setting fields by choice name which I totally overlooked?</p>
| 62 | 2009-07-13T03:05:15Z | 1,117,586 | <p>I'd probably set up the reverse-lookup dict once and for all, but if I hadn't I'd just use:</p>
<pre><code>thing.priority = next(value for value, name in Thing.PRIORITIES
if name=='Normal')
</code></pre>
<p>which seems simpler than building the dict on the fly just to toss it away again;-).</p>
| 7 | 2009-07-13T03:23:26Z | [
"python",
"django",
"django-models"
] |
Set Django IntegerField by choices=... name | 1,117,564 | <p>When you have a model field with a choices option you tend to have some magic values associated with human readable names. Is there in Django a convenient way to set these fields by the human readable name instead of the value?</p>
<p>Consider this model:</p>
<pre><code>class Thing(models.Model):
PRIORITIES = (
(0, 'Low'),
(1, 'Normal'),
(2, 'High'),
)
priority = models.IntegerField(default=0, choices=PRIORITIES)
</code></pre>
<p>At some point we have a Thing instance and we want to set its priority. Obviously you could do,</p>
<pre><code>thing.priority = 1
</code></pre>
<p>But that forces you to memorize the Value-Name mapping of PRIORITIES. This doesn't work:</p>
<pre><code>thing.priority = 'Normal' # Throws ValueError on .save()
</code></pre>
<p>Currently I have this silly workaround:</p>
<pre><code>thing.priority = dict((key,value) for (value,key) in Thing.PRIORITIES)['Normal']
</code></pre>
<p>but that's clunky. Given how common this scenario could be I was wondering if anyone had a better solution. Is there some field method for setting fields by choice name which I totally overlooked?</p>
| 62 | 2009-07-13T03:05:15Z | 1,117,587 | <p>Do as <a href="http://www.b-list.org/weblog/2007/nov/02/handle-choices-right-way/">seen here</a>. Then you can use a word that represents the proper integer.</p>
<p>Like so:</p>
<pre><code>LOW = 0
NORMAL = 1
HIGH = 2
STATUS_CHOICES = (
(LOW, 'Low'),
(NORMAL, 'Normal'),
(HIGH, 'High'),
)
</code></pre>
<p>Then they are still integers in the DB.</p>
<p>Usage would be <code>thing.priority = Thing.NORMAL</code></p>
| 103 | 2009-07-13T03:23:48Z | [
"python",
"django",
"django-models"
] |
Set Django IntegerField by choices=... name | 1,117,564 | <p>When you have a model field with a choices option you tend to have some magic values associated with human readable names. Is there in Django a convenient way to set these fields by the human readable name instead of the value?</p>
<p>Consider this model:</p>
<pre><code>class Thing(models.Model):
PRIORITIES = (
(0, 'Low'),
(1, 'Normal'),
(2, 'High'),
)
priority = models.IntegerField(default=0, choices=PRIORITIES)
</code></pre>
<p>At some point we have a Thing instance and we want to set its priority. Obviously you could do,</p>
<pre><code>thing.priority = 1
</code></pre>
<p>But that forces you to memorize the Value-Name mapping of PRIORITIES. This doesn't work:</p>
<pre><code>thing.priority = 'Normal' # Throws ValueError on .save()
</code></pre>
<p>Currently I have this silly workaround:</p>
<pre><code>thing.priority = dict((key,value) for (value,key) in Thing.PRIORITIES)['Normal']
</code></pre>
<p>but that's clunky. Given how common this scenario could be I was wondering if anyone had a better solution. Is there some field method for setting fields by choice name which I totally overlooked?</p>
| 62 | 2009-07-13T03:05:15Z | 1,490,069 | <p>Here's a field type I wrote a few minutes ago that I think does what you want. Its constructor requires an argument 'choices', which may be either a tuple of 2-tuples in the same format as the choices option to IntegerField, or instead a simple list of names (ie ChoiceField(('Low', 'Normal', 'High'), default='Low') ). The class takes care of the mapping from string to int for you, you never see the int.</p>
<pre><code> class ChoiceField(models.IntegerField):
def __init__(self, choices, **kwargs):
if not hasattr(choices[0],'__iter__'):
choices = zip(range(len(choices)), choices)
self.val2choice = dict(choices)
self.choice2val = dict((v,k) for k,v in choices)
kwargs['choices'] = choices
super(models.IntegerField, self).__init__(**kwargs)
def to_python(self, value):
return self.val2choice[value]
def get_db_prep_value(self, choice):
return self.choice2val[choice]
</code></pre>
| 4 | 2009-09-29T00:56:05Z | [
"python",
"django",
"django-models"
] |
Set Django IntegerField by choices=... name | 1,117,564 | <p>When you have a model field with a choices option you tend to have some magic values associated with human readable names. Is there in Django a convenient way to set these fields by the human readable name instead of the value?</p>
<p>Consider this model:</p>
<pre><code>class Thing(models.Model):
PRIORITIES = (
(0, 'Low'),
(1, 'Normal'),
(2, 'High'),
)
priority = models.IntegerField(default=0, choices=PRIORITIES)
</code></pre>
<p>At some point we have a Thing instance and we want to set its priority. Obviously you could do,</p>
<pre><code>thing.priority = 1
</code></pre>
<p>But that forces you to memorize the Value-Name mapping of PRIORITIES. This doesn't work:</p>
<pre><code>thing.priority = 'Normal' # Throws ValueError on .save()
</code></pre>
<p>Currently I have this silly workaround:</p>
<pre><code>thing.priority = dict((key,value) for (value,key) in Thing.PRIORITIES)['Normal']
</code></pre>
<p>but that's clunky. Given how common this scenario could be I was wondering if anyone had a better solution. Is there some field method for setting fields by choice name which I totally overlooked?</p>
| 62 | 2009-07-13T03:05:15Z | 4,846,507 | <pre><code>class Sequence(object):
def __init__(self, func, *opts):
keys = func(len(opts))
self.attrs = dict(zip([t[0] for t in opts], keys))
self.choices = zip(keys, [t[1] for t in opts])
self.labels = dict(self.choices)
def __getattr__(self, a):
return self.attrs[a]
def __getitem__(self, k):
return self.labels[k]
def __len__(self):
return len(self.choices)
def __iter__(self):
return iter(self.choices)
def __deepcopy__(self, memo):
return self
class Enum(Sequence):
def __init__(self, *opts):
return super(Enum, self).__init__(range, *opts)
class Flags(Sequence):
def __init__(self, *opts):
return super(Flags, self).__init__(lambda l: [1<<i for i in xrange(l)], *opts)
</code></pre>
<p>Use it like this:</p>
<pre><code>Priorities = Enum(
('LOW', 'Low'),
('NORMAL', 'Normal'),
('HIGH', 'High')
)
priority = models.IntegerField(default=Priorities.LOW, choices=Priorities)
</code></pre>
| 2 | 2011-01-31T00:07:59Z | [
"python",
"django",
"django-models"
] |
Set Django IntegerField by choices=... name | 1,117,564 | <p>When you have a model field with a choices option you tend to have some magic values associated with human readable names. Is there in Django a convenient way to set these fields by the human readable name instead of the value?</p>
<p>Consider this model:</p>
<pre><code>class Thing(models.Model):
PRIORITIES = (
(0, 'Low'),
(1, 'Normal'),
(2, 'High'),
)
priority = models.IntegerField(default=0, choices=PRIORITIES)
</code></pre>
<p>At some point we have a Thing instance and we want to set its priority. Obviously you could do,</p>
<pre><code>thing.priority = 1
</code></pre>
<p>But that forces you to memorize the Value-Name mapping of PRIORITIES. This doesn't work:</p>
<pre><code>thing.priority = 'Normal' # Throws ValueError on .save()
</code></pre>
<p>Currently I have this silly workaround:</p>
<pre><code>thing.priority = dict((key,value) for (value,key) in Thing.PRIORITIES)['Normal']
</code></pre>
<p>but that's clunky. Given how common this scenario could be I was wondering if anyone had a better solution. Is there some field method for setting fields by choice name which I totally overlooked?</p>
| 62 | 2009-07-13T03:05:15Z | 35,026,629 | <p>I appreciate the constant defining way but I believe <a href="https://www.python.org/dev/peps/pep-0435/" rel="nofollow">Enum</a> type is far best for this task. They can represent integer and a string for an item in the same time, while keeping your code more readable.</p>
<p>Enums were introduced to Python in version 3.4. If you are using any lower (such as v2.x) you can still have it by installing the <a href="https://pypi.python.org/pypi/enum34" rel="nofollow">backported package</a>: <code>pip install enum34</code>.</p>
<pre><code># myapp/fields.py
from enum import Enum
class ChoiceEnum(Enum):
@classmethod
def choices(cls):
choices = list()
# Loop thru defined enums
for item in cls:
choices.append((item.value, item.name))
# return as tuple
return tuple(choices)
def __str__(self):
return self.name
def __int__(self):
return self.value
class Language(ChoiceEnum):
Python = 1
Ruby = 2
Java = 3
PHP = 4
Cpp = 5
# Uh oh
Language.Cpp._name_ = 'C++'
</code></pre>
<p>This is pretty much all. You can inherit the <code>ChoiceEnum</code> to create your own definitions and use them in a model definition like:</p>
<pre><code>from django.db import models
from myapp.fields import Language
class MyModel(models.Model):
language = models.IntegerField(choices=Language.choices(), default=int(Language.Python))
# ...
</code></pre>
<p>Querying is icing on the cake as you may guess:</p>
<pre><code>MyModel.objects.filter(language=int(Language.Ruby))
# or if you don't prefer `__int__` method..
MyModel.objects.filter(language=Language.Ruby.value)
</code></pre>
<p>Representing them in string is also made easy:</p>
<pre><code># Get the enum item
lang = Language(some_instance.language)
print(str(lang))
# or if you don't prefer `__str__` method..
print(lang.name)
# Same as get_FOO_display
lang.name == some_instance.get_language_display()
</code></pre>
| 1 | 2016-01-27T00:25:36Z | [
"python",
"django",
"django-models"
] |
In Python, is there a way to detect the use of incorrect variable names; something like VB's "Option Explicit"? | 1,117,661 | <p>I do most of my development in Java and C++ but recently had to write various scripts and picked up Python. I run python from the command line on scripts; not in interactive mode. I'm wondering if </p>
<p>I like a lot of things about the language, but one thing that keeps reducing my productivity is the fact that I get no advance warning if I am using a variable that is not yet defined. </p>
<p>For example, somewhere in the code I forget to prefix a variable with its declaring module, or I make a little typo, and the first time I learn about it is when the program crashes. </p>
<p>Is there a way to get the python interpreter to throw advance warnings if something might be funky when I access a variable that hasn't been accessed or set somewhere else in the program? I realize this is somewhat against the philosophy of the language, but I can't be the only one who makes these silly errors and has no way of catching them early.</p>
| 3 | 2009-07-13T04:09:46Z | 1,117,676 | <p>there are some tools like <a href="http://www.logilab.org/project/pylint" rel="nofollow">pylint</a> or <a href="http://www.divmod.org/trac/wiki/DivmodPyflakes" rel="nofollow">pyflakes</a> which may catch some of those. pyflakes is quite fast, and usable on many projects for this reason</p>
<p>As reported on pyflakes webpage, the two primary categories of defects reported by PyFlakes are:</p>
<ul>
<li>Names which are used but not defined or used before they are defined</li>
<li>Names which are redefined without having been used </li>
</ul>
| 2 | 2009-07-13T04:14:44Z | [
"python"
] |
In Python, is there a way to detect the use of incorrect variable names; something like VB's "Option Explicit"? | 1,117,661 | <p>I do most of my development in Java and C++ but recently had to write various scripts and picked up Python. I run python from the command line on scripts; not in interactive mode. I'm wondering if </p>
<p>I like a lot of things about the language, but one thing that keeps reducing my productivity is the fact that I get no advance warning if I am using a variable that is not yet defined. </p>
<p>For example, somewhere in the code I forget to prefix a variable with its declaring module, or I make a little typo, and the first time I learn about it is when the program crashes. </p>
<p>Is there a way to get the python interpreter to throw advance warnings if something might be funky when I access a variable that hasn't been accessed or set somewhere else in the program? I realize this is somewhat against the philosophy of the language, but I can't be the only one who makes these silly errors and has no way of catching them early.</p>
| 3 | 2009-07-13T04:09:46Z | 1,117,736 | <p>Pydev is pretty well integrated with Pylint, see <a href="http://pydev.sourceforge.net/pylint.html" rel="nofollow">here</a> -- and pylint is a much more powerful checker than pyflakes (beyond the minor issue of misspelled variables, it will catch style violations, etc, etc -- it's <em>highly</em> customizable for whatever your specific purposes are!).</p>
| 2 | 2009-07-13T04:48:57Z | [
"python"
] |
Python MySQLdb exceptions | 1,117,828 | <p>Just starting to get to grips with python and MySQLdb and was wondering</p>
<ol>
<li><p>Where is the best play to put a try/catch block for the connection to MySQL. At the MySQLdb.connect point? Also should there be one when ever i query?</p></li>
<li><p>What exceptions should i be catching on any of these blocks?</p></li>
</ol>
<p>thanks for any help</p>
<p>Cheers
Mark</p>
| 7 | 2009-07-13T05:31:22Z | 1,117,841 | <p>I think that the connections and the query can raised errors so you should have try/excepy for both of them. </p>
| 1 | 2009-07-13T05:37:08Z | [
"python",
"mysql",
"exception"
] |
Python MySQLdb exceptions | 1,117,828 | <p>Just starting to get to grips with python and MySQLdb and was wondering</p>
<ol>
<li><p>Where is the best play to put a try/catch block for the connection to MySQL. At the MySQLdb.connect point? Also should there be one when ever i query?</p></li>
<li><p>What exceptions should i be catching on any of these blocks?</p></li>
</ol>
<p>thanks for any help</p>
<p>Cheers
Mark</p>
| 7 | 2009-07-13T05:31:22Z | 1,118,129 | <p>Catch the MySQLdb.Error, while connecting and while executing query</p>
| 13 | 2009-07-13T07:38:08Z | [
"python",
"mysql",
"exception"
] |
Caching PHP script outputs on the client side | 1,117,890 | <p>I have a php script that outputs a random image each time it's called. So when I open the script in a web browser, it shows one image and if I refresh, another image shows up.</p>
<p>I'm trying to capture the correct image from visiting the web site through a command line (via mechanize). I used urllib2.urlopen(...) to grab the image, but each time I do that I get a different image. I want to be able to consistently grab the same image. How can I accomplish that?</p>
<p>Thanks!</p>
<p>UPDATE:
Here's an example of what I'm talking about. If you reload this image in a web browser, a different image pops up each time. If you right click and save, you get the correct image. And if you keep doing that, you keep getting the correct image... BUT, how do you that from a command line?</p>
<p><a href="http://www.biglickmedia.com/art/random/index.php" rel="nofollow">http://www.biglickmedia.com/art/random/index.php</a></p>
| 0 | 2009-07-13T06:03:22Z | 1,117,912 | <p>Most likely your image is cached by browser set this:</p>
<pre><code><?php
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
?>
</code></pre>
<p>and each time you generating the image use another name for it (can be done by adding milliseconds to original one).</p>
| 1 | 2009-07-13T06:17:21Z | [
"php",
"python",
"caching",
"mechanize"
] |
Caching PHP script outputs on the client side | 1,117,890 | <p>I have a php script that outputs a random image each time it's called. So when I open the script in a web browser, it shows one image and if I refresh, another image shows up.</p>
<p>I'm trying to capture the correct image from visiting the web site through a command line (via mechanize). I used urllib2.urlopen(...) to grab the image, but each time I do that I get a different image. I want to be able to consistently grab the same image. How can I accomplish that?</p>
<p>Thanks!</p>
<p>UPDATE:
Here's an example of what I'm talking about. If you reload this image in a web browser, a different image pops up each time. If you right click and save, you get the correct image. And if you keep doing that, you keep getting the correct image... BUT, how do you that from a command line?</p>
<p><a href="http://www.biglickmedia.com/art/random/index.php" rel="nofollow">http://www.biglickmedia.com/art/random/index.php</a></p>
| 0 | 2009-07-13T06:03:22Z | 1,117,926 | <p>You can try caching the image generated to disk and make it available to the user via a different link.</p>
<p>After the image is generated, move it to a temp folder, where the user can download the generated static image. After it is downloaded, delete to make space.</p>
| 1 | 2009-07-13T06:22:39Z | [
"php",
"python",
"caching",
"mechanize"
] |
Caching PHP script outputs on the client side | 1,117,890 | <p>I have a php script that outputs a random image each time it's called. So when I open the script in a web browser, it shows one image and if I refresh, another image shows up.</p>
<p>I'm trying to capture the correct image from visiting the web site through a command line (via mechanize). I used urllib2.urlopen(...) to grab the image, but each time I do that I get a different image. I want to be able to consistently grab the same image. How can I accomplish that?</p>
<p>Thanks!</p>
<p>UPDATE:
Here's an example of what I'm talking about. If you reload this image in a web browser, a different image pops up each time. If you right click and save, you get the correct image. And if you keep doing that, you keep getting the correct image... BUT, how do you that from a command line?</p>
<p><a href="http://www.biglickmedia.com/art/random/index.php" rel="nofollow">http://www.biglickmedia.com/art/random/index.php</a></p>
| 0 | 2009-07-13T06:03:22Z | 1,125,281 | <p>Grab it once and cache it on your side.</p>
| 0 | 2009-07-14T13:12:10Z | [
"php",
"python",
"caching",
"mechanize"
] |
Caching PHP script outputs on the client side | 1,117,890 | <p>I have a php script that outputs a random image each time it's called. So when I open the script in a web browser, it shows one image and if I refresh, another image shows up.</p>
<p>I'm trying to capture the correct image from visiting the web site through a command line (via mechanize). I used urllib2.urlopen(...) to grab the image, but each time I do that I get a different image. I want to be able to consistently grab the same image. How can I accomplish that?</p>
<p>Thanks!</p>
<p>UPDATE:
Here's an example of what I'm talking about. If you reload this image in a web browser, a different image pops up each time. If you right click and save, you get the correct image. And if you keep doing that, you keep getting the correct image... BUT, how do you that from a command line?</p>
<p><a href="http://www.biglickmedia.com/art/random/index.php" rel="nofollow">http://www.biglickmedia.com/art/random/index.php</a></p>
| 0 | 2009-07-13T06:03:22Z | 1,125,316 | <p>When you save it from the browser, it is not going back to the server to re-request the image, it is serving the one that it is displaying from its cache.</p>
<p>Your command line client needs to do the same thing. You need to save the image every time you request it. Then when you find the one you want to keep you need to copy the already saved image to wherever it is you want to keep it permanently.</p>
<p>If the server is always serving a new random image there's nothing else you can do.</p>
| 1 | 2009-07-14T13:17:10Z | [
"php",
"python",
"caching",
"mechanize"
] |
How Do I Use Raw Socket in Python? | 1,117,958 | <p>I am writing an application to test a network driver for handling corrupted data. And I thought of sending this data using raw socket, so it will not be corrected by the sending machine's TCP-IP stack.</p>
<p>I am writing this application solely on Linux. I have code examples of using raw sockets in system-calls, but I would really like to keep my test as dynamic as possible, and write most if not all of it in Python.</p>
<p>I have googled the web a bit for explanations and examples of the usage of raw sockets in python, but haven't found anything really enlightening. Just a a very old code example that demonstrates the idea, but in no means work.</p>
<p>From what I gathered, Raw Socket usage in Python is nearly identical in semantics to UNIX's raw socket, but without the <code>struct</code>s that define the packets structure.</p>
<p><strong>I was wondering if it would even be better not to write the raw socket part of the test in Python, but in C with system-calls, and call it from the main Python code?</strong></p>
| 30 | 2009-07-13T06:36:13Z | 1,117,995 | <p>The socket class should help. If not you'll need to either write a Python module in C or just use C. See <a href="http://mail.python.org/pipermail/python-list/2001-April/077454.html" rel="nofollow">http://mail.python.org/pipermail/python-list/2001-April/077454.html</a>.</p>
<p>Basic Googling found that.</p>
<p>I actually tried the code example which "unwind" has pointed out. AF_PACKET did work for me in python 2.7.4</p>
| 0 | 2009-07-13T06:49:05Z | [
"python",
"sockets",
"raw-sockets"
] |
How Do I Use Raw Socket in Python? | 1,117,958 | <p>I am writing an application to test a network driver for handling corrupted data. And I thought of sending this data using raw socket, so it will not be corrected by the sending machine's TCP-IP stack.</p>
<p>I am writing this application solely on Linux. I have code examples of using raw sockets in system-calls, but I would really like to keep my test as dynamic as possible, and write most if not all of it in Python.</p>
<p>I have googled the web a bit for explanations and examples of the usage of raw sockets in python, but haven't found anything really enlightening. Just a a very old code example that demonstrates the idea, but in no means work.</p>
<p>From what I gathered, Raw Socket usage in Python is nearly identical in semantics to UNIX's raw socket, but without the <code>struct</code>s that define the packets structure.</p>
<p><strong>I was wondering if it would even be better not to write the raw socket part of the test in Python, but in C with system-calls, and call it from the main Python code?</strong></p>
| 30 | 2009-07-13T06:36:13Z | 1,118,001 | <p>Is <a href="ftp://ftp.visi.com/users/grante/python/rawDemo.py" rel="nofollow">this</a> the old code you mentioned finding? It looks sensible to me, but I haven't tested it myself (or used raw sockets much). <a href="http://docs.python.org/library/socket.html" rel="nofollow">This example</a> from the documentation shows how to use raw sockets to sniff packets, and it looks similar enough.</p>
| 2 | 2009-07-13T06:50:15Z | [
"python",
"sockets",
"raw-sockets"
] |
How Do I Use Raw Socket in Python? | 1,117,958 | <p>I am writing an application to test a network driver for handling corrupted data. And I thought of sending this data using raw socket, so it will not be corrected by the sending machine's TCP-IP stack.</p>
<p>I am writing this application solely on Linux. I have code examples of using raw sockets in system-calls, but I would really like to keep my test as dynamic as possible, and write most if not all of it in Python.</p>
<p>I have googled the web a bit for explanations and examples of the usage of raw sockets in python, but haven't found anything really enlightening. Just a a very old code example that demonstrates the idea, but in no means work.</p>
<p>From what I gathered, Raw Socket usage in Python is nearly identical in semantics to UNIX's raw socket, but without the <code>struct</code>s that define the packets structure.</p>
<p><strong>I was wondering if it would even be better not to write the raw socket part of the test in Python, but in C with system-calls, and call it from the main Python code?</strong></p>
| 30 | 2009-07-13T06:36:13Z | 1,118,003 | <p>Sockets system calls (or Winsocks, on Windows), are already wrapped in the standard module <code>socket</code>: <a href="http://docs.python.org/howto/sockets.html">intro</a>, <a href="http://docs.python.org/library/socket.html">reference</a>.</p>
<p>I've never used raw sockets but it looks like they can be used with this module:</p>
<blockquote>
<p>The last example shows how to write a
very simple network sniffer with raw
sockets on Windows. The example
requires administrator privileges to
modify the interface:</p>
<pre><code>import socket
# the public network interface
HOST = socket.gethostbyname(socket.gethostname())
# create a raw socket and bind it to the public interface
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
s.bind((HOST, 0))
# Include IP headers
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
# receive all packages
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
# receive a package
print s.recvfrom(65565)
# disabled promiscuous mode
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
</code></pre>
</blockquote>
| 8 | 2009-07-13T06:52:13Z | [
"python",
"sockets",
"raw-sockets"
] |
How Do I Use Raw Socket in Python? | 1,117,958 | <p>I am writing an application to test a network driver for handling corrupted data. And I thought of sending this data using raw socket, so it will not be corrected by the sending machine's TCP-IP stack.</p>
<p>I am writing this application solely on Linux. I have code examples of using raw sockets in system-calls, but I would really like to keep my test as dynamic as possible, and write most if not all of it in Python.</p>
<p>I have googled the web a bit for explanations and examples of the usage of raw sockets in python, but haven't found anything really enlightening. Just a a very old code example that demonstrates the idea, but in no means work.</p>
<p>From what I gathered, Raw Socket usage in Python is nearly identical in semantics to UNIX's raw socket, but without the <code>struct</code>s that define the packets structure.</p>
<p><strong>I was wondering if it would even be better not to write the raw socket part of the test in Python, but in C with system-calls, and call it from the main Python code?</strong></p>
| 30 | 2009-07-13T06:36:13Z | 1,186,810 | <p>Eventually the best solution for this case was to write the entire thing in C, because it's not a big application, so it would've incurred greater penalty to write such a small thing in more than 1 language.</p>
<p>After much toying with both the C and python RAW sockets, I eventually preferred the C RAW sockets. RAW sockets require bit-level modifications of less than 8 bit groups for writing the packet headers. Sometimes writing only 4 bits or less. python defines no assistance to this, whereas Linux C has a full API for this.</p>
<p>But I definitely believe that if only this little bit of header initialization was handled conveniently in python, I would've never used C here.</p>
| 4 | 2009-07-27T06:58:51Z | [
"python",
"sockets",
"raw-sockets"
] |
How Do I Use Raw Socket in Python? | 1,117,958 | <p>I am writing an application to test a network driver for handling corrupted data. And I thought of sending this data using raw socket, so it will not be corrected by the sending machine's TCP-IP stack.</p>
<p>I am writing this application solely on Linux. I have code examples of using raw sockets in system-calls, but I would really like to keep my test as dynamic as possible, and write most if not all of it in Python.</p>
<p>I have googled the web a bit for explanations and examples of the usage of raw sockets in python, but haven't found anything really enlightening. Just a a very old code example that demonstrates the idea, but in no means work.</p>
<p>From what I gathered, Raw Socket usage in Python is nearly identical in semantics to UNIX's raw socket, but without the <code>struct</code>s that define the packets structure.</p>
<p><strong>I was wondering if it would even be better not to write the raw socket part of the test in Python, but in C with system-calls, and call it from the main Python code?</strong></p>
| 30 | 2009-07-13T06:36:13Z | 6,374,862 | <p>You do it like this:</p>
<p>First you disable your network card's automatic checksumming:</p>
<pre><code>sudo ethtool -K eth1 tx off
</code></pre>
<p>And then send your dodgy frame from python:</p>
<pre><code>#!/usr/bin/env python
from socket import socket, AF_PACKET, SOCK_RAW
s = socket(AF_PACKET, SOCK_RAW)
s.bind(("eth1", 0))
# We're putting together an ethernet frame here,
# but you could have anything you want instead
# Have a look at the 'struct' module for more
# flexible packing/unpacking of binary data
# and 'binascii' for 32 bit CRC
src_addr = "\x01\x02\x03\x04\x05\x06"
dst_addr = "\x01\x02\x03\x04\x05\x06"
payload = ("["*30)+"PAYLOAD"+("]"*30)
checksum = "\x1a\x2b\x3c\x4d"
ethertype = "\x08\x01"
s.send(dst_addr+src_addr+ethertype+payload+checksum)
</code></pre>
<p>Done.</p>
| 35 | 2011-06-16T15:57:17Z | [
"python",
"sockets",
"raw-sockets"
] |
How Do I Use Raw Socket in Python? | 1,117,958 | <p>I am writing an application to test a network driver for handling corrupted data. And I thought of sending this data using raw socket, so it will not be corrected by the sending machine's TCP-IP stack.</p>
<p>I am writing this application solely on Linux. I have code examples of using raw sockets in system-calls, but I would really like to keep my test as dynamic as possible, and write most if not all of it in Python.</p>
<p>I have googled the web a bit for explanations and examples of the usage of raw sockets in python, but haven't found anything really enlightening. Just a a very old code example that demonstrates the idea, but in no means work.</p>
<p>From what I gathered, Raw Socket usage in Python is nearly identical in semantics to UNIX's raw socket, but without the <code>struct</code>s that define the packets structure.</p>
<p><strong>I was wondering if it would even be better not to write the raw socket part of the test in Python, but in C with system-calls, and call it from the main Python code?</strong></p>
| 30 | 2009-07-13T06:36:13Z | 12,633,135 | <pre><code>s = socket(AF_PACKET, SOCK_RAW)
s = socket(PF_PACKET, SOCK_RAW)
</code></pre>
<p>resultï¼</p>
<pre><code>[root@localhost python]# tcpdump -i eth0
capture size 96 bytes
11:01:46.850438
01:02:03:04:05:06 (oui Unknown) > 01:02:03:04:05:06 (oui Unknown), ethertype Unknown (0x0801), length 85:
0x0000: 5b5b 5b5b 5b5b 5b5b 5b5b 5b5b 5b5b 5b5b [[[[[[[[[[[[[[[[
0x0010: 5b5b 5b5b 5b5b 5b5b 5b5b 5b5b 5b5b 5041 [[[[[[[[[[[[[[PA
0x0020: 594c 4f41 445d 5d5d 5d5d 5d5d 5d5d 5d5d YLOAD]]]]]]]]]]]
0x0030: 5d5d 5d5d 5d5d 5d5d 5d5d 5d5d 5d5d 5d5d ]]]]]]]]]]]]]]]]
0x0040: 5d5d 5d00 0000 00 ]]]....
</code></pre>
| 1 | 2012-09-28T03:15:43Z | [
"python",
"sockets",
"raw-sockets"
] |
Most "pythonic" way of organising class attributes, constructor arguments and subclass constructor defaults? | 1,118,006 | <p>Being relatively new to Python 2, I'm uncertain how best to organise my class files in the most 'pythonic' way. I wouldn't be asking this but for the fact that Python seems to have quite a few ways of doing things that are very different to what I have come to expect from the languages I am used to.</p>
<p>Initially, I was just treating classes how I'd usually treat them in C# or PHP, which of course made me trip up all over the place when I eventually discovered the mutable values gotcha:</p>
<pre><code>class Pants(object):
pockets = 2
pocketcontents = []
class CargoPants(Pants):
pockets = 200
p1 = Pants()
p1.pocketcontents.append("Magical ten dollar bill")
p2 = CargoPants()
print p2.pocketcontents
</code></pre>
<p>Yikes! Didn't expect that!</p>
<p>I've spent a lot of time searching the web and through some source for other projects for hints on how best to arrange my classes, and one of the things I noticed was that people seem to declare a lot of their instance variables - mutable or otherwise - in the constructor, and also pile the default constructor arguments on quite thickly. </p>
<p>After developing like this for a while, I'm still left scratching my head a bit about the unfamiliarity of it. Considering the lengths to which the python language goes to to make things seem more intuitive and obvious, it seems outright odd to me in the few cases where I've got quite a lot of attributes or a lot of default constructor arguments, especially when I'm subclassing:</p>
<pre><code>class ClassWithLotsOfAttributes(object):
def __init__(self, jeebus, coolness='lots', python='isgoodfun',
pythonic='nebulous', duck='goose', pants=None,
magictenbucks=4, datawad=None, dataload=None,
datacatastrophe=None):
if pants is None: pants = []
if datawad is None: datawad = []
if dataload is None: dataload = []
if datacatastrophe is None: datacatastrophe = []
self.coolness = coolness
self.python = python
self.pythonic = pythonic
self.duck = duck
self.pants = pants
self.magictenbucks = magictenbucks
self.datawad = datawad
self.dataload = dataload
self.datacatastrophe = datacatastrophe
self.bigness = None
self.awesomeitude = None
self.genius = None
self.fatness = None
self.topwise = None
self.brillant = False
self.strangenessfactor = 3
self.noisiness = 12
self.whatever = None
self.yougettheidea = True
class Dog(ClassWithLotsOfAttributes):
def __init__(self, coolness='lots', python='isgoodfun', pythonic='nebulous', duck='goose', pants=None, magictenbucks=4, datawad=None, dataload=None, datacatastrophe=None):
super(ClassWithLotsOfAttributes, self).__init__(coolness, python, pythonic, duck, pants, magictenbucks, datawad, dataload, datacatastrophe)
self.noisiness = 1000000
def quack(self):
print "woof"
</code></pre>
<p>Mild silliness aside (I can't really help myself when cooking up these artificial example classes), assuming I have a real-world need for a set of classes with this many attributes, I suppose my questions are:</p>
<ul>
<li><p>What is the most, uhh, 'pythonic' way of declaring a class with that many attributes? Is it best to put them against the class if the default is immutable, ala Pants.pockets, or is it better to put them in the constructor, ala ClassWithLotsOfAttributes.noisiness? </p></li>
<li><p>Is there a way to eliminate the need to redeclare the defaults for all of the subclass constructor arguments, as in Dog.__init__? Should I even be including this many arguments with defaults anyway?</p></li>
</ul>
| 12 | 2009-07-13T06:54:28Z | 1,118,035 | <ul>
<li><p>If attributes will vary from instance
to instance make them instance
attribute i.e. create them
inside<code>__init__</code> using <strong>self</strong> else if they need to
be shared between class instances
like a constant, put them at class
level.</p></li>
<li><p>If your class really need to pass, so
many arguments in <code>__init__</code>, let
derive class use argument list and
keyword arguments e.g.</p></li>
</ul>
<pre>class Dog(ClassWithLotsOfAttributes):
def __init__(self, *args , **kwargs):
super(ClassWithLotsOfAttributes, self).__init__(*args , **kwargs)
self.coolness = "really cool!!!</pre>
<ul>
<li>No need of passing all variables except few important ones, in
<code>__init__</code>, class can assume some
defaults and user can change them
later on if needed.</li>
<li><p>Use 4 spaces instead of tab.</p></li>
<li><p>if you need to add an extra arg bite, to Dog and keyword arg old too</p></li>
</ul>
<pre>class CoolDog(ClassWithLotsOfAttributes):
def __init__(self, bite, *args , **kwargs):
self.old = kwargs.pop('old', False) # this way we can access base class args too
super(ClassWithLotsOfAttributes, self).__init__(*args , **kwargs)
self.bite = bite
self.coolness = "really really cool!!!</pre>
<p>various ways you useCoolDog</p>
<pre><code>CoolDog(True)
CoolDog(True, old=False)
CoolDog(bite=True, old=True)
CoolDog(old=True, bite=False)
</code></pre>
| 4 | 2009-07-13T07:05:47Z | [
"python",
"python-2.6"
] |
Most "pythonic" way of organising class attributes, constructor arguments and subclass constructor defaults? | 1,118,006 | <p>Being relatively new to Python 2, I'm uncertain how best to organise my class files in the most 'pythonic' way. I wouldn't be asking this but for the fact that Python seems to have quite a few ways of doing things that are very different to what I have come to expect from the languages I am used to.</p>
<p>Initially, I was just treating classes how I'd usually treat them in C# or PHP, which of course made me trip up all over the place when I eventually discovered the mutable values gotcha:</p>
<pre><code>class Pants(object):
pockets = 2
pocketcontents = []
class CargoPants(Pants):
pockets = 200
p1 = Pants()
p1.pocketcontents.append("Magical ten dollar bill")
p2 = CargoPants()
print p2.pocketcontents
</code></pre>
<p>Yikes! Didn't expect that!</p>
<p>I've spent a lot of time searching the web and through some source for other projects for hints on how best to arrange my classes, and one of the things I noticed was that people seem to declare a lot of their instance variables - mutable or otherwise - in the constructor, and also pile the default constructor arguments on quite thickly. </p>
<p>After developing like this for a while, I'm still left scratching my head a bit about the unfamiliarity of it. Considering the lengths to which the python language goes to to make things seem more intuitive and obvious, it seems outright odd to me in the few cases where I've got quite a lot of attributes or a lot of default constructor arguments, especially when I'm subclassing:</p>
<pre><code>class ClassWithLotsOfAttributes(object):
def __init__(self, jeebus, coolness='lots', python='isgoodfun',
pythonic='nebulous', duck='goose', pants=None,
magictenbucks=4, datawad=None, dataload=None,
datacatastrophe=None):
if pants is None: pants = []
if datawad is None: datawad = []
if dataload is None: dataload = []
if datacatastrophe is None: datacatastrophe = []
self.coolness = coolness
self.python = python
self.pythonic = pythonic
self.duck = duck
self.pants = pants
self.magictenbucks = magictenbucks
self.datawad = datawad
self.dataload = dataload
self.datacatastrophe = datacatastrophe
self.bigness = None
self.awesomeitude = None
self.genius = None
self.fatness = None
self.topwise = None
self.brillant = False
self.strangenessfactor = 3
self.noisiness = 12
self.whatever = None
self.yougettheidea = True
class Dog(ClassWithLotsOfAttributes):
def __init__(self, coolness='lots', python='isgoodfun', pythonic='nebulous', duck='goose', pants=None, magictenbucks=4, datawad=None, dataload=None, datacatastrophe=None):
super(ClassWithLotsOfAttributes, self).__init__(coolness, python, pythonic, duck, pants, magictenbucks, datawad, dataload, datacatastrophe)
self.noisiness = 1000000
def quack(self):
print "woof"
</code></pre>
<p>Mild silliness aside (I can't really help myself when cooking up these artificial example classes), assuming I have a real-world need for a set of classes with this many attributes, I suppose my questions are:</p>
<ul>
<li><p>What is the most, uhh, 'pythonic' way of declaring a class with that many attributes? Is it best to put them against the class if the default is immutable, ala Pants.pockets, or is it better to put them in the constructor, ala ClassWithLotsOfAttributes.noisiness? </p></li>
<li><p>Is there a way to eliminate the need to redeclare the defaults for all of the subclass constructor arguments, as in Dog.__init__? Should I even be including this many arguments with defaults anyway?</p></li>
</ul>
| 12 | 2009-07-13T06:54:28Z | 1,118,076 | <p>It is possible that you can break your massive classes down into classes that each only perform one simple task. Usually classes don't need this many attributes.</p>
<p>If you really need to have that many attributes, I think you'll have to live with assigning them all too, especially since you need default values for them all. You don't need to reassign the defaults in your subclasses though (I see Anurag Uniyal showed how.)</p>
<p>You should assign them to <code>self</code> though, and not as class attributes. Note the difference:</p>
<pre><code>class Class1(object):
attr1 = 'abc'
class Class2(object):
def __init__(self):
self.attr1 = 'abc'
Class1.attr1 # returns 'abc'
c = Class1()
c.attr1 # Also returns 'abc'
Class1.attr1 = 'def'
c.attr1 # Returns 'def'!
c.attr1 = 'abc' # Now the c instance gets its own value and will show it
# independently of what Class1.attr1 is. This is the same
# behavior that Class2 exhibits from the start.
</code></pre>
| -1 | 2009-07-13T07:19:25Z | [
"python",
"python-2.6"
] |
Turbogears 2 vs Django - any advice on choosing replacement for Turbogears 1? | 1,118,163 | <p>I have been using Turbogears 1 for prototyping small sites for the last couple of years and it is getting a little long in the tooth. Any suggestions on making the call between upgrading to Turbogears 2 or switching to something like Django? I'm torn between the familiarity of the TG community who are pretty responsive and do pretty good documentation vs the far larger community using Django. I am quite tempted by the built-in CMS features and the Google AppEngine support.</p>
<p>Any advice?</p>
<p>Thanks</p>
<p>.M.</p>
| 10 | 2009-07-13T07:49:39Z | 1,118,228 | <p>Am sure you would have read from plenty of comparison between TurboGears and DJango on web.</p>
<p>But as for your temptation on CMS and GAE, i can really think you got to go DJango way.
Check these out, and decide youself.</p>
<p><a href="http://stackoverflow.com/questions/526256/best-django-features-that-do-work-on-google-app-engine/526313#526313">Django with GAE</a></p>
<p><a href="http://blueflavor.com/blog/2007/dec/03/django-a-flexible-choice-for-y/" rel="nofollow">Django for CMS</a></p>
| 1 | 2009-07-13T08:13:20Z | [
"python",
"django",
"google-app-engine",
"turbogears",
"turbogears2"
] |
Turbogears 2 vs Django - any advice on choosing replacement for Turbogears 1? | 1,118,163 | <p>I have been using Turbogears 1 for prototyping small sites for the last couple of years and it is getting a little long in the tooth. Any suggestions on making the call between upgrading to Turbogears 2 or switching to something like Django? I'm torn between the familiarity of the TG community who are pretty responsive and do pretty good documentation vs the far larger community using Django. I am quite tempted by the built-in CMS features and the Google AppEngine support.</p>
<p>Any advice?</p>
<p>Thanks</p>
<p>.M.</p>
| 10 | 2009-07-13T07:49:39Z | 1,118,237 | <p>I have been using Django for a year now and when I started I had no experience of Python or Django and found it very intuitive to use.</p>
<p>I have created a number of hobbyist Google App Engine apps using Django with the latest one being a CMS for my site. Using Django has meant that I have been able to code a lot quicker and with a lot less bugs.</p>
| 5 | 2009-07-13T08:15:27Z | [
"python",
"django",
"google-app-engine",
"turbogears",
"turbogears2"
] |
Turbogears 2 vs Django - any advice on choosing replacement for Turbogears 1? | 1,118,163 | <p>I have been using Turbogears 1 for prototyping small sites for the last couple of years and it is getting a little long in the tooth. Any suggestions on making the call between upgrading to Turbogears 2 or switching to something like Django? I'm torn between the familiarity of the TG community who are pretty responsive and do pretty good documentation vs the far larger community using Django. I am quite tempted by the built-in CMS features and the Google AppEngine support.</p>
<p>Any advice?</p>
<p>Thanks</p>
<p>.M.</p>
| 10 | 2009-07-13T07:49:39Z | 1,118,670 | <p>I have experience with both Django and TG1.1.</p>
<p>IMO, TurboGears strong point is it's ORM: SQLAlchemy. I prefer TurboGears when the database side of things is non-trivial.</p>
<p>Django's ORM is just not that flexible and powerful.</p>
<p>That being said, I prefer Django. If the database schema is a good fit with Django's ORM I would go with Django.</p>
<p>In my experience, it is simply less hassle to use Django compared with TurboGears.</p>
| 9 | 2009-07-13T10:18:12Z | [
"python",
"django",
"google-app-engine",
"turbogears",
"turbogears2"
] |
Turbogears 2 vs Django - any advice on choosing replacement for Turbogears 1? | 1,118,163 | <p>I have been using Turbogears 1 for prototyping small sites for the last couple of years and it is getting a little long in the tooth. Any suggestions on making the call between upgrading to Turbogears 2 or switching to something like Django? I'm torn between the familiarity of the TG community who are pretty responsive and do pretty good documentation vs the far larger community using Django. I am quite tempted by the built-in CMS features and the Google AppEngine support.</p>
<p>Any advice?</p>
<p>Thanks</p>
<p>.M.</p>
| 10 | 2009-07-13T07:49:39Z | 1,118,673 | <p>TG2 is built on top of Pylons which has a fairly large community as well. TG got faster compared to TG1 and it includes a per-method (not just web pages) caching engine.
I think it's more AJAX-friendly than Django by the way pages can be easly published in HTML or JSON .</p>
<p>2011 update: after 3 years of bloated frameworks I'm an happy user of <a href="http://bottlepy.org/">http://bottlepy.org/</a></p>
| 13 | 2009-07-13T10:19:12Z | [
"python",
"django",
"google-app-engine",
"turbogears",
"turbogears2"
] |
Turbogears 2 vs Django - any advice on choosing replacement for Turbogears 1? | 1,118,163 | <p>I have been using Turbogears 1 for prototyping small sites for the last couple of years and it is getting a little long in the tooth. Any suggestions on making the call between upgrading to Turbogears 2 or switching to something like Django? I'm torn between the familiarity of the TG community who are pretty responsive and do pretty good documentation vs the far larger community using Django. I am quite tempted by the built-in CMS features and the Google AppEngine support.</p>
<p>Any advice?</p>
<p>Thanks</p>
<p>.M.</p>
| 10 | 2009-07-13T07:49:39Z | 1,584,576 | <p>Ive only got one question...is the app you are developing directed towards social networking
or customized business logic?</p>
<p>I personally find Django is good for social networking and pylons/turbogears if you really
want the flexibility and no boundaries...</p>
<p>just my 2c</p>
| -1 | 2009-10-18T10:44:30Z | [
"python",
"django",
"google-app-engine",
"turbogears",
"turbogears2"
] |
Turbogears 2 vs Django - any advice on choosing replacement for Turbogears 1? | 1,118,163 | <p>I have been using Turbogears 1 for prototyping small sites for the last couple of years and it is getting a little long in the tooth. Any suggestions on making the call between upgrading to Turbogears 2 or switching to something like Django? I'm torn between the familiarity of the TG community who are pretty responsive and do pretty good documentation vs the far larger community using Django. I am quite tempted by the built-in CMS features and the Google AppEngine support.</p>
<p>Any advice?</p>
<p>Thanks</p>
<p>.M.</p>
| 10 | 2009-07-13T07:49:39Z | 4,919,043 | <p>TG2 seem much complicated and confusing, even for doing somewhat simple like a login page with multimple error messages
<a href="http://stackoverflow.com/questions/1960747/how-to-extend-the-turbogears-2-1-login-functionality">How to extend the Turbogears 2.1 login functionality</a>
I think thats because of intemperance in modularity...</p>
| 0 | 2011-02-07T07:49:15Z | [
"python",
"django",
"google-app-engine",
"turbogears",
"turbogears2"
] |
How to debug in Django, the good way? | 1,118,183 | <p>So, I started learning to code in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> and later <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging my Django code. As this was done early in my coding experience, I sat down and wondered if how I was doing this was ineffective and could be done faster. I usually manage to find and correct the bugs in my code, but I wonder if I should be doing it faster?</p>
<p>I usually just use the debug info Django gives when enabled. When things do end up as I thought it would, I break the code flow a lot with a syntax error, and look at the variables at that point in the flow to figure out, where the code does something other than what I wanted.</p>
<p>But can this be improved? Are there some good tools or better ways to debug your Django code?</p>
| 378 | 2009-07-13T07:57:02Z | 1,118,271 | <p>There are a bunch of ways to do it, but the most straightforward is to simply
use the <a href="https://docs.python.org/2/library/pdb.html">Python debugger</a>. Just add following line in to a Django view function:</p>
<pre><code>import pdb; pdb.set_trace()
</code></pre>
<p>If you try to load that page in your browser, the browser will hang and you get a prompt to carry on debugging on actual executing code.</p>
<p>However there are other options suggested by others (I won't recommend them):</p>
<pre><code>* return HttpResponse({variable to inspect})
* print {variable to inspect}
* raise Exception({variable to inspect})
</code></pre>
<p>But the Python Debugger (pdb) is highly recommended for all types of Python code. If you are already into pdb, you'd also want to have a look at <a href="http://pypi.python.org/pypi/ipdb/"><strong>IPDB</strong></a> that uses <a href="http://ipython.org/"><strong>ipython</strong></a> for debugging. Happy Coding.</p>
<p>A useful reference provided by <a href="http://stackoverflow.com/users/884640/seafangs">Seafangs</a> : <a href="https://web.archive.org/web/20120910233425/http://v3.mike.tig.as/blog/2010/09/14/pdb">Using the Python debugger in Django</a></p>
| 345 | 2009-07-13T08:29:24Z | [
"python",
"django",
"debugging"
] |
How to debug in Django, the good way? | 1,118,183 | <p>So, I started learning to code in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> and later <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging my Django code. As this was done early in my coding experience, I sat down and wondered if how I was doing this was ineffective and could be done faster. I usually manage to find and correct the bugs in my code, but I wonder if I should be doing it faster?</p>
<p>I usually just use the debug info Django gives when enabled. When things do end up as I thought it would, I break the code flow a lot with a syntax error, and look at the variables at that point in the flow to figure out, where the code does something other than what I wanted.</p>
<p>But can this be improved? Are there some good tools or better ways to debug your Django code?</p>
| 378 | 2009-07-13T07:57:02Z | 1,118,273 | <p>There are a few tools that cooperate well and can make your debugging task easier.</p>
<p>Most important is the <a href="https://github.com/django-debug-toolbar/django-debug-toolbar">Django debug toolbar</a>.</p>
<p>Then you need good logging using the Python <a href="http://docs.python.org/library/logging.html#module-logging">logging</a> facility. You can send logging output to a log file, but an easier option is sending log output to <a href="http://github.com/darwin/firepython/tree/master">firepython</a>. To use this you need to use the Firefox browser with the <a href="http://getfirebug.com/">firebug</a> extension. Firepython includes a firebug plugin that will display any server-side logging in a Firebug tab.</p>
<p>Firebug itself is also critical for debugging the Javascript side of any app you develop. (Assuming you have some JS code of course).</p>
<p>I also liked <a href="http://eric.themoritzfamily.com/2009/02/17/announcing-django-viewtools/">django-viewtools</a> for debugging views interactively using pdb, but I don't use it that much.</p>
<p>There are more useful tools like dozer for tracking down memory leaks (there are also other good suggestions given in answers here on SO for memory tracking).</p>
| 64 | 2009-07-13T08:30:07Z | [
"python",
"django",
"debugging"
] |
How to debug in Django, the good way? | 1,118,183 | <p>So, I started learning to code in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> and later <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging my Django code. As this was done early in my coding experience, I sat down and wondered if how I was doing this was ineffective and could be done faster. I usually manage to find and correct the bugs in my code, but I wonder if I should be doing it faster?</p>
<p>I usually just use the debug info Django gives when enabled. When things do end up as I thought it would, I break the code flow a lot with a syntax error, and look at the variables at that point in the flow to figure out, where the code does something other than what I wanted.</p>
<p>But can this be improved? Are there some good tools or better ways to debug your Django code?</p>
| 378 | 2009-07-13T07:57:02Z | 1,118,314 | <p>I use <a href="http://www.pydev.sourceforge.net/">pyDev</a> with Eclipse really good, set break points, step into code, view values on any objects and variables, try it.</p>
| 13 | 2009-07-13T08:40:54Z | [
"python",
"django",
"debugging"
] |
How to debug in Django, the good way? | 1,118,183 | <p>So, I started learning to code in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> and later <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging my Django code. As this was done early in my coding experience, I sat down and wondered if how I was doing this was ineffective and could be done faster. I usually manage to find and correct the bugs in my code, but I wonder if I should be doing it faster?</p>
<p>I usually just use the debug info Django gives when enabled. When things do end up as I thought it would, I break the code flow a lot with a syntax error, and look at the variables at that point in the flow to figure out, where the code does something other than what I wanted.</p>
<p>But can this be improved? Are there some good tools or better ways to debug your Django code?</p>
| 378 | 2009-07-13T07:57:02Z | 1,118,360 | <p>I really like <a href="http://werkzeug.pocoo.org/">Werkzeug</a>'s interactive debugger. It's similar to Django's debug page, except that you get an interactive shell on every level of the traceback. If you use the <a href="https://github.com/django-extensions/django-extensions">django-extensions</a>, you get a <code>runserver_plus</code> managment command which starts the development server and gives you Werkzeug's debugger on exceptions.</p>
<p>Of course, you should only run this locally, as it gives anyone with a browser the rights to execute arbitrary python code in the context of the server.</p>
| 181 | 2009-07-13T08:54:44Z | [
"python",
"django",
"debugging"
] |
How to debug in Django, the good way? | 1,118,183 | <p>So, I started learning to code in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> and later <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging my Django code. As this was done early in my coding experience, I sat down and wondered if how I was doing this was ineffective and could be done faster. I usually manage to find and correct the bugs in my code, but I wonder if I should be doing it faster?</p>
<p>I usually just use the debug info Django gives when enabled. When things do end up as I thought it would, I break the code flow a lot with a syntax error, and look at the variables at that point in the flow to figure out, where the code does something other than what I wanted.</p>
<p>But can this be improved? Are there some good tools or better ways to debug your Django code?</p>
| 378 | 2009-07-13T07:57:02Z | 2,324,210 | <p>A little quickie for template tags:</p>
<pre><code>@register.filter
def pdb(element):
import pdb; pdb.set_trace()
return element
</code></pre>
<p>Now, inside a template you can do <code>{{ template_var|pdb }}</code> and enter a pdb session (given you're running the local devel server) where you can inspect <code>element</code> to your heart's content.</p>
<p>It's a very nice way to see what's happened to your object when it arrives at the template. </p>
| 138 | 2010-02-24T06:52:09Z | [
"python",
"django",
"debugging"
] |
How to debug in Django, the good way? | 1,118,183 | <p>So, I started learning to code in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> and later <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging my Django code. As this was done early in my coding experience, I sat down and wondered if how I was doing this was ineffective and could be done faster. I usually manage to find and correct the bugs in my code, but I wonder if I should be doing it faster?</p>
<p>I usually just use the debug info Django gives when enabled. When things do end up as I thought it would, I break the code flow a lot with a syntax error, and look at the variables at that point in the flow to figure out, where the code does something other than what I wanted.</p>
<p>But can this be improved? Are there some good tools or better ways to debug your Django code?</p>
| 378 | 2009-07-13T07:57:02Z | 2,324,303 | <p>Almost everything has been mentioned so far, so I'll only add that instead of <code>pdb.set_trace()</code> one can use <strong>ipdb.set_trace()</strong> which uses iPython and therefore is more powerful (autocomplete and other goodies). This requires ipdb package, so you only need to <code>pip install ipdb</code></p>
| 33 | 2010-02-24T07:25:16Z | [
"python",
"django",
"debugging"
] |
How to debug in Django, the good way? | 1,118,183 | <p>So, I started learning to code in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> and later <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging my Django code. As this was done early in my coding experience, I sat down and wondered if how I was doing this was ineffective and could be done faster. I usually manage to find and correct the bugs in my code, but I wonder if I should be doing it faster?</p>
<p>I usually just use the debug info Django gives when enabled. When things do end up as I thought it would, I break the code flow a lot with a syntax error, and look at the variables at that point in the flow to figure out, where the code does something other than what I wanted.</p>
<p>But can this be improved? Are there some good tools or better ways to debug your Django code?</p>
| 378 | 2009-07-13T07:57:02Z | 3,466,951 | <p>I use <a href="http://www.jetbrains.com/pycharm/">PyCharm</a> (same pydev engine as eclipse). Really helps me to visually be able to step through my code and see what is happening.</p>
| 34 | 2010-08-12T11:07:32Z | [
"python",
"django",
"debugging"
] |
How to debug in Django, the good way? | 1,118,183 | <p>So, I started learning to code in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> and later <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging my Django code. As this was done early in my coding experience, I sat down and wondered if how I was doing this was ineffective and could be done faster. I usually manage to find and correct the bugs in my code, but I wonder if I should be doing it faster?</p>
<p>I usually just use the debug info Django gives when enabled. When things do end up as I thought it would, I break the code flow a lot with a syntax error, and look at the variables at that point in the flow to figure out, where the code does something other than what I wanted.</p>
<p>But can this be improved? Are there some good tools or better ways to debug your Django code?</p>
| 378 | 2009-07-13T07:57:02Z | 6,880,214 | <p>I've pushed <code>django-pdb</code> to <a href="http://pypi.python.org/pypi/django-pdb">PyPI</a>.
It's a simple app that means you don't need to edit your source code every time you want to break into pdb.</p>
<p>Installation is just...</p>
<ol>
<li><code>pip install django-pdb</code></li>
<li>Add <code>'django_pdb'</code> to your <code>INSTALLED_APPS</code></li>
</ol>
<p>You can now run: <code>manage.py runserver --pdb</code> to break into pdb at the start of every view...</p>
<pre><code>bash: manage.py runserver --pdb
Validating models...
0 errors found
Django version 1.3, using settings 'testproject.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
GET /
function "myview" in testapp/views.py:6
args: ()
kwargs: {}
> /Users/tom/github/django-pdb/testproject/testapp/views.py(7)myview()
-> a = 1
(Pdb)
</code></pre>
<p>And run: <code>manage.py test --pdb</code> to break into pdb on test failures/errors...</p>
<pre><code>bash: manage.py test testapp --pdb
Creating test database for alias 'default'...
E
======================================================================
>>> test_error (testapp.tests.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File ".../django-pdb/testproject/testapp/tests.py", line 16, in test_error
one_plus_one = four
NameError: global name 'four' is not defined
======================================================================
> /Users/tom/github/django-pdb/testproject/testapp/tests.py(16)test_error()
-> one_plus_one = four
(Pdb)
</code></pre>
<p>The project's hosted on <a href="https://github.com/tomchristie/django-pdb" title="GitHub">GitHub</a>, contributions are welcome of course.</p>
| 21 | 2011-07-30T00:11:18Z | [
"python",
"django",
"debugging"
] |
How to debug in Django, the good way? | 1,118,183 | <p>So, I started learning to code in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> and later <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging my Django code. As this was done early in my coding experience, I sat down and wondered if how I was doing this was ineffective and could be done faster. I usually manage to find and correct the bugs in my code, but I wonder if I should be doing it faster?</p>
<p>I usually just use the debug info Django gives when enabled. When things do end up as I thought it would, I break the code flow a lot with a syntax error, and look at the variables at that point in the flow to figure out, where the code does something other than what I wanted.</p>
<p>But can this be improved? Are there some good tools or better ways to debug your Django code?</p>
| 378 | 2009-07-13T07:57:02Z | 9,154,880 | <p>If using Aptana for django development, watch this: <a href="http://www.youtube.com/watch?v=qQh-UQFltJQ" rel="nofollow">http://www.youtube.com/watch?v=qQh-UQFltJQ</a></p>
<p>If not, consider using it.</p>
| 2 | 2012-02-06T02:05:13Z | [
"python",
"django",
"debugging"
] |
How to debug in Django, the good way? | 1,118,183 | <p>So, I started learning to code in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> and later <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging my Django code. As this was done early in my coding experience, I sat down and wondered if how I was doing this was ineffective and could be done faster. I usually manage to find and correct the bugs in my code, but I wonder if I should be doing it faster?</p>
<p>I usually just use the debug info Django gives when enabled. When things do end up as I thought it would, I break the code flow a lot with a syntax error, and look at the variables at that point in the flow to figure out, where the code does something other than what I wanted.</p>
<p>But can this be improved? Are there some good tools or better ways to debug your Django code?</p>
| 378 | 2009-07-13T07:57:02Z | 10,039,794 | <p>The easiest way to debug python - especially for programmers that are used to Visual Studio - is using PTVS (Python Tools for Visual Studio).
The steps are simple: </p>
<ol>
<li>Download and install it from <a href="http://pytools.codeplex.com/">http://pytools.codeplex.com/</a> </li>
<li>Set breakpoints and press F5. </li>
<li>Your breakpoint is hit, you can view/change the variables as easy as debugging C#/C++ programs. </li>
<li>That's all :) </li>
</ol>
<p>If you want to debug Django using PTVS, you need to do the following: </p>
<ol>
<li>In Project settings - General tab, set "Startup File" to "manage.py", the entry point of the Django program. </li>
<li>In Project settings - Debug tab, set "Script Arguments" to "runserver --noreload". The key point is the "--noreload" here. If you don't set it, your breakpoints won't be hit. </li>
<li>Enjoy it.</li>
</ol>
| 17 | 2012-04-06T06:09:44Z | [
"python",
"django",
"debugging"
] |
How to debug in Django, the good way? | 1,118,183 | <p>So, I started learning to code in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> and later <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging my Django code. As this was done early in my coding experience, I sat down and wondered if how I was doing this was ineffective and could be done faster. I usually manage to find and correct the bugs in my code, but I wonder if I should be doing it faster?</p>
<p>I usually just use the debug info Django gives when enabled. When things do end up as I thought it would, I break the code flow a lot with a syntax error, and look at the variables at that point in the flow to figure out, where the code does something other than what I wanted.</p>
<p>But can this be improved? Are there some good tools or better ways to debug your Django code?</p>
| 378 | 2009-07-13T07:57:02Z | 11,884,452 | <p>Most options are alredy mentioned.
To print template context, I've created a simple library for that.
See <a href="https://github.com/edoburu/django-debugtools" rel="nofollow">https://github.com/edoburu/django-debugtools</a></p>
<p>You can use it to print template context without any <code>{% load %}</code> construct:</p>
<pre><code>{% print var %} prints variable
{% print %} prints all
</code></pre>
<p>It uses a customized pprint format to display the variables in a <code><pre></code> tag.</p>
| 2 | 2012-08-09T13:22:54Z | [
"python",
"django",
"debugging"
] |
How to debug in Django, the good way? | 1,118,183 | <p>So, I started learning to code in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> and later <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging my Django code. As this was done early in my coding experience, I sat down and wondered if how I was doing this was ineffective and could be done faster. I usually manage to find and correct the bugs in my code, but I wonder if I should be doing it faster?</p>
<p>I usually just use the debug info Django gives when enabled. When things do end up as I thought it would, I break the code flow a lot with a syntax error, and look at the variables at that point in the flow to figure out, where the code does something other than what I wanted.</p>
<p>But can this be improved? Are there some good tools or better ways to debug your Django code?</p>
| 378 | 2009-07-13T07:57:02Z | 15,304,395 | <p>I highly recommend epdb (Extended Python Debugger). </p>
<p><a href="https://bitbucket.org/dugan/epdb">https://bitbucket.org/dugan/epdb</a></p>
<p>One thing I love about epdb for debugging Django or other Python webservers is the epdb.serve() command. This sets a trace and serves this on a local port that you can connect to. Typical use case:</p>
<p>I have a view that I want to go through step-by-step. I'll insert the following at the point I want to set the trace.</p>
<pre><code>import epdb; epdb.serve()
</code></pre>
<p>Once this code gets executed, I open a Python interpreter and connect to the serving instance. I can analyze all the values and step through the code using the standard pdb commands like n, s, etc.</p>
<pre><code>In [2]: import epdb; epdb.connect()
(Epdb) request
<WSGIRequest
path:/foo,
GET:<QueryDict: {}>,
POST:<QuestDict: {}>,
...
>
(Epdb) request.session.session_key
'i31kq7lljj3up5v7hbw9cff0rga2vlq5'
(Epdb) list
85 raise some_error.CustomError()
86
87 # Example login view
88 def login(request, username, password):
89 import epdb; epdb.serve()
90 -> return my_login_method(username, password)
91
92 # Example view to show session key
93 def get_session_key(request):
94 return request.session.session_key
95
</code></pre>
<p>And tons more that you can learn about typing epdb help at any time.</p>
<p>If you want to serve or connect to multiple epdb instances at the same time, you can specify the port to listen on (default is 8080). I.e.</p>
<pre><code>import epdb; epdb.serve(4242)
>> import epdb; epdb.connect(host='192.168.3.2', port=4242)
</code></pre>
<p>host defaults to 'localhost' if not specified. I threw it in here to demonstrate how you can use this to debug something other than a local instance, like a development server on your local LAN. Obviously, if you do this be careful that the set trace never makes it onto your production server!</p>
<p>As a quick note, you can still do the same thing as the accepted answer with epdb (<code>import epdb; epdb.set_trace()</code>) but I wanted to highlight the serve functionality since I've found it so useful.</p>
| 6 | 2013-03-08T22:26:24Z | [
"python",
"django",
"debugging"
] |
How to debug in Django, the good way? | 1,118,183 | <p>So, I started learning to code in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> and later <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging my Django code. As this was done early in my coding experience, I sat down and wondered if how I was doing this was ineffective and could be done faster. I usually manage to find and correct the bugs in my code, but I wonder if I should be doing it faster?</p>
<p>I usually just use the debug info Django gives when enabled. When things do end up as I thought it would, I break the code flow a lot with a syntax error, and look at the variables at that point in the flow to figure out, where the code does something other than what I wanted.</p>
<p>But can this be improved? Are there some good tools or better ways to debug your Django code?</p>
| 378 | 2009-07-13T07:57:02Z | 17,351,366 | <p>I use <a href="http://www.jetbrains.com/pycharm/" rel="nofollow">PyCharm</a> and different debug tools. Also have a nice articles set about easy set up those things for novices. <a href="http://garmoncheg.blogspot.com/2013/06/django-how-to-debug-django.html" rel="nofollow">You may start here.</a> It tells about PDB and GUI debugging in general with Django projects. Hope someone would benefit from them.</p>
| 3 | 2013-06-27T19:12:02Z | [
"python",
"django",
"debugging"
] |
How to debug in Django, the good way? | 1,118,183 | <p>So, I started learning to code in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> and later <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging my Django code. As this was done early in my coding experience, I sat down and wondered if how I was doing this was ineffective and could be done faster. I usually manage to find and correct the bugs in my code, but I wonder if I should be doing it faster?</p>
<p>I usually just use the debug info Django gives when enabled. When things do end up as I thought it would, I break the code flow a lot with a syntax error, and look at the variables at that point in the flow to figure out, where the code does something other than what I wanted.</p>
<p>But can this be improved? Are there some good tools or better ways to debug your Django code?</p>
| 378 | 2009-07-13T07:57:02Z | 17,560,099 | <p>I just found wdb (<a href="http://www.rkblog.rk.edu.pl/w/p/debugging-python-code-browser-wdb-debugger/?goback=%2Egde_25827_member_255996401">http://www.rkblog.rk.edu.pl/w/p/debugging-python-code-browser-wdb-debugger/?goback=%2Egde_25827_member_255996401</a>). It has a pretty nice user interface / GUI with all the bells and whistles. Author says this about wdb -</p>
<p>"There are IDEs like PyCharm that have their own debuggers. They offer similar or equal set of features ... However to use them you have to use those specific IDEs (and some of then are non-free or may not be available for all platforms). Pick the right tool for your needs."</p>
<p>Thought i'd just pass it on.</p>
<p><strong>Also a very helpful article about python debuggers:</strong>
<a href="https://zapier.com/engineering/debugging-python-boss/">https://zapier.com/engineering/debugging-python-boss/</a></p>
<p><strong>Finally</strong>, if you'd like to see a nice graphical printout of your call stack in Django, checkout:
<a href="https://github.com/joerick/pyinstrument">https://github.com/joerick/pyinstrument</a>. Just add pyinstrument.middleware.ProfilerMiddleware to MIDDLEWARE_CLASSES, then add ?profile to the end of the request URL to activate the profiler. </p>
<p>Can also run pyinstrument from command line or by importing as a module.</p>
| 6 | 2013-07-09T23:38:42Z | [
"python",
"django",
"debugging"
] |
How to debug in Django, the good way? | 1,118,183 | <p>So, I started learning to code in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> and later <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging my Django code. As this was done early in my coding experience, I sat down and wondered if how I was doing this was ineffective and could be done faster. I usually manage to find and correct the bugs in my code, but I wonder if I should be doing it faster?</p>
<p>I usually just use the debug info Django gives when enabled. When things do end up as I thought it would, I break the code flow a lot with a syntax error, and look at the variables at that point in the flow to figure out, where the code does something other than what I wanted.</p>
<p>But can this be improved? Are there some good tools or better ways to debug your Django code?</p>
| 378 | 2009-07-13T07:57:02Z | 17,892,930 | <p>Sometimes when I wan to explore around in a particular method and summoning pdb is just too cumbersome, I would add:</p>
<pre><code>import IPython; IPython.embed()
</code></pre>
<p><code>IPython.embed()</code> starts an IPython shell which have access to the local variables from the point where you call it. </p>
| 6 | 2013-07-27T00:15:25Z | [
"python",
"django",
"debugging"
] |
How to debug in Django, the good way? | 1,118,183 | <p>So, I started learning to code in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> and later <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging my Django code. As this was done early in my coding experience, I sat down and wondered if how I was doing this was ineffective and could be done faster. I usually manage to find and correct the bugs in my code, but I wonder if I should be doing it faster?</p>
<p>I usually just use the debug info Django gives when enabled. When things do end up as I thought it would, I break the code flow a lot with a syntax error, and look at the variables at that point in the flow to figure out, where the code does something other than what I wanted.</p>
<p>But can this be improved? Are there some good tools or better ways to debug your Django code?</p>
| 378 | 2009-07-13T07:57:02Z | 19,250,270 | <p>I use <a href="http://www.jetbrains.com/pycharm/">PyCharm</a> and stand by it all the way. It cost me a little but I have to say the advantage that I get out of it is priceless. I tried debugging from console and I do give people a lot of credit who can do that, but for me being able to visually debug my application(s) is great.</p>
<p>I have to say though, <a href="http://www.jetbrains.com/pycharm/">PyCharm</a> does take a lot of memory. But then again, nothing good is free in life. They just came with their latest version 3. It also plays very well with Django, Flask and Google AppEngine. So, all in all, I'd say it's a great handy tool to have for any developer.</p>
<p>If you are not using it yet, I'd recommend to get the trial version for 30 days to take a look at the power of PyCharm. I'm sure there are other tools also available, such as Aptana. But I guess I just also like the way PyCharm looks. I feel very comfortable debugging my apps there.</p>
| 6 | 2013-10-08T14:18:43Z | [
"python",
"django",
"debugging"
] |
How to debug in Django, the good way? | 1,118,183 | <p>So, I started learning to code in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> and later <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging my Django code. As this was done early in my coding experience, I sat down and wondered if how I was doing this was ineffective and could be done faster. I usually manage to find and correct the bugs in my code, but I wonder if I should be doing it faster?</p>
<p>I usually just use the debug info Django gives when enabled. When things do end up as I thought it would, I break the code flow a lot with a syntax error, and look at the variables at that point in the flow to figure out, where the code does something other than what I wanted.</p>
<p>But can this be improved? Are there some good tools or better ways to debug your Django code?</p>
| 378 | 2009-07-13T07:57:02Z | 26,323,570 | <p>i highly suggest to use PDB.</p>
<pre><code>import pdb
pdb.set_trace()
</code></pre>
<p>You can inspect all the variables values, step in to the function and much more.
<a href="https://docs.python.org/2/library/pdb.html" rel="nofollow">https://docs.python.org/2/library/pdb.html</a></p>
<p>for checking out the all kind of request,response and hits to database.i am using django-debug-toolbar
<a href="https://github.com/django-debug-toolbar/django-debug-toolbar" rel="nofollow">https://github.com/django-debug-toolbar/django-debug-toolbar</a></p>
| 1 | 2014-10-12T09:14:05Z | [
"python",
"django",
"debugging"
] |
How to debug in Django, the good way? | 1,118,183 | <p>So, I started learning to code in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> and later <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging my Django code. As this was done early in my coding experience, I sat down and wondered if how I was doing this was ineffective and could be done faster. I usually manage to find and correct the bugs in my code, but I wonder if I should be doing it faster?</p>
<p>I usually just use the debug info Django gives when enabled. When things do end up as I thought it would, I break the code flow a lot with a syntax error, and look at the variables at that point in the flow to figure out, where the code does something other than what I wanted.</p>
<p>But can this be improved? Are there some good tools or better ways to debug your Django code?</p>
| 378 | 2009-07-13T07:57:02Z | 33,038,237 | <p>As mentioned in other posts here - setting breakpoints in your code and walking thru the code to see if it behaves as you expected is a great way to learn something like Django until you have a good sense of how it all behaves - and what your code is doing.</p>
<p>To do this I would recommend using WingIde. Just like other mentioned IDEs nice and easy to use, nice layout and also easy to set breakpoints evaluate / modify the stack etc. Perfect for visualizing what your code is doing as you step through it. I'm a big fan of it.</p>
<p>Also I use PyCharm - it has excellent static code analysis and can help sometimes spot problems before you realize they are there.</p>
<p>As mentioned already django-debug-toolbar is essential - <a href="https://github.com/django-debug-toolbar/django-debug-toolbar" rel="nofollow">https://github.com/django-debug-toolbar/django-debug-toolbar</a></p>
<p>And while not explicitly a debug or analysis tool - one of my favorites is <strong>SQL Printing Middleware</strong> available from Django Snippets at <a href="https://djangosnippets.org/snippets/290/" rel="nofollow">https://djangosnippets.org/snippets/290/</a></p>
<p>This will display the SQL queries that your view has generated. This will give you a good sense of what the ORM is doing and if your queries are efficient or you need to rework your code (or add caching).</p>
<p>I find it invaluable for keeping an eye on query performance while developing and debugging my application. </p>
<p>Just one other tip - I modified it slightly for my own use to only show the summary and not the SQL statement.... So I always use it while developing and testing. I also added that if the len(connection.queries) is greater than a pre-defined threshold it displays an extra warning.</p>
<p>Then if I spot something bad (from a performance or number of queries perspective) is happening I turn back on the full display of the SQL statements to see exactly what is going on. Very handy when you are working on a large Django project with multiple developers.</p>
| 1 | 2015-10-09T12:24:44Z | [
"python",
"django",
"debugging"
] |
How to debug in Django, the good way? | 1,118,183 | <p>So, I started learning to code in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> and later <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging my Django code. As this was done early in my coding experience, I sat down and wondered if how I was doing this was ineffective and could be done faster. I usually manage to find and correct the bugs in my code, but I wonder if I should be doing it faster?</p>
<p>I usually just use the debug info Django gives when enabled. When things do end up as I thought it would, I break the code flow a lot with a syntax error, and look at the variables at that point in the flow to figure out, where the code does something other than what I wanted.</p>
<p>But can this be improved? Are there some good tools or better ways to debug your Django code?</p>
| 378 | 2009-07-13T07:57:02Z | 34,699,590 | <p>From my perspective, we could break down common <em>code debugging</em> tasks into three distinct usage patterns:</p>
<ol>
<li>Something has <strong>raised an exception</strong>: <a href="https://github.com/django-extensions/django-extensions">runserver_plus</a>' Werkzeug debugger to the rescue. The ability to run custom code at all the trace levels is a killer. And if you're completely stuck, you can create a Gist to share with just a click.</li>
<li>Page is rendered, but the <strong>result is wrong</strong>: again, Werkzeug rocks. To make a breakpoint in code, just type <code>assert False</code> in the place you want to stop at.</li>
<li><strong>Code works wrong</strong>, but the quick look doesn't help. Most probably, an algorithmic problem. Sigh. Then I usually fire up a console debugger <a href="https://pypi.python.org/pypi/pudb">PuDB</a>: <code>import pudb; pudb.set_trace()</code>. The main advantage over [i]pdb is that PuDB (while looking as you're in 80's) makes setting custom watch expressions a breeze. And debugging a bunch of nested loops is much simpler with a GUI.</li>
</ol>
<p>Ah, yes, the templates' woes. The most common (to me and my colleagues) problem is a wrong context: either you don't have a variable, or your variable doesn't have some attribute. If you're using <a href="https://github.com/django-debug-toolbar/django-debug-toolbar">debug toolbar</a>, just inspect the context at the "Templates" section, or, if it's not sufficient, set a break in your views' code just after your context is filled up.</p>
<p>So it goes.</p>
| 6 | 2016-01-09T22:17:57Z | [
"python",
"django",
"debugging"
] |
How to debug in Django, the good way? | 1,118,183 | <p>So, I started learning to code in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> and later <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging my Django code. As this was done early in my coding experience, I sat down and wondered if how I was doing this was ineffective and could be done faster. I usually manage to find and correct the bugs in my code, but I wonder if I should be doing it faster?</p>
<p>I usually just use the debug info Django gives when enabled. When things do end up as I thought it would, I break the code flow a lot with a syntax error, and look at the variables at that point in the flow to figure out, where the code does something other than what I wanted.</p>
<p>But can this be improved? Are there some good tools or better ways to debug your Django code?</p>
| 378 | 2009-07-13T07:57:02Z | 38,065,474 | <p>An additional suggestion. </p>
<p>You can leverage <strong>nosetests</strong> and <strong>pdb</strong> together, rather injecting <code>pdb.set_trace()</code> in your views manually. The advantage is that you can observe error conditions when they first start, potentially in 3rd party code.</p>
<p>Here's an error for me today.</p>
<pre><code>TypeError at /db/hcm91dmo/catalog/records/
render_option() argument after * must be a sequence, not int
....
Error during template rendering
In template /opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/crispy_forms/templates/bootstrap3/field.html, error at line 28
render_option() argument after * must be a sequence, not int
18
19 {% if field|is_checkboxselectmultiple %}
20 {% include 'bootstrap3/layout/checkboxselectmultiple.html' %}
21 {% endif %}
22
23 {% if field|is_radioselect %}
24 {% include 'bootstrap3/layout/radioselect.html' %}
25 {% endif %}
26
27 {% if not field|is_checkboxselectmultiple and not field|is_radioselect %}
28
{% if field|is_checkbox and form_show_labels %}
</code></pre>
<p>Now, I know this means that I goofed the constructor for the form, and I even have good idea of which field is a problem. But, can I use pdb to see what crispy forms is complaining about, <strong>within a template</strong>?</p>
<p>Yes, I can. Using the <em>--pdb</em> option on nosetests:</p>
<p><code>tests$ nosetests test_urls_catalog.py --pdb</code></p>
<p>As soon as I hit any exception (including ones handled gracefully), pdb stops where it happens and I can look around.</p>
<pre><code> File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/forms.py", line 537, in __str__
return self.as_widget()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/forms.py", line 593, in as_widget
return force_text(widget.render(name, self.value(), attrs=attrs))
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/widgets.py", line 513, in render
options = self.render_options(choices, [value])
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/widgets.py", line 543, in render_options
output.append(self.render_option(selected_choices, *option))
TypeError: render_option() argument after * must be a sequence, not int
INFO lib.capture_middleware log write_to_index(http://localhost:8082/db/hcm91dmo/catalog/records.html)
INFO lib.capture_middleware log write_to_index:end
> /opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/widgets.py(543)render_options()
-> output.append(self.render_option(selected_choices, *option))
(Pdb) import pprint
(Pdb) pprint.PrettyPrinter(indent=4).pprint(self)
<django.forms.widgets.Select object at 0x115fe7d10>
(Pdb) pprint.PrettyPrinter(indent=4).pprint(vars(self))
{ 'attrs': { 'class': 'select form-control'},
'choices': [[('_', 'any type'), (7, (7, 'type 7', 'RECTYPE_TABLE'))]],
'is_required': False}
(Pdb)
</code></pre>
<p>Now, it's clear that my choices argument to the crispy field constructor was as it was a list within a list, rather than a list/tuple of tuples.</p>
<pre><code> 'choices': [[('_', 'any type'), (7, (7, 'type 7', 'RECTYPE_TABLE'))]]
</code></pre>
<p>The neat thing is that this pdb is taking place within crispy's code, not mine and I didn't need to insert it manually.</p>
| 0 | 2016-06-28T01:01:29Z | [
"python",
"django",
"debugging"
] |
How to debug in Django, the good way? | 1,118,183 | <p>So, I started learning to code in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> and later <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging my Django code. As this was done early in my coding experience, I sat down and wondered if how I was doing this was ineffective and could be done faster. I usually manage to find and correct the bugs in my code, but I wonder if I should be doing it faster?</p>
<p>I usually just use the debug info Django gives when enabled. When things do end up as I thought it would, I break the code flow a lot with a syntax error, and look at the variables at that point in the flow to figure out, where the code does something other than what I wanted.</p>
<p>But can this be improved? Are there some good tools or better ways to debug your Django code?</p>
| 378 | 2009-07-13T07:57:02Z | 38,287,020 | <p>I like answers I can copy directly. And I like IPython:</p>
<pre><code>pip install ipdb
</code></pre>
<p>In your code:</p>
<pre><code>import ipdb; ipdb.set_trace()
</code></pre>
| 1 | 2016-07-09T22:52:30Z | [
"python",
"django",
"debugging"
] |
How to debug in Django, the good way? | 1,118,183 | <p>So, I started learning to code in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> and later <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging my Django code. As this was done early in my coding experience, I sat down and wondered if how I was doing this was ineffective and could be done faster. I usually manage to find and correct the bugs in my code, but I wonder if I should be doing it faster?</p>
<p>I usually just use the debug info Django gives when enabled. When things do end up as I thought it would, I break the code flow a lot with a syntax error, and look at the variables at that point in the flow to figure out, where the code does something other than what I wanted.</p>
<p>But can this be improved? Are there some good tools or better ways to debug your Django code?</p>
| 378 | 2009-07-13T07:57:02Z | 39,866,246 | <p>use <code>pdb</code> or <code>ipdb</code>. Diffrence between these two is ipdb supports auto complete.</p>
<p>for pdb</p>
<pre><code>import pdb
pdb.set_trace()
</code></pre>
<p>for ipdb</p>
<pre><code>import ipdb
ipdb.set_trace()
</code></pre>
<p>For executing new line hit <code>n</code> key, for continue hit <code>c</code> key.
check more options by using <code>help(pdb)</code></p>
| 0 | 2016-10-05T05:45:53Z | [
"python",
"django",
"debugging"
] |
Is there a way to know which versions of python are supported by my code? | 1,118,208 | <p>You may know the Windows compliance tool that helps people to know if their code is supported by any version of the MS OS.</p>
<p>I am looking something similar for Python. </p>
<p>I am writing a lib with Python 2.6 and I realized that it was not compatible with Python 2.5 due to the use of the with keyword. </p>
<p>I would like to know if there is a simple and automatic way to avoid this situation in the future.</p>
<p>I am also interested in something similar to know which OS are supported.</p>
<p>Thanks for your help</p>
| 3 | 2009-07-13T08:05:03Z | 1,118,220 | <p>In response to <a href="http://stackoverflow.com/questions/804538/tool-to-determine-what-lowest-version-of-python-required">a previous question about this</a>, I wrote <a href="http://github.com/ghewgill/pyqver/tree/master" rel="nofollow">pyqver</a>. If you have any improvements, please feel free to fork and contribute!</p>
| 7 | 2009-07-13T08:09:04Z | [
"python",
"dependencies",
"versioning"
] |
Is there a way to know which versions of python are supported by my code? | 1,118,208 | <p>You may know the Windows compliance tool that helps people to know if their code is supported by any version of the MS OS.</p>
<p>I am looking something similar for Python. </p>
<p>I am writing a lib with Python 2.6 and I realized that it was not compatible with Python 2.5 due to the use of the with keyword. </p>
<p>I would like to know if there is a simple and automatic way to avoid this situation in the future.</p>
<p>I am also interested in something similar to know which OS are supported.</p>
<p>Thanks for your help</p>
| 3 | 2009-07-13T08:05:03Z | 1,118,459 | <p>I recommend you rather use automated tests than a code analysis tool.</p>
<p>Be aware that there are subtle behaviour changes in the Python standard library that your code may or may not depend upon. For example <code>httplib</code>: When uploading files, it is normal to give the data as a <code>str</code>. In Python 2.6 you <em>can</em> give stream objects instead (useful for >1GB files) if you nudge them correctly, but in Python 2.5 you will get an error.</p>
<p>A comprehensive set of unit tests and integration tests will be much more reliable because they test that your program actually <em>works</em> on Python version X.Y.</p>
<pre><code>$ python2.6 tests/run_all.py
.................................
33 tests passed
[OK]
</code></pre>
<p>You're Python 2.6 compatible.</p>
<pre><code>$ python2.4 tests/run_all.py
...........EEE.........EEE.......
27 tests passed, 6 errors
[FAIL]
</code></pre>
<p>You're <em>not</em> Python 2.4 compatible.</p>
| 6 | 2009-07-13T09:24:52Z | [
"python",
"dependencies",
"versioning"
] |
Is there a way to know which versions of python are supported by my code? | 1,118,208 | <p>You may know the Windows compliance tool that helps people to know if their code is supported by any version of the MS OS.</p>
<p>I am looking something similar for Python. </p>
<p>I am writing a lib with Python 2.6 and I realized that it was not compatible with Python 2.5 due to the use of the with keyword. </p>
<p>I would like to know if there is a simple and automatic way to avoid this situation in the future.</p>
<p>I am also interested in something similar to know which OS are supported.</p>
<p>Thanks for your help</p>
| 3 | 2009-07-13T08:05:03Z | 1,118,558 | <p>Python 2.5 can still be saved, since it can use the with keyword:</p>
<pre><code>from __future__ import with_statement
</code></pre>
| 0 | 2009-07-13T09:51:55Z | [
"python",
"dependencies",
"versioning"
] |
List of values to a sound file | 1,118,266 | <p>Guys,
Im trying to engineer in python a way of transforming a list of integer values between 0-255 into representative equivalent tones from 1500-2200Hz. Timing information (at 1200Hz) is given by the (-1),(-2) and (-3) values. I have created a function that generates a .wav file and then call this function with the parameters of each tone.
I need to create a 'stream' either by concatenating lots of individual tones into one output file or creating some way of running through the entire list and creating a separate file. Or by some other crazy function I don't know of....
The timing information will vary in duration but the information bits (0-255) will all be fixed length. </p>
<p>A sample of the list is shown below:</p>
<p>[-2, 3, 5, 7, 7, 7, 16, 9, 10, 21, 16, -1, 19, 13, 8, 8, 0, 5, 9, 21, 19, 11, -1, 11, 16, 19, 5, 21, 34, 39, 46, 58, 50, -1, 35, 46, 17, 28, 23, 19, 8, 2, 13, 12, -1, 9, 6, 8, 11, 2, 3, 2, 13, 14, 42, -1, 35, 41, 46, 55, 73, 69, 56, 47, 45, 26, -1, -3] </p>
<p>The current solution I'm thinking of involves opening the file, checking the next value in the list using an 'if' statement to check whether the bit is timing (-ve) and if not: run an algorithm to see what freq needs to be generated and add the tone to the output file. Continue until -3 or end of list.</p>
<p>Can anyone guide on how this complete output file might be created or any suggestions...
I'm new to programming so please be gentle. Thanks in advance </p>
| 0 | 2009-07-13T08:27:25Z | 1,118,303 | <p>Looks like you're trying to reinvent the wheel, be careful...
If you want to generate music from arrays then you can have a look at pyaudiere, a simple wrapper upon the audiere library. See the docs for how to open an array but it looks should like this : </p>
<pre><code>import audiere
d = audiere.open_device()
s = d.open_array(buff,fs)
s.play()
</code></pre>
<p>the documentation for this call is:</p>
<p><strong>open_array(buffer, fs)</strong> :</p>
<p>Opens a sound buffer for playback, and returns an OutputStream object for it. The buffer should be a NumPy array of Float32's with one or two columns for mono of stereo playback. The second parameter is the sampling frequency. Values outside the range +-1 will be clipped. </p>
| 2 | 2009-07-13T08:38:44Z | [
"python",
"audio"
] |
List of values to a sound file | 1,118,266 | <p>Guys,
Im trying to engineer in python a way of transforming a list of integer values between 0-255 into representative equivalent tones from 1500-2200Hz. Timing information (at 1200Hz) is given by the (-1),(-2) and (-3) values. I have created a function that generates a .wav file and then call this function with the parameters of each tone.
I need to create a 'stream' either by concatenating lots of individual tones into one output file or creating some way of running through the entire list and creating a separate file. Or by some other crazy function I don't know of....
The timing information will vary in duration but the information bits (0-255) will all be fixed length. </p>
<p>A sample of the list is shown below:</p>
<p>[-2, 3, 5, 7, 7, 7, 16, 9, 10, 21, 16, -1, 19, 13, 8, 8, 0, 5, 9, 21, 19, 11, -1, 11, 16, 19, 5, 21, 34, 39, 46, 58, 50, -1, 35, 46, 17, 28, 23, 19, 8, 2, 13, 12, -1, 9, 6, 8, 11, 2, 3, 2, 13, 14, 42, -1, 35, 41, 46, 55, 73, 69, 56, 47, 45, 26, -1, -3] </p>
<p>The current solution I'm thinking of involves opening the file, checking the next value in the list using an 'if' statement to check whether the bit is timing (-ve) and if not: run an algorithm to see what freq needs to be generated and add the tone to the output file. Continue until -3 or end of list.</p>
<p>Can anyone guide on how this complete output file might be created or any suggestions...
I'm new to programming so please be gentle. Thanks in advance </p>
| 0 | 2009-07-13T08:27:25Z | 1,120,253 | <p>All you need to do is just append the new data on the end of your wav file. So if you haven't closed your file, just keep writing to it, or if you have, reopen it in append mode (<code>w = open(myfile, 'ba')</code>) and write the new data.</p>
<p>For this to sound reasonable without clicks and such, the trick will be to make the waveform continuous from one frequency to the next. Assuming that you're using sine waves of the same amplitude, you need to start each sine wave with the same phase that you ended the previous. You can do this either by playing with the length of the waveform to make sure you always end at, say, zero phase and then always start at zero phase, or by explicitly including the phase in the sine wave. </p>
| 0 | 2009-07-13T15:41:32Z | [
"python",
"audio"
] |
List of values to a sound file | 1,118,266 | <p>Guys,
Im trying to engineer in python a way of transforming a list of integer values between 0-255 into representative equivalent tones from 1500-2200Hz. Timing information (at 1200Hz) is given by the (-1),(-2) and (-3) values. I have created a function that generates a .wav file and then call this function with the parameters of each tone.
I need to create a 'stream' either by concatenating lots of individual tones into one output file or creating some way of running through the entire list and creating a separate file. Or by some other crazy function I don't know of....
The timing information will vary in duration but the information bits (0-255) will all be fixed length. </p>
<p>A sample of the list is shown below:</p>
<p>[-2, 3, 5, 7, 7, 7, 16, 9, 10, 21, 16, -1, 19, 13, 8, 8, 0, 5, 9, 21, 19, 11, -1, 11, 16, 19, 5, 21, 34, 39, 46, 58, 50, -1, 35, 46, 17, 28, 23, 19, 8, 2, 13, 12, -1, 9, 6, 8, 11, 2, 3, 2, 13, 14, 42, -1, 35, 41, 46, 55, 73, 69, 56, 47, 45, 26, -1, -3] </p>
<p>The current solution I'm thinking of involves opening the file, checking the next value in the list using an 'if' statement to check whether the bit is timing (-ve) and if not: run an algorithm to see what freq needs to be generated and add the tone to the output file. Continue until -3 or end of list.</p>
<p>Can anyone guide on how this complete output file might be created or any suggestions...
I'm new to programming so please be gentle. Thanks in advance </p>
| 0 | 2009-07-13T08:27:25Z | 1,705,021 | <p>I'm not sure I understand exactly what you're asking, but I'll try to answer.</p>
<p>I wouldn't mess around with the low-level WAV format if I didn't have to. Just use <a href="http://cournape.github.com/audiolab/" rel="nofollow">Audiolab</a> for this.</p>
<ol>
<li>Initialize an empty <code>song</code> NumPy 1-D array</li>
<li>Open your file of numbers</li>
<li>Use the <code>if</code> statement as you said, to detect if it's a negative or positive number</li>
<li>Generate a "snippet" of tone according to your formula (which I don't really understand from the description).
<ol>
<li>First generate a timebase with something like <code>t = linspace(0,1,num=48000)</code></li>
<li>Then generate the tone with something like <code>a = sin(2*pi*f*t)</code></li>
</ol></li>
<li>Concatenate the snippet onto the rest of the array with something like <code>song = concatenate((song,a))</code></li>
<li>Loop through the file to create and concatenate each snippet</li>
<li>Write to a WAV file using something like <code>wavwrite(song, 'filename.wav', fs, enc)</code></li>
</ol>
<p>Did you think up this format of tones and timing yourself or is it something created by others?</p>
| 0 | 2009-11-10T00:58:52Z | [
"python",
"audio"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.