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
Why would traceback.extract_stack() return [] when there is definitely a call stack?
1,252,823
<p>I have a class that calls</p> <pre><code>traceback.extract_stack() </code></pre> <p>in its <code>__init__()</code>, but whenever I do that, the value of <code>traceback.extract_stack()</code> is <code>[]</code>.</p> <p>What are some reasons that this could be the case? Is there another way to get a traceback that...
0
2009-08-10T01:43:15Z
1,252,831
<p>Looking at the code for the traceback module, one possibility is that you've got sys.tracebacklimit set to zero, though that seems like a longshot...</p>
0
2009-08-10T01:49:11Z
[ "python", "stack-trace" ]
Why would traceback.extract_stack() return [] when there is definitely a call stack?
1,252,823
<p>I have a class that calls</p> <pre><code>traceback.extract_stack() </code></pre> <p>in its <code>__init__()</code>, but whenever I do that, the value of <code>traceback.extract_stack()</code> is <code>[]</code>.</p> <p>What are some reasons that this could be the case? Is there another way to get a traceback that...
0
2009-08-10T01:43:15Z
1,252,853
<p>Following shows traceback.extract_stack() working when called from a class's <code>__init__</code> method. Please post your code showing that it doesn't work. Include the Python version. Don't type from memory; use copy/paste as I have done.</p> <pre><code>Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.150...
1
2009-08-10T01:59:31Z
[ "python", "stack-trace" ]
Why would traceback.extract_stack() return [] when there is definitely a call stack?
1,252,823
<p>I have a class that calls</p> <pre><code>traceback.extract_stack() </code></pre> <p>in its <code>__init__()</code>, but whenever I do that, the value of <code>traceback.extract_stack()</code> is <code>[]</code>.</p> <p>What are some reasons that this could be the case? Is there another way to get a traceback that...
0
2009-08-10T01:43:15Z
1,257,132
<p>The reason turned out to be that someone turned on Pysco on the project, and Psyco doesn't play nice with the traceback module.</p>
0
2009-08-10T20:49:27Z
[ "python", "stack-trace" ]
How to include and use .eggs/pkg_resources within a project directory targeting python 2.5.1
1,252,910
<p>I have python .egg files that are stored in a relative location to some .py code. The problem is, I am targeting python 2.5.1 computers which require my project be self contained in a folder (hundreds of thousands of OLPC XO 8.2.1 release laptops running Sugar). This means I cannot just ./ez_install to perform a s...
3
2009-08-10T02:40:14Z
1,252,942
<p><strong>Include pkg_resources.py in the <code>lib/</code> directory.</strong></p> <p>Add at the top of example.py...</p> <pre><code> import sys sys.path.append("lib/") import pkg_resources </code></pre> <p>and then you can...</p> <pre><code> sys.path.append("library1.egg") sys.path.append("libs/libr...
0
2009-08-10T03:01:53Z
[ "python", "egg", "python-2.5", "olpc" ]
How to include and use .eggs/pkg_resources within a project directory targeting python 2.5.1
1,252,910
<p>I have python .egg files that are stored in a relative location to some .py code. The problem is, I am targeting python 2.5.1 computers which require my project be self contained in a folder (hundreds of thousands of OLPC XO 8.2.1 release laptops running Sugar). This means I cannot just ./ez_install to perform a s...
3
2009-08-10T02:40:14Z
2,898,409
<p>If you want to be able to use pkg_resources, just copy pkg_resources.py alongside your application's main script. It's designed to be able to be used this way as a standalone runtime.</p>
1
2010-05-24T16:14:06Z
[ "python", "egg", "python-2.5", "olpc" ]
Distributing my python scripts as jars with jython?
1,252,965
<p>I have been a python programmer for almost 2 years and I am used to writing small scripts to automate some repetitive tasks I had to do at office. Now, apparently my colleagues noticed this and they want those scripts too.</p> <p>Some of them have macs, some windows, I made these on windows. I investigated the poss...
50
2009-08-10T03:11:51Z
1,253,267
<p>The 'jythonc' command should be able to compile your .py source into JVM bytecode, which should make it portable to any Java install. Or so I read at: <a href="http://hell.org.ua/Docs/oreilly/other2/python/0596001886%5Fpythonian-chp-25-sect-3.html" rel="nofollow">http://hell.org.ua/Docs/oreilly/other2/python/059600...
1
2009-08-10T05:47:00Z
[ "python", "jython", "distribution", "executable-jar" ]
Distributing my python scripts as jars with jython?
1,252,965
<p>I have been a python programmer for almost 2 years and I am used to writing small scripts to automate some repetitive tasks I had to do at office. Now, apparently my colleagues noticed this and they want those scripts too.</p> <p>Some of them have macs, some windows, I made these on windows. I investigated the poss...
50
2009-08-10T03:11:51Z
1,255,113
<p>The best current techniques for distributing your Python files in a jar are detailed in this article on Jython's wiki: <a href="http://wiki.python.org/jython/JythonFaq/DistributingJythonScripts">http://wiki.python.org/jython/JythonFaq/DistributingJythonScripts</a></p> <p>For your case, I think you would want to tak...
57
2009-08-10T14:12:55Z
[ "python", "jython", "distribution", "executable-jar" ]
Distributing my python scripts as jars with jython?
1,252,965
<p>I have been a python programmer for almost 2 years and I am used to writing small scripts to automate some repetitive tasks I had to do at office. Now, apparently my colleagues noticed this and they want those scripts too.</p> <p>Some of them have macs, some windows, I made these on windows. I investigated the poss...
50
2009-08-10T03:11:51Z
14,900,677
<p>I experienced a similar issue in that I want to be able to create simple command line calls for my jython apps, not require that the user go through the jython installation process, and be able to have the jython scripts append library dependencies at runtime to sys.path so as to include core java code.</p> <pre><c...
2
2013-02-15T18:04:39Z
[ "python", "jython", "distribution", "executable-jar" ]
Distributing my python scripts as jars with jython?
1,252,965
<p>I have been a python programmer for almost 2 years and I am used to writing small scripts to automate some repetitive tasks I had to do at office. Now, apparently my colleagues noticed this and they want those scripts too.</p> <p>Some of them have macs, some windows, I made these on windows. I investigated the poss...
50
2009-08-10T03:11:51Z
29,523,138
<p>I know this question is rather old, but nonetheless I thought it worth pointing out that for distributing your Python scripts in a way that doesn't require a native Python installation, you could also try <a href="http://nuitka.net/" rel="nofollow">Nuitka</a>, which basically translates your Python code to C++ code,...
0
2015-04-08T19:00:18Z
[ "python", "jython", "distribution", "executable-jar" ]
Google Web Toolkit like application in Django
1,253,056
<p>I'm trying to develop an application that would be perfect for GWT, however I am using this app as a learning example for Django. Is there some precedence for this type of application in Django?</p>
3
2009-08-10T04:00:23Z
1,253,082
<p><a href="http://pyjs.org/">Pyjamas</a> is sort of like GWT which is written with Python. From there you can make it work with your django code.</p>
5
2009-08-10T04:10:27Z
[ "python", "django", "gwt" ]
Google Web Toolkit like application in Django
1,253,056
<p>I'm trying to develop an application that would be perfect for GWT, however I am using this app as a learning example for Django. Is there some precedence for this type of application in Django?</p>
3
2009-08-10T04:00:23Z
1,258,305
<p>Lots of people have done this by writing their UI in GWT and having it issue ajax calls back to their python backend. There are basically two ways to go about it. First, you can simply use JSON to communicate between the frontend and the backend. That's the approach you will find here (<a href="http://palantar.blogs...
3
2009-08-11T03:10:00Z
[ "python", "django", "gwt" ]
Why does subprocess.Popen() with shell=True work differently on Linux vs Windows?
1,253,122
<p>When using <code>subprocess.Popen(args, shell=True)</code> to run "<code>gcc --version</code>" (just as an example), on Windows we get this:</p> <pre><code>&gt;&gt;&gt; from subprocess import Popen &gt;&gt;&gt; Popen(['gcc', '--version'], shell=True) gcc (GCC) 3.4.5 (mingw-vista special r3) ... </code></pre> <p>So...
19
2009-08-10T04:39:58Z
1,253,161
<p>From the subprocess.py source:</p> <blockquote> <p>On UNIX, with shell=True: If args is a string, it specifies the command string to execute through the shell. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional shell arguments.</p> ...
5
2009-08-10T04:55:52Z
[ "python", "shell", "subprocess", "popen" ]
Why does subprocess.Popen() with shell=True work differently on Linux vs Windows?
1,253,122
<p>When using <code>subprocess.Popen(args, shell=True)</code> to run "<code>gcc --version</code>" (just as an example), on Windows we get this:</p> <pre><code>&gt;&gt;&gt; from subprocess import Popen &gt;&gt;&gt; Popen(['gcc', '--version'], shell=True) gcc (GCC) 3.4.5 (mingw-vista special r3) ... </code></pre> <p>So...
19
2009-08-10T04:39:58Z
1,254,322
<p>Actually on Windows, it does use <code>cmd.exe</code> when <code>shell=True</code> - it prepends <code>cmd.exe /c </code> (it actually looks up the <code>COMSPEC</code> environment variable but defaults to <code>cmd.exe</code> if not present) to the shell arguments. (On Windows 95/98 it uses the intermediate <code>w...
14
2009-08-10T11:09:49Z
[ "python", "shell", "subprocess", "popen" ]
Why does subprocess.Popen() with shell=True work differently on Linux vs Windows?
1,253,122
<p>When using <code>subprocess.Popen(args, shell=True)</code> to run "<code>gcc --version</code>" (just as an example), on Windows we get this:</p> <pre><code>&gt;&gt;&gt; from subprocess import Popen &gt;&gt;&gt; Popen(['gcc', '--version'], shell=True) gcc (GCC) 3.4.5 (mingw-vista special r3) ... </code></pre> <p>So...
19
2009-08-10T04:39:58Z
27,404,401
<p>The reason for the UNIX behaviour of <code>shell=True</code> is to do with quoting. When we write a shell command, it will be split at spaces, so we have to quote some arguments:</p> <pre><code>cp "My File" "New Location" </code></pre> <p>This leads to problems when our arguments <em>contain</em> quotes, which req...
0
2014-12-10T15:11:01Z
[ "python", "shell", "subprocess", "popen" ]
Is there an easy way to pickle a python function (or otherwise serialize its code)?
1,253,528
<p>I'm trying to transfer a transfer a function across a network connection (using asyncore). Is there an easy way to serialize a python function (one that, in this case at least, will have no side affects) for transfer like this?</p> <p>I would ideally like to have a pair of functions similar to these:</p> <pre><cod...
68
2009-08-10T07:25:47Z
1,253,540
<p>The most simple way is probably <code>inspect.getsource(object)</code> (see the <a href="http://docs.python.org/library/inspect.html#retrieving-source-code">inspect module</a>) which returns a String with the source code for a function or a method.</p>
9
2009-08-10T07:29:42Z
[ "python", "function", "pickle" ]
Is there an easy way to pickle a python function (or otherwise serialize its code)?
1,253,528
<p>I'm trying to transfer a transfer a function across a network connection (using asyncore). Is there an easy way to serialize a python function (one that, in this case at least, will have no side affects) for transfer like this?</p> <p>I would ideally like to have a pair of functions similar to these:</p> <pre><cod...
68
2009-08-10T07:25:47Z
1,253,579
<p><a href="http://pythonhosted.org/Pyro4/">Pyro</a> is able to <a href="http://packages.python.org/Pyro/7-features.html#mobile">do this for you</a>.</p>
13
2009-08-10T07:45:33Z
[ "python", "function", "pickle" ]
Is there an easy way to pickle a python function (or otherwise serialize its code)?
1,253,528
<p>I'm trying to transfer a transfer a function across a network connection (using asyncore). Is there an easy way to serialize a python function (one that, in this case at least, will have no side affects) for transfer like this?</p> <p>I would ideally like to have a pair of functions similar to these:</p> <pre><cod...
68
2009-08-10T07:25:47Z
1,253,813
<p>You could serialise the function bytecode and then reconstruct it on the caller. The <a href="https://docs.python.org/3/library/marshal.html">marshal</a> module can be used to serialise code objects, which can then be reassembled into a function. ie:</p> <pre><code>import marshal def foo(x): return x*x code_strin...
91
2009-08-10T08:58:22Z
[ "python", "function", "pickle" ]
Is there an easy way to pickle a python function (or otherwise serialize its code)?
1,253,528
<p>I'm trying to transfer a transfer a function across a network connection (using asyncore). Is there an easy way to serialize a python function (one that, in this case at least, will have no side affects) for transfer like this?</p> <p>I would ideally like to have a pair of functions similar to these:</p> <pre><cod...
68
2009-08-10T07:25:47Z
1,253,895
<p>It all depends on whether you generate the function at runtime or not:</p> <p>If you do - <code>inspect.getsource(object)</code> won't work for dynamically generated functions as it gets object's source from <code>.py</code> file, so only functions defined before execution can be retrieved as source.</p> <p>And if...
5
2009-08-10T09:22:44Z
[ "python", "function", "pickle" ]
Is there an easy way to pickle a python function (or otherwise serialize its code)?
1,253,528
<p>I'm trying to transfer a transfer a function across a network connection (using asyncore). Is there an easy way to serialize a python function (one that, in this case at least, will have no side affects) for transfer like this?</p> <p>I would ideally like to have a pair of functions similar to these:</p> <pre><cod...
68
2009-08-10T07:25:47Z
1,416,937
<p>The basic functions used for this module covers your query, plus you get the best compression over the wire; see the instructive source code:</p> <p>y_serial.py module :: warehouse Python objects with SQLite</p> <p>"Serialization + persistance :: in a few lines of code, compress and annotate Python objects into SQ...
1
2009-09-13T05:35:44Z
[ "python", "function", "pickle" ]
Is there an easy way to pickle a python function (or otherwise serialize its code)?
1,253,528
<p>I'm trying to transfer a transfer a function across a network connection (using asyncore). Is there an easy way to serialize a python function (one that, in this case at least, will have no side affects) for transfer like this?</p> <p>I would ideally like to have a pair of functions similar to these:</p> <pre><cod...
68
2009-08-10T07:25:47Z
16,900,634
<p>The <code>cloud</code> package (pip install cloud) can pickle arbitrary code, including dependencies. See <a href="http://stackoverflow.com/a/16891169/1264797">http://stackoverflow.com/a/16891169/1264797</a>.</p>
2
2013-06-03T15:41:56Z
[ "python", "function", "pickle" ]
Is there an easy way to pickle a python function (or otherwise serialize its code)?
1,253,528
<p>I'm trying to transfer a transfer a function across a network connection (using asyncore). Is there an easy way to serialize a python function (one that, in this case at least, will have no side affects) for transfer like this?</p> <p>I would ideally like to have a pair of functions similar to these:</p> <pre><cod...
68
2009-08-10T07:25:47Z
20,417,344
<p>Check out <a href="https://pypi.python.org/pypi/dill">Dill</a>, which extends Python's pickle library to support a greater variety of types, including functions:</p> <pre><code>&gt;&gt;&gt; import dill as pickle &gt;&gt;&gt; def f(x): return x + 1 ... &gt;&gt;&gt; g = pickle.dumps(f) &gt;&gt;&gt; f(1) 2 &gt;&gt;&gt...
15
2013-12-06T06:20:22Z
[ "python", "function", "pickle" ]
get_allowed_auths() in paramiko for authentication types
1,253,870
<p>I am trying to get supported authentication types/methods from a running SSH server in Python.</p> <p>I found this method get_allowed_auths() in the ServerInterface class in Paramiko but I can't understand if it is usable in a simple client-like snippet of code (I am writing something that accomplish in ONLY this t...
3
2009-08-10T09:15:19Z
1,257,769
<p>You can try to authenticate using no authentication, which should always fail, but the server will then send back the auth types that can continue. There is an <code>auth_none()</code> method provided by <code>paramiko.Transport</code> to do this.</p> <pre><code>import paramiko import socket s = socket.socket() s....
4
2009-08-10T23:22:38Z
[ "python", "authentication", "ssh", "paramiko" ]
Suggestion Needed - Networking in Python - A good idea?
1,253,905
<p>I am considering programming the network related features of my application in Python instead of the C/C++ API. The intended use of networking is to pass text messages between two instances of my application, similar to a game passing player positions as often as possible over the network.</p> <p>Although the pytho...
4
2009-08-10T09:26:22Z
1,253,945
<p>To answer #1, I know that among other things, EVE Online (the MMO) uses a variant of Python for their server code.</p>
1
2009-08-10T09:37:03Z
[ "python", "network-programming" ]
Suggestion Needed - Networking in Python - A good idea?
1,253,905
<p>I am considering programming the network related features of my application in Python instead of the C/C++ API. The intended use of networking is to pass text messages between two instances of my application, similar to a game passing player positions as often as possible over the network.</p> <p>Although the pytho...
4
2009-08-10T09:26:22Z
1,254,092
<p>The python that EVE online uses is StacklessPython (<a href="http://www.stackless.com/" rel="nofollow">http://www.stackless.com/</a>), and as far as i understand they use it for how it implements threading through using tasklets and whatnot. But since python itself can handle stuff like MMO with 40k people online i ...
1
2009-08-10T10:15:36Z
[ "python", "network-programming" ]
Suggestion Needed - Networking in Python - A good idea?
1,253,905
<p>I am considering programming the network related features of my application in Python instead of the C/C++ API. The intended use of networking is to pass text messages between two instances of my application, similar to a game passing player positions as often as possible over the network.</p> <p>Although the pytho...
4
2009-08-10T09:26:22Z
1,254,288
<p>Python is a mature language that can do almost anything that you can do in C/C++ (even direct memory access if you really want to hurt yourself).</p> <p>You'll find that you can write beautiful code in it in a very short time, that this code is readable from the start and that it will stay readable (you will still ...
3
2009-08-10T11:04:14Z
[ "python", "network-programming" ]
Suggestion Needed - Networking in Python - A good idea?
1,253,905
<p>I am considering programming the network related features of my application in Python instead of the C/C++ API. The intended use of networking is to pass text messages between two instances of my application, similar to a game passing player positions as often as possible over the network.</p> <p>Although the pytho...
4
2009-08-10T09:26:22Z
1,255,979
<p>Check out <a href="http://twistedmatrix.com/trac/">Twisted</a>, a Python engine for Networking. Has built-in support for TCP, UDP, SSL/TLS, multicast, Unix sockets, a large number of protocols (including HTTP, NNTP, IMAP, SSH, IRC, FTP, and others)</p>
9
2009-08-10T16:52:04Z
[ "python", "network-programming" ]
How to add a custom implicit conversion to a C++ type in Boost::Python?
1,254,013
<p>In my C++ code I have a class Foo with many methods taking a Bar type variable as an argument:</p> <pre><code>class Foo { public: void do_this(Bar b); void do_that(Bar b); /* ... */ }; </code></pre> <p>Bar has a number of constructors that create a new object from many common types such as int, std::string, ...
2
2009-08-10T09:55:13Z
1,254,045
<p>Create some type TupleCollector with overridden "operator ,(int)" so you can write</p> <pre><code>f.do_that((TuppleCollector(), 1, 2, 3)) </code></pre> <p>at last create conversion between TupleCollector and expected target</p>
0
2009-08-10T10:03:26Z
[ "c++", "python", "boost-python" ]
How to add a custom implicit conversion to a C++ type in Boost::Python?
1,254,013
<p>In my C++ code I have a class Foo with many methods taking a Bar type variable as an argument:</p> <pre><code>class Foo { public: void do_this(Bar b); void do_that(Bar b); /* ... */ }; </code></pre> <p>Bar has a number of constructors that create a new object from many common types such as int, std::string, ...
2
2009-08-10T09:55:13Z
1,887,414
<p>You can export function do_that which take boost::python::object param, check if param is a python tuple, extract data and pass it to object.</p>
-1
2009-12-11T11:21:35Z
[ "c++", "python", "boost-python" ]
How to add a custom implicit conversion to a C++ type in Boost::Python?
1,254,013
<p>In my C++ code I have a class Foo with many methods taking a Bar type variable as an argument:</p> <pre><code>class Foo { public: void do_this(Bar b); void do_that(Bar b); /* ... */ }; </code></pre> <p>Bar has a number of constructors that create a new object from many common types such as int, std::string, ...
2
2009-08-10T09:55:13Z
4,137,806
<p>Subclass Bar near the wrapper code and give your subclass a ctor that takes a bp::object (or a more specific python type)</p> <pre><code>struct Bar_wrapper:Bar,bp::wrapper&lt;Bar&gt; { Bar_wrapper(bp::object arg) { //code to build a Bar_wrapper Here } } </code></pre> <p>Then export a Bar_wrappe...
2
2010-11-09T19:46:57Z
[ "c++", "python", "boost-python" ]
How to add a custom implicit conversion to a C++ type in Boost::Python?
1,254,013
<p>In my C++ code I have a class Foo with many methods taking a Bar type variable as an argument:</p> <pre><code>class Foo { public: void do_this(Bar b); void do_that(Bar b); /* ... */ }; </code></pre> <p>Bar has a number of constructors that create a new object from many common types such as int, std::string, ...
2
2009-08-10T09:55:13Z
7,401,595
<p>Add a new constructor <code>template &lt;typename T&gt; Bar(T)</code> in your header and implement as <code>template &lt;&gt; Bar::Bar(Tupple) {}</code></p>
1
2011-09-13T12:07:38Z
[ "c++", "python", "boost-python" ]
How to add a custom implicit conversion to a C++ type in Boost::Python?
1,254,013
<p>In my C++ code I have a class Foo with many methods taking a Bar type variable as an argument:</p> <pre><code>class Foo { public: void do_this(Bar b); void do_that(Bar b); /* ... */ }; </code></pre> <p>Bar has a number of constructors that create a new object from many common types such as int, std::string, ...
2
2009-08-10T09:55:13Z
7,402,828
<p>You can make a static factory method and then expose it as one of the Python constructors for the class. Just make a converter that will take any Python object and you're free do do whatever your please.</p> <pre><code>using namespace boost::python; Bar CreateBar(object obj) { // Do your thing here retur...
0
2011-09-13T13:38:43Z
[ "c++", "python", "boost-python" ]
How to add a custom implicit conversion to a C++ type in Boost::Python?
1,254,013
<p>In my C++ code I have a class Foo with many methods taking a Bar type variable as an argument:</p> <pre><code>class Foo { public: void do_this(Bar b); void do_that(Bar b); /* ... */ }; </code></pre> <p>Bar has a number of constructors that create a new object from many common types such as int, std::string, ...
2
2009-08-10T09:55:13Z
7,403,293
<p>You can register from-python converter which will construct <code>Bar</code> instance from arbitrary object. See <a href="http://misspent.wordpress.com/2009/09/27/how-to-write-boost-python-converters/" rel="nofollow">here</a> and an exmaple of my own (converts either <code>(Vector3,Quaternion)</code> tuple or 7*doub...
0
2011-09-13T14:12:13Z
[ "c++", "python", "boost-python" ]
Has anyone succeeded in using Google App Engine with Python version 2.6?
1,254,028
<p>Since Python 2.6 is backward compatible to 2.52 , did anyone succeeded in using it with Google app Engine ( which supports 2.52 officially ).</p> <p>I know i should try it myself. But i am a python and web-apps new bee and for me installation and configuration is the hardest part while getting started with somethi...
9
2009-08-10T09:58:39Z
1,254,047
<p>I suppose logging module crashes if you try to start the dev environment. See <a href="http://code.google.com/p/googleappengine/issues/detail?id=1159#c7" rel="nofollow">the issue and a workaround</a>.</p> <p>After doing that change my code worked in 2.6 without any problems. I suggest using 2.5.x though so there ar...
11
2009-08-10T10:04:45Z
[ "python", "google-app-engine" ]
Has anyone succeeded in using Google App Engine with Python version 2.6?
1,254,028
<p>Since Python 2.6 is backward compatible to 2.52 , did anyone succeeded in using it with Google app Engine ( which supports 2.52 officially ).</p> <p>I know i should try it myself. But i am a python and web-apps new bee and for me installation and configuration is the hardest part while getting started with somethi...
9
2009-08-10T09:58:39Z
1,255,893
<p>There are a few issues with using Python 2.6 with the SDK, mostly related to the SDK's sandboxing, which is designed to imitate the sandbox limitations in production. Note, of course, that even if you get Python 2.6 running with the SDK, your code will still have to run under 2.5 in production.</p>
6
2009-08-10T16:32:18Z
[ "python", "google-app-engine" ]
string quoting issues in doctests
1,254,187
<p>When I run doctests on different Python versions (2.5 vs 2.6) and different plattforms (FreeBSD vs Mac OS) strings get quoted differently:</p> <pre><code>Failed example: decode('{"created_by":"test","guid":123,"num":5.00}') Expected: {'guid': 123, 'num': Decimal("5.00"), 'created_by': 'test'} Got: {'gui...
2
2009-08-10T10:38:03Z
1,254,230
<p>This is actually because the <code>decimal</code> module's source code has changed: In python 2.4 and python2.5 the <code>decimal.Decimal.__repr__</code> function contains:</p> <pre><code>return 'Decimal("%s")' % str(self) </code></pre> <p>whereas in python2.6 it contains:</p> <pre><code>return "Decimal('%s')" % ...
4
2009-08-10T10:49:29Z
[ "python", "testing", "doctest" ]
string quoting issues in doctests
1,254,187
<p>When I run doctests on different Python versions (2.5 vs 2.6) and different plattforms (FreeBSD vs Mac OS) strings get quoted differently:</p> <pre><code>Failed example: decode('{"created_by":"test","guid":123,"num":5.00}') Expected: {'guid': 123, 'num': Decimal("5.00"), 'created_by': 'test'} Got: {'gui...
2
2009-08-10T10:38:03Z
1,254,452
<p>Following the hits by D<a href="http://stackoverflow.com/users/120398/david-fraser">avid Fraser</a> i found <a href="http://mail.python.org/pipermail/python-dev/2008-July/081420.html" rel="nofollow">this suggestion</a> by Raymond Hettinger on the Python mailinglist.</p> <p>I now use something like this:</p> <pre><...
0
2009-08-10T11:51:13Z
[ "python", "testing", "doctest" ]
PHP - Print all statements that are executed in a PHP command line script?
1,254,215
<p>In python, one can trace all the statements that are executed by a command line script using the <a href="http://docs.python.org/library/trace.html" rel="nofollow">trace</a> module. In bash you can do the same with <code>set -x</code>. We have a PHP script that we're running from the command line, like a normal bash...
1
2009-08-10T10:46:04Z
1,254,247
<p>Not in pure-PHP, no -- as far as i know.</p> <p>But you can use a debugger ; a nice way to do that is with </p> <ul> <li>The extension <a href="http://xdebug.org/" rel="nofollow">Xdebug</a>, which can be used as a <a href="http://xdebug.org/docs/remote" rel="nofollow">debugger</a></li> <li>and some graphical IDE t...
1
2009-08-10T10:53:13Z
[ "php", "python", "debugging", "command-line" ]
PHP - Print all statements that are executed in a PHP command line script?
1,254,215
<p>In python, one can trace all the statements that are executed by a command line script using the <a href="http://docs.python.org/library/trace.html" rel="nofollow">trace</a> module. In bash you can do the same with <code>set -x</code>. We have a PHP script that we're running from the command line, like a normal bash...
1
2009-08-10T10:46:04Z
1,254,625
<p>I'm kinda blind here but I guess one way you could do it is to write all the relevant code inside custom functions and call <a href="http://php.net/manual/en/function.debug-backtrace.php" rel="nofollow">debug_backtrace()</a>. <a href="http://php.net/manual/en/function.debug-print-backtrace.php" rel="nofollow">debug_...
-1
2009-08-10T12:37:07Z
[ "php", "python", "debugging", "command-line" ]
PHP - Print all statements that are executed in a PHP command line script?
1,254,215
<p>In python, one can trace all the statements that are executed by a command line script using the <a href="http://docs.python.org/library/trace.html" rel="nofollow">trace</a> module. In bash you can do the same with <code>set -x</code>. We have a PHP script that we're running from the command line, like a normal bash...
1
2009-08-10T10:46:04Z
1,256,690
<p>There is a PECL extension, <a href="http://pecl.php.net/package/apd" rel="nofollow">apd</a>, that will generate a trace file. </p>
2
2009-08-10T19:17:11Z
[ "php", "python", "debugging", "command-line" ]
Multipart form post to google app engine not working
1,254,270
<p>I am trying to post a multi-part form using httplib, url is hosted on google app engine, on post it says Method not allowed, though the post using urllib2 works. Full working example is attached.</p> <p>My question is what is the difference between two, why one works but not the other</p> <ol> <li><p>is there a pr...
0
2009-08-10T10:59:02Z
1,387,513
<p><a href="http://stackoverflow.com/users/12030/nick-johnson">Nick Johnson's</a> answer </p> <p>Have you tried sending the request with httplib using .request() instead of .putrequest() etc, supplying the headers as a dict?</p> <p>it works!</p>
0
2009-09-07T04:09:16Z
[ "python", "google-app-engine", "forms", "html-post" ]
Avoid program exit on I/O error
1,254,292
<p>I have a Python script using shutil.copy2 extensively. Since I use it to copy files over the network, I get too frequent I/O errors, which lead to the abortion of my program's execution:</p> <pre><code>Traceback (most recent call last): File "run_model.py", line 46, in &lt;module&gt; main() File "run_model....
3
2009-08-10T11:05:10Z
1,254,309
<p>you can use </p> <pre><code>try: ... except IOError as err: ... </code></pre> <p>to catch the errors and treat them</p> <p>Have a look on <a href="http://docs.python.org/tutorial/errors.html" rel="nofollow">this</a></p>
6
2009-08-10T11:08:13Z
[ "python", "shutil" ]
Avoid program exit on I/O error
1,254,292
<p>I have a Python script using shutil.copy2 extensively. Since I use it to copy files over the network, I get too frequent I/O errors, which lead to the abortion of my program's execution:</p> <pre><code>Traceback (most recent call last): File "run_model.py", line 46, in &lt;module&gt; main() File "run_model....
3
2009-08-10T11:05:10Z
1,254,324
<p>Which block is giving the error? Just wrap a <a href="http://docs.python.org/tutorial/errors.html">try/except</a> around it:</p> <pre><code>def check_file(file, size=0): try: if not os.path.exists(file): return False if (size != 0 and os.path.getsize(file) != size): retu...
7
2009-08-10T11:10:03Z
[ "python", "shutil" ]
Reimport a module in python while interactive
1,254,370
<p>I know it can be done, but I never remember how.</p> <p>How can you reimport a module in python? The scenario is as follows: I import a module interactively and tinker with it, but then I face an error. I fix the error in the .py file and then I want to reimport the fixed module without quitting python. How can I ...
148
2009-08-10T11:24:17Z
1,254,379
<p>This should work:</p> <pre><code>reload(my.module) </code></pre> <p>From the <a href="http://docs.python.org/library/functions.html#reload">Python docs</a></p> <blockquote> <p>Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is us...
168
2009-08-10T11:29:12Z
[ "python" ]
Reimport a module in python while interactive
1,254,370
<p>I know it can be done, but I never remember how.</p> <p>How can you reimport a module in python? The scenario is as follows: I import a module interactively and tinker with it, but then I face an error. I fix the error in the .py file and then I want to reimport the fixed module without quitting python. How can I ...
148
2009-08-10T11:24:17Z
14,390,676
<p>In python 3, <code>reload</code> is no longer a built in function.</p> <p>If you are using python 3.4+ you should use <a href="https://docs.python.org/3/library/importlib.html#importlib.reload"><code>reload</code></a> from the <a href="https://docs.python.org/3/library/importlib.html"><code>importlib</code></a> lib...
67
2013-01-18T00:35:29Z
[ "python" ]
Reimport a module in python while interactive
1,254,370
<p>I know it can be done, but I never remember how.</p> <p>How can you reimport a module in python? The scenario is as follows: I import a module interactively and tinker with it, but then I face an error. I fix the error in the .py file and then I want to reimport the fixed module without quitting python. How can I ...
148
2009-08-10T11:24:17Z
23,901,170
<p>Actually, in Python 3 the module <code>imp</code> is marked as DEPRECATED. Well, at least that's true for 3.4.</p> <p>Instead the <code>reload</code> function from the <code>importlib</code> module should be used:</p> <p><a href="https://docs.python.org/3/library/importlib.html#importlib.reload">https://docs.pytho...
28
2014-05-28T00:39:22Z
[ "python" ]
Python API to fetch PGP public key from key server?
1,254,425
<p>Is there any Python API which can fetch a PGP public key from the public key server?</p>
3
2009-08-10T11:42:24Z
1,254,526
<p>You can use HTTP (urllib2 and beautiful soup would be my choice) if you're querying the MIT PGP keyserver.</p> <p><a href="http://pgp.mit.edu/extracthelp.html" rel="nofollow">http://pgp.mit.edu/extracthelp.html</a></p>
3
2009-08-10T12:11:27Z
[ "python", "pgp" ]
Fastest way to convert a dict's keys & values from `unicode` to `str`?
1,254,454
<p>I'm receiving a dict from one "layer" of code upon which some calculations/modifications are performed before passing it onto another "layer". The original dict's keys &amp; "string" values are <code>unicode</code>, but the layer they're being passed onto only accepts <code>str</code>.</p> <p>This is going to be ca...
45
2009-08-10T11:51:17Z
1,254,488
<pre><code>def to_str(key, value): if isinstance(key, unicode): key = str(key) if isinstance(value, unicode): value = str(value) return key, value </code></pre> <p>pass key and value to it, and add recursion to your code to account for inner dictionary.</p>
3
2009-08-10T11:59:49Z
[ "python", "casting", "types" ]
Fastest way to convert a dict's keys & values from `unicode` to `str`?
1,254,454
<p>I'm receiving a dict from one "layer" of code upon which some calculations/modifications are performed before passing it onto another "layer". The original dict's keys &amp; "string" values are <code>unicode</code>, but the layer they're being passed onto only accepts <code>str</code>.</p> <p>This is going to be ca...
45
2009-08-10T11:51:17Z
1,254,499
<pre><code>DATA = { u'spam': u'eggs', u'foo': frozenset([u'Gah!']), u'bar': { u'baz': 97 }, u'list': [u'list', (True, u'Maybe'), set([u'and', u'a', u'set', 1])]} def convert(data): if isinstance(data, basestring): return str(data) elif isinstance(data, collections.Mapping): return dict...
102
2009-08-10T12:03:54Z
[ "python", "casting", "types" ]
Fastest way to convert a dict's keys & values from `unicode` to `str`?
1,254,454
<p>I'm receiving a dict from one "layer" of code upon which some calculations/modifications are performed before passing it onto another "layer". The original dict's keys &amp; "string" values are <code>unicode</code>, but the layer they're being passed onto only accepts <code>str</code>.</p> <p>This is going to be ca...
45
2009-08-10T11:51:17Z
6,728,427
<p>If you wanted to do this inline and didn't need recursive descent, this might work:</p> <pre><code>DATA = { u'spam': u'eggs', u'foo': True, u'bar': { u'baz': 97 } } print DATA # "{ u'spam': u'eggs', u'foo': True, u'bar': { u'baz': 97 } }" STRING_DATA = dict([(str(k), v) for k, v in data.items()]) print STRING_DATA...
10
2011-07-18T03:39:39Z
[ "python", "casting", "types" ]
Fastest way to convert a dict's keys & values from `unicode` to `str`?
1,254,454
<p>I'm receiving a dict from one "layer" of code upon which some calculations/modifications are performed before passing it onto another "layer". The original dict's keys &amp; "string" values are <code>unicode</code>, but the layer they're being passed onto only accepts <code>str</code>.</p> <p>This is going to be ca...
45
2009-08-10T11:51:17Z
7,027,514
<p>I know I'm late on this one:</p> <pre><code>def convert_keys_to_string(dictionary): """Recursively converts dictionary keys to strings.""" if not isinstance(dictionary, dict): return dictionary return dict((str(k), convert_keys_to_string(v)) for k, v in dictionary.items()) </code></pre>...
13
2011-08-11T14:18:22Z
[ "python", "casting", "types" ]
Fastest way to convert a dict's keys & values from `unicode` to `str`?
1,254,454
<p>I'm receiving a dict from one "layer" of code upon which some calculations/modifications are performed before passing it onto another "layer". The original dict's keys &amp; "string" values are <code>unicode</code>, but the layer they're being passed onto only accepts <code>str</code>.</p> <p>This is going to be ca...
45
2009-08-10T11:51:17Z
38,476,472
<p>for a non-nested dict (since the title does not mention that case, it might be interesting for other people)</p> <pre><code>{str(k): str(v) for k,v in DATA} </code></pre>
0
2016-07-20T08:45:29Z
[ "python", "casting", "types" ]
Can Python's optparse display the default value of an option?
1,254,469
<p>Is there a way to make Python's optparse print the default value of an option or flag when showing the help with --help?</p>
38
2009-08-10T11:55:02Z
1,254,491
<p>Try using the <code>%default</code> string placeholder:</p> <pre><code># This example taken from http://docs.python.org/library/optparse.html#generating-help parser.add_option("-m", "--mode", default="intermediate", help="interaction mode: novice, intermediate, " ...
50
2009-08-10T12:01:33Z
[ "python", "optparse" ]
Can Python's optparse display the default value of an option?
1,254,469
<p>Is there a way to make Python's optparse print the default value of an option or flag when showing the help with --help?</p>
38
2009-08-10T11:55:02Z
1,254,500
<p>And if you need programmatic access to the default values, you can get to them via the <code>defaults</code> attribute of the parser (it's a dict)</p>
7
2009-08-10T12:04:04Z
[ "python", "optparse" ]
Can Python's optparse display the default value of an option?
1,254,469
<p>Is there a way to make Python's optparse print the default value of an option or flag when showing the help with --help?</p>
38
2009-08-10T11:55:02Z
11,906,371
<p>And if you want to add default values automatically to all options that you have specified, you can do the following:</p> <pre><code>for option in parser.option_list: if option.default != ("NO", "DEFAULT"): option.help += (" " if option.help else "") + "[default: %default]" </code></pre>
7
2012-08-10T17:16:52Z
[ "python", "optparse" ]
Can Python's optparse display the default value of an option?
1,254,469
<p>Is there a way to make Python's optparse print the default value of an option or flag when showing the help with --help?</p>
38
2009-08-10T11:55:02Z
33,969,137
<p>The comments to your question already indicate there's another way to parse arguments called <a href="https://docs.python.org/3.5/library/argparse.html" rel="nofollow">argparse</a>. It's been introduced in Python 3.2. It actually deprecates <code>optparse</code> but is used similarly.</p> <p><code>argpass</code> co...
0
2015-11-28T08:07:00Z
[ "python", "optparse" ]
Why don't Django and CherryPy support HTTP verb-based dispatch natively?
1,254,629
<p>It's not the same to POST to an URL than to GET it, DELETE it or PUT it. These actions are fundamentally different. However, Django seems to ignore them in its dispatch mechanism. Basically, one is forced to either ignore HTTP verbs completely or do this on every view:</p> <pre><code>def my_view(request, arg1, arg2...
10
2009-08-10T12:39:18Z
1,254,672
<p>I believe the decision for django was made because usually just <code>GET</code> and <code>POST</code> is enough, and that keeps the framework simpler for its requirements. It is very convenient to just "not care" about which verb was used.</p> <p>However, there are plenty other frameworks that can do dispatch base...
2
2009-08-10T12:46:58Z
[ "python", "django", "rest", "cherrypy", "web-frameworks" ]
Why don't Django and CherryPy support HTTP verb-based dispatch natively?
1,254,629
<p>It's not the same to POST to an URL than to GET it, DELETE it or PUT it. These actions are fundamentally different. However, Django seems to ignore them in its dispatch mechanism. Basically, one is forced to either ignore HTTP verbs completely or do this on every view:</p> <pre><code>def my_view(request, arg1, arg2...
10
2009-08-10T12:39:18Z
1,254,735
<p>Because this is not hard to DIY. Just have a dictionary of accepted verbs to functions in each class.</p> <pre><code>def dispatcher(someObject, request): try: return someObject.acceptedVerbs[request.method]() except: return http.HttpResponseNotAllowed(someObject.acceptedVerbs.keys()) </code></pr...
1
2009-08-10T12:58:12Z
[ "python", "django", "rest", "cherrypy", "web-frameworks" ]
Why don't Django and CherryPy support HTTP verb-based dispatch natively?
1,254,629
<p>It's not the same to POST to an URL than to GET it, DELETE it or PUT it. These actions are fundamentally different. However, Django seems to ignore them in its dispatch mechanism. Basically, one is forced to either ignore HTTP verbs completely or do this on every view:</p> <pre><code>def my_view(request, arg1, arg2...
10
2009-08-10T12:39:18Z
1,255,171
<p>I can't speak for Django, but in CherryPy, you can have one function per HTTP verb with a single config entry:</p> <pre><code>request.dispatch = cherrypy.dispatch.MethodDispatcher() </code></pre> <p>However, I have seen some situations where that's not desirable.</p> <p>One example would be a hard redirect regard...
12
2009-08-10T14:22:15Z
[ "python", "django", "rest", "cherrypy", "web-frameworks" ]
Why don't Django and CherryPy support HTTP verb-based dispatch natively?
1,254,629
<p>It's not the same to POST to an URL than to GET it, DELETE it or PUT it. These actions are fundamentally different. However, Django seems to ignore them in its dispatch mechanism. Basically, one is forced to either ignore HTTP verbs completely or do this on every view:</p> <pre><code>def my_view(request, arg1, arg2...
10
2009-08-10T12:39:18Z
15,728,522
<p>Came across this from Google, and thought of updating.</p> <h1>Django</h1> <p>Just FYI, This is now supported in Django as class based views. You can extend the generic class <code>View</code> and add methods like <code>get()</code>, <code>post()</code>, <code>put()</code> etc. E.g. - </p> <pre><code>from django....
7
2013-03-31T10:35:44Z
[ "python", "django", "rest", "cherrypy", "web-frameworks" ]
Call PHP code from Python
1,254,802
<p>I'm trying to integrate an old PHP ad management system into a (Django) Python-based web application. The PHP and the Python code are both installed on the same hosts, PHP is executed by <code>mod_php5</code> and Python through <code>mod_wsgi</code>, usually.</p> <p>Now I wonder what's the best way to call this PHP...
2
2009-08-10T13:13:10Z
1,254,825
<p>How about using AJAX from the browser to load the ads?</p> <p>For instance (using JQuery):</p> <pre><code>$(document).ready(function() { $("#apageelement").load("/phpapp/getads.php"); }) </code></pre> <p>This allows you to keep you app almost completely separate from the PHP app.</p>
4
2009-08-10T13:17:53Z
[ "php", "python" ]
Call PHP code from Python
1,254,802
<p>I'm trying to integrate an old PHP ad management system into a (Django) Python-based web application. The PHP and the Python code are both installed on the same hosts, PHP is executed by <code>mod_php5</code> and Python through <code>mod_wsgi</code>, usually.</p> <p>Now I wonder what's the best way to call this PHP...
2
2009-08-10T13:13:10Z
1,255,480
<p>Best solution is to use server side includes. Most webservers support this.</p> <p>For example this is how it would be done in nginx:</p> <pre><code>&lt;!--# include virtual="http://localhost:8080/phpapp/getads.php" --&gt; </code></pre> <p>Your webserver would then dynamically request from your php backend, and i...
2
2009-08-10T15:17:51Z
[ "php", "python" ]
Call PHP code from Python
1,254,802
<p>I'm trying to integrate an old PHP ad management system into a (Django) Python-based web application. The PHP and the Python code are both installed on the same hosts, PHP is executed by <code>mod_php5</code> and Python through <code>mod_wsgi</code>, usually.</p> <p>Now I wonder what's the best way to call this PHP...
2
2009-08-10T13:13:10Z
1,256,684
<p>I've done this in the past by serving the PHP portions directly via Apache. You could either put them in with your media files, (/site_media/php/) or if you prefer to use something more lightweight for your media server (like lighttpd), you can set up another portion of the site that goes through apache with PHP en...
0
2009-08-10T19:15:55Z
[ "php", "python" ]
Non-editable text box in wxPython
1,254,819
<p>How to create a non-editable text box with no cursor in wxPython to dump text in? </p>
5
2009-08-10T13:16:03Z
1,254,881
<p><code>wx.StaticText</code></p> <p>You could also use a regular TextCtrl with the style <code>TE_READONLY</code> but that shows a cursor and the text looks editable, but it isn't.</p>
7
2009-08-10T13:29:01Z
[ "python", "textbox", "wxpython", "wx" ]
How do I validate XML document using RELAX NG schema in Python?
1,254,919
<p>How do I validate XML document via compact RELAX NG schema in Python?</p>
7
2009-08-10T13:33:51Z
1,254,992
<p>How about using <a href="http://codespeak.net/lxml/validation.html#relaxng">lxml</a>?</p> <p>From the docs:</p> <pre><code>&gt;&gt;&gt; f = StringIO('''\ ... &lt;element name="a" xmlns="http://relaxng.org/ns/structure/1.0"&gt; ... &lt;zeroOrMore&gt; ... &lt;element name="b"&gt; ... &lt;text /&gt; ... ...
15
2009-08-10T13:46:26Z
[ "python", "xml", "relaxng" ]
How can you ensure registered atexit function will run with AppHelper.runEventLoop() in PyObjC?
1,255,025
<p>I'm just wondering why I my registered an atexit function... e.g.</p> <pre><code>import atexit atexit.register(somefunc) ... AppHelper.runEventLoop() </code></pre> <p>Of course I know when will <code>atexit</code> won't work. When I comment out <code>AppHelper.runEventLoop()</code> the <code>atexit</code> function...
1
2009-08-10T13:52:42Z
1,255,910
<p>I believe you do need delegates, because otherwise the event loop can exit the process rather abruptly (kind of like <code>os._exit</code>) and therefore not give the Python runtime a chance to run termination code such as <code>finally</code> clauses, <code>atexit</code> functions, etc etc.</p>
1
2009-08-10T16:37:20Z
[ "python", "pyobjc", "atexit" ]
Python: using threads to call subprocess.Popen multiple times
1,255,449
<p>I have a service that is running (Twisted jsonrpc server). When I make a call to "run_procs" the service will look at a bunch of objects and inspect their timestamp property to see if they should run. If they should, they get added to a thread_pool (list) and then every item in the thread_pool gets the start() met...
-1
2009-08-10T15:11:10Z
1,255,505
<p>I think the key code is:</p> <pre><code> self.lock.acquire() print "\nSubprocess started" p = subprocess.Popen( # etc stdout_value = proc.communicate('through stdin to stdout')[0] self.lock.release() </code></pre> <p>the explicit calls to acquire and release should guarantee serialization -- don...
1
2009-08-10T15:21:56Z
[ "python" ]
Python: using threads to call subprocess.Popen multiple times
1,255,449
<p>I have a service that is running (Twisted jsonrpc server). When I make a call to "run_procs" the service will look at a bunch of objects and inspect their timestamp property to see if they should run. If they should, they get added to a thread_pool (list) and then every item in the thread_pool gets the start() met...
-1
2009-08-10T15:11:10Z
1,255,539
<p>Your specific problem is probably caused by the line <code>stdout_value = proc.communicate('through stdin to stdout')[0]</code>. Subprocess.communicate will <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen.communicate" rel="nofollow">"Wait for process to terminate"</a>, which, when used with ...
1
2009-08-10T15:24:34Z
[ "python" ]
Catching uncaught exceptions through django development server
1,255,467
<p>I am looking for some way in django's development server that will make the server to stop at any uncaught exception automatically, as it is done with pdb mode in ipython console.</p> <p>I know to put import pdb; pdb.set_trace() lines into the code to make application stop. But this doesn't help me, because the lin...
0
2009-08-10T15:15:14Z
1,255,858
<p>You can set <code>sys.excepthook</code> to a function that does <code>import pdb; pdb.pm()</code>, as per <a href="http://my.safaribooksonline.com/0596001673/pythoncook-CHP-14-SECT-6" rel="nofollow">this recipe</a>.</p>
2
2009-08-10T16:24:34Z
[ "python", "django", "debugging" ]
text file format from array
1,255,688
<p>I have no: of arrays, and i like to take it to text file in specific format, for eg.,</p> <p>'present form'</p> <pre><code>a= [1 2 3 4 5 ] b= [ 1 2 3 4 5 6 7 8 ] c= [ 8 9 10 12 23 43 45 56 76 78] d= [ 1 2 3 4 5 6 7 8 45 56 76 78 12 23 43 ] </code></pre> <p>The 'required format' in a txt file,</p> <pre><code...
0
2009-08-10T15:49:56Z
1,255,742
<pre><code>from __future__ import with_statement import csv import itertools a= [1, 2, 3, 4, 5] b= [1, 2, 3, 4, 5, 6, 7, 8] c= [8, 9, 10, 12, 23, 43, 45, 56, 76, 78] d= [1, 2, 3, 4, 5, 6, 7, 8, 45, 56, 76, 78, 12, 23, 43] with open('destination.txt', 'w') as f: cf = csv.writer(f, delimiter='\t') cf.writerow...
6
2009-08-10T15:59:47Z
[ "python" ]
text file format from array
1,255,688
<p>I have no: of arrays, and i like to take it to text file in specific format, for eg.,</p> <p>'present form'</p> <pre><code>a= [1 2 3 4 5 ] b= [ 1 2 3 4 5 6 7 8 ] c= [ 8 9 10 12 23 43 45 56 76 78] d= [ 1 2 3 4 5 6 7 8 45 56 76 78 12 23 43 ] </code></pre> <p>The 'required format' in a txt file,</p> <pre><code...
0
2009-08-10T15:49:56Z
1,255,877
<p>Have a look at matplotlib.mlab.rec2csv and csv2rec:</p> <pre><code>&gt;&gt;&gt; from matplotlib.mlab import rec2csv,csv2rec # note: these are also imported automatically when you do ipython -pylab &gt;&gt;&gt; rec = csv2rec('csv file.csv') &gt;&gt;&gt; rec2csv(rec, 'copy csv file', delimiter='\t') </code></pre>
1
2009-08-10T16:27:58Z
[ "python" ]
text file format from array
1,255,688
<p>I have no: of arrays, and i like to take it to text file in specific format, for eg.,</p> <p>'present form'</p> <pre><code>a= [1 2 3 4 5 ] b= [ 1 2 3 4 5 6 7 8 ] c= [ 8 9 10 12 23 43 45 56 76 78] d= [ 1 2 3 4 5 6 7 8 45 56 76 78 12 23 43 ] </code></pre> <p>The 'required format' in a txt file,</p> <pre><code...
0
2009-08-10T15:49:56Z
1,256,020
<p>Just for fun with no imports:</p> <pre><code>a= [1, 2, 3, 4, 5] b= [1, 2, 3, 4, 5, 6, 7, 8] c= [8, 9, 10, 12, 23, 43, 45, 56, 76, 78] d= [1, 2, 3, 4, 5, 6, 7, 8, 45, 56, 76, 78, 12, 23, 43] fh = open("out.txt","w") # header line fh.write("a\tb\td\tc\n") # rest of file for i in map(lambda *row: [elem or "" for ele...
-1
2009-08-10T17:03:12Z
[ "python" ]
Finding Functions Defined in a with: Block
1,255,914
<p>Here's some code from <a href="http://www.mechanicalcat.net/richard/log/Python/Something%5FI%5Fm%5Fworking%5Fon.3">Richard Jones' Blog</a>:</p> <pre><code>with gui.vertical: text = gui.label('hello!') items = gui.selection(['one', 'two', 'three']) with gui.button('click me!'): def on_click(): ...
9
2009-08-10T16:38:03Z
1,256,018
<p>Here's one way:</p> <pre><code>from __future__ import with_statement import inspect class button(object): def __enter__(self): # keep track of all that's already defined BEFORE the `with` f = inspect.currentframe(1) self.mustignore = dict(f.f_locals) def __exit__(self, exc_type, exc_value, traceba...
11
2009-08-10T17:02:58Z
[ "python", "scope", "with-statement", "contextmanager" ]
Finding Functions Defined in a with: Block
1,255,914
<p>Here's some code from <a href="http://www.mechanicalcat.net/richard/log/Python/Something%5FI%5Fm%5Fworking%5Fon.3">Richard Jones' Blog</a>:</p> <pre><code>with gui.vertical: text = gui.label('hello!') items = gui.selection(['one', 'two', 'three']) with gui.button('click me!'): def on_click(): ...
9
2009-08-10T16:38:03Z
1,256,661
<p>To answer your question, yes, it's frame introspection.</p> <p>But the syntax I would create to do the same thing is</p> <pre><code>with gui.vertical: text = gui.label('hello!') items = gui.selection(['one', 'two', 'three']) @gui.button('click me!') class button: def on_click(): ...
1
2009-08-10T19:10:42Z
[ "python", "scope", "with-statement", "contextmanager" ]
How to read String in java that was written using python's struct.pack method
1,255,918
<p>I have written information to a file in python using struct.pack eg.</p> <pre><code>out.write( struct.pack("&gt;f", 1.1) ); out.write( struct.pack("&gt;i", 12) ); out.write( struct.pack("&gt;3s", "abc") ); </code></pre> <p>Then I read it in java using <code>DataInputStream</code> and <code>readInt</code>, <code>re...
2
2009-08-10T16:38:51Z
1,256,054
<p>The format expected by <code>readUTF()</code>, is documented <a href="http://java.sun.com/javase/6/docs/api/java/io/DataInput.html" rel="nofollow">here</a>. In short, it expects a 16-bit, big-endian length followed by the bytes of the string. So, I think you could modify your pack call to look something like this:</...
4
2009-08-10T17:09:22Z
[ "java", "python" ]
How do you dynamically hide form fields in Django?
1,255,976
<p>I am making a profile form in Django. There are a lot of optional extra profile fields but I would only like to show two at a time. How do I hide or remove the fields I do not want to show dynamically? </p> <p>Here is what I have so far:</p> <pre><code>class UserProfileForm(forms.ModelForm): extra_fields = ('f...
13
2009-08-10T16:51:04Z
1,256,386
<p>You are coding this in the Form. Wouldn't it make more sense to do this using CSS and JavaScript in the template code? Hiding a field is as easy as setting "display='none'" and toggling it back to 'block', say, if you need to display it.</p> <p>Maybe some context on what the requirement is would clarify this.</p>
0
2009-08-10T18:16:41Z
[ "python", "django", "django-forms" ]
How do you dynamically hide form fields in Django?
1,255,976
<p>I am making a profile form in Django. There are a lot of optional extra profile fields but I would only like to show two at a time. How do I hide or remove the fields I do not want to show dynamically? </p> <p>Here is what I have so far:</p> <pre><code>class UserProfileForm(forms.ModelForm): extra_fields = ('f...
13
2009-08-10T16:51:04Z
1,256,705
<p>I think I found my answer.</p> <p>First I tried:</p> <pre><code>field.widget = field.hidden_widget </code></pre> <p>which didn't work.</p> <p>The correct way happens to be:</p> <pre><code>field.widget = field.hidden_widget() </code></pre>
14
2009-08-10T19:18:53Z
[ "python", "django", "django-forms" ]
How do you dynamically hide form fields in Django?
1,255,976
<p>I am making a profile form in Django. There are a lot of optional extra profile fields but I would only like to show two at a time. How do I hide or remove the fields I do not want to show dynamically? </p> <p>Here is what I have so far:</p> <pre><code>class UserProfileForm(forms.ModelForm): extra_fields = ('f...
13
2009-08-10T16:51:04Z
9,183,273
<p>Can also use</p> <pre><code>def __init__(self, instance, *args, **kwargs): super(FormClass, self).__init__(instance=instance, *args, **kwargs) if instance and instance.item: del self.fields['field_for_item'] </code></pre>
3
2012-02-07T20:21:35Z
[ "python", "django", "django-forms" ]
How do you dynamically hide form fields in Django?
1,255,976
<p>I am making a profile form in Django. There are a lot of optional extra profile fields but I would only like to show two at a time. How do I hide or remove the fields I do not want to show dynamically? </p> <p>Here is what I have so far:</p> <pre><code>class UserProfileForm(forms.ModelForm): extra_fields = ('f...
13
2009-08-10T16:51:04Z
9,792,130
<pre><code>def __init__(self, *args, **kwargs): is_video = kwargs.pop('is_video') is_image = kwargs.pop('is_image') super(ContestForm, self).__init__(*args, **kwargs) if is_video: del self.fields['video_link'] #self.exclude('video_link') ...
3
2012-03-20T17:42:19Z
[ "python", "django", "django-forms" ]
create an array from a txt file
1,256,099
<p>hey guys, I'm new in python and I have a problem. I have some measured data saved in a txt file. the data is separated with tabs, it has this structure:</p> <pre><code>0 0 -11.007001 -14.222319 2.336769 </code></pre> <p>i have always 32 datapoints per simulation (0,1,2,...,31) and i have 300 simulations (0,1,2.....
3
2009-08-10T17:19:12Z
1,256,160
<p>you can combine them with <a href="http://docs.python.org/library/functions.html?highlight=zip#zip" rel="nofollow"><code>zip</code> function</a>, like so:</p> <pre><code>for sim, datapoint, x, y, z in zip(simnum, npts, *xyz): # do your thing </code></pre> <p>or you could avoid list comprehensions altogether an...
2
2009-08-10T17:29:17Z
[ "python", "arrays", "text" ]
create an array from a txt file
1,256,099
<p>hey guys, I'm new in python and I have a problem. I have some measured data saved in a txt file. the data is separated with tabs, it has this structure:</p> <pre><code>0 0 -11.007001 -14.222319 2.336769 </code></pre> <p>i have always 32 datapoints per simulation (0,1,2,...,31) and i have 300 simulations (0,1,2.....
3
2009-08-10T17:19:12Z
1,256,221
<p>According to the zen of python, flat is better than nested. I'd just use a dict.</p> <pre><code>import csv f = csv.reader(open('thefile.csv'), delimiter='\t', quoting=csv.QUOTE_NONNUMERIC) result = {} for simn, dpoint, c1, c2, c3 in f: result[simn, dpoint] = c1, c2, c3 # pretty-prints the resul...
2
2009-08-10T17:43:20Z
[ "python", "arrays", "text" ]
create an array from a txt file
1,256,099
<p>hey guys, I'm new in python and I have a problem. I have some measured data saved in a txt file. the data is separated with tabs, it has this structure:</p> <pre><code>0 0 -11.007001 -14.222319 2.336769 </code></pre> <p>i have always 32 datapoints per simulation (0,1,2,...,31) and i have 300 simulations (0,1,2.....
3
2009-08-10T17:19:12Z
1,256,248
<p>This seems like a good opportunity to use itertools.groupby.</p> <pre><code>import itertools import csv file = open("data.txt") reader = csv.reader(file, delimiter='\t') result = [] for simnumberStr, rows in itertools.groupby(reader, key=lambda t: t[0]): simData = [] for row in rows: simData.append(...
2
2009-08-10T17:47:54Z
[ "python", "arrays", "text" ]
create an array from a txt file
1,256,099
<p>hey guys, I'm new in python and I have a problem. I have some measured data saved in a txt file. the data is separated with tabs, it has this structure:</p> <pre><code>0 0 -11.007001 -14.222319 2.336769 </code></pre> <p>i have always 32 datapoints per simulation (0,1,2,...,31) and i have 300 simulations (0,1,2.....
3
2009-08-10T17:19:12Z
1,256,313
<p>essentially the difficulty is what happens if different simulations have different numbers of points.</p> <p>You will therefore need to dimension an array to the appropriate sizes first. t should be an array of at least <code>max(simnum) x max(npts) x 3</code>. To eliminate confusion you should initialise with no...
1
2009-08-10T18:02:16Z
[ "python", "arrays", "text" ]
create an array from a txt file
1,256,099
<p>hey guys, I'm new in python and I have a problem. I have some measured data saved in a txt file. the data is separated with tabs, it has this structure:</p> <pre><code>0 0 -11.007001 -14.222319 2.336769 </code></pre> <p>i have always 32 datapoints per simulation (0,1,2,...,31) and i have 300 simulations (0,1,2.....
3
2009-08-10T17:19:12Z
1,256,365
<p>First I'd point out that your first data point appears to be an index, and wonder if the data is therefore important or not, but whichever :-)</p> <pre><code>def parse(line): mch = re.compile('^(\d+)\s+(\d+)\s+([-\d\.]+)\s+([-\d\.]+)\s+([-\d\.]+)$') m = mch.match(line) if m: l = m.groups() ...
0
2009-08-10T18:11:57Z
[ "python", "arrays", "text" ]
create an array from a txt file
1,256,099
<p>hey guys, I'm new in python and I have a problem. I have some measured data saved in a txt file. the data is separated with tabs, it has this structure:</p> <pre><code>0 0 -11.007001 -14.222319 2.336769 </code></pre> <p>i have always 32 datapoints per simulation (0,1,2,...,31) and i have 300 simulations (0,1,2.....
3
2009-08-10T17:19:12Z
1,256,420
<p>You could be using many different kinds of containers for your purposes, but none of them has <code>array</code> as an unqualified name -- Python has a module <code>array</code> which you can import from the standard library, but the <code>array.array</code> type is too limited for your purposes (1-D only and with e...
1
2009-08-10T18:25:03Z
[ "python", "arrays", "text" ]
create an array from a txt file
1,256,099
<p>hey guys, I'm new in python and I have a problem. I have some measured data saved in a txt file. the data is separated with tabs, it has this structure:</p> <pre><code>0 0 -11.007001 -14.222319 2.336769 </code></pre> <p>i have always 32 datapoints per simulation (0,1,2,...,31) and i have 300 simulations (0,1,2.....
3
2009-08-10T17:19:12Z
1,257,787
<p>Are you sure a 3d array is what you want? It seems more likely that you want a 2d array, where the simulation number is one dimension, the data point is the second, and then the value stored at that location is the coordinates.</p> <p>This code will give you that.</p> <pre><code>data = [] for coord in coords: ...
0
2009-08-10T23:26:49Z
[ "python", "arrays", "text" ]
Django - Getting last object created, simultaneous filters
1,256,190
<p>Apologies, I am completely new to Django and Python.</p> <p>I have 2 questions. First, how would I go about getting the last object created (or highest pk) in a list of objects? For example, I know that I could use the following to get the first object:</p> <pre><code>list = List.objects.all()[0] </code></pre> <p...
21
2009-08-10T17:35:15Z
1,256,241
<p>You can use the count() method on a query set the get the number of items.</p> <pre><code>list = List.objects.all() list.count() </code></pre> <p>Arguments to filter are "AND"ed together. If you need to do OR filters look at Q objects. <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookup...
4
2009-08-10T17:46:11Z
[ "python", "django", "filter", "django-views" ]
Django - Getting last object created, simultaneous filters
1,256,190
<p>Apologies, I am completely new to Django and Python.</p> <p>I have 2 questions. First, how would I go about getting the last object created (or highest pk) in a list of objects? For example, I know that I could use the following to get the first object:</p> <pre><code>list = List.objects.all()[0] </code></pre> <p...
21
2009-08-10T17:35:15Z
1,256,325
<p>I haven't tried this yet, but I'd look at the <em>latest()</em> operator on <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#ref-models-querysets">QuerySets</a>:</p> <blockquote> <p>latest(field_name=None)</p> <p>Returns the latest object in the table, by date, using the field_name pro...
31
2009-08-10T18:04:21Z
[ "python", "django", "filter", "django-views" ]
Django - Getting last object created, simultaneous filters
1,256,190
<p>Apologies, I am completely new to Django and Python.</p> <p>I have 2 questions. First, how would I go about getting the last object created (or highest pk) in a list of objects? For example, I know that I could use the following to get the first object:</p> <pre><code>list = List.objects.all()[0] </code></pre> <p...
21
2009-08-10T17:35:15Z
1,256,899
<p>For the largest primary key, try this: </p> <pre><code>List.objects.order_by('-pk')[0] </code></pre> <p>Note that using <code>pk</code> works regardless of the actual name of the field defined as your primary key.</p>
11
2009-08-10T19:58:19Z
[ "python", "django", "filter", "django-views" ]
Django - Getting last object created, simultaneous filters
1,256,190
<p>Apologies, I am completely new to Django and Python.</p> <p>I have 2 questions. First, how would I go about getting the last object created (or highest pk) in a list of objects? For example, I know that I could use the following to get the first object:</p> <pre><code>list = List.objects.all()[0] </code></pre> <p...
21
2009-08-10T17:35:15Z
1,886,857
<p>this works!</p> <p><code>Model.objects.latest('field')</code> - field can be id. that will be the latest id</p>
13
2009-12-11T09:28:20Z
[ "python", "django", "filter", "django-views" ]
Django - Getting last object created, simultaneous filters
1,256,190
<p>Apologies, I am completely new to Django and Python.</p> <p>I have 2 questions. First, how would I go about getting the last object created (or highest pk) in a list of objects? For example, I know that I could use the following to get the first object:</p> <pre><code>list = List.objects.all()[0] </code></pre> <p...
21
2009-08-10T17:35:15Z
24,908,035
<p>alternative for the latest object created:</p> <pre><code>List.objects.all()[List.objects.count()-1] </code></pre> <p>It is necessary to add an AssertionError for the case when there are no items in the list.</p> <pre><code>except AssertionError: ... </code></pre>
0
2014-07-23T10:30:04Z
[ "python", "django", "filter", "django-views" ]
Django - Getting last object created, simultaneous filters
1,256,190
<p>Apologies, I am completely new to Django and Python.</p> <p>I have 2 questions. First, how would I go about getting the last object created (or highest pk) in a list of objects? For example, I know that I could use the following to get the first object:</p> <pre><code>list = List.objects.all()[0] </code></pre> <p...
21
2009-08-10T17:35:15Z
33,762,411
<p><strong>Since Django 1.6 - last</strong></p> <p><code>last()</code></p> <p>Works like <code>first()</code>, but returns the last object in the queryset. </p> <p>Returns the last object matched by the queryset, or <code>None</code> if there is no matching object. If the QuerySet has no ordering defined, then the q...
5
2015-11-17T16:41:44Z
[ "python", "django", "filter", "django-views" ]
pywikipedia bot with https and http authentication
1,256,213
<p>I'm having trouble getting my bot to login to a MediaWiki install on the intranet. I believe it is due to the http authentication protecting the wiki. </p> <p>Facts:</p> <ol> <li>The wiki root is: <a href="https://local.example.com/mywiki/" rel="nofollow">https://local.example.com/mywiki/</a></li> <li>When visitin...
3
2009-08-10T17:41:25Z
1,257,603
<p>I am guessing the problem you have is that the server expects basic authentication and you are not handling that in your client. Michael Foord wrote a good article about handling <a href="http://www.voidspace.org.uk/python/articles/authentication.shtml" rel="nofollow">basic authentication in Python</a>.</p> <p>You ...
0
2009-08-10T22:31:59Z
[ "python", "https", "urllib2", "http-authentication", "pywikipedia" ]
pywikipedia bot with https and http authentication
1,256,213
<p>I'm having trouble getting my bot to login to a MediaWiki install on the intranet. I believe it is due to the http authentication protecting the wiki. </p> <p>Facts:</p> <ol> <li>The wiki root is: <a href="https://local.example.com/mywiki/" rel="nofollow">https://local.example.com/mywiki/</a></li> <li>When visitin...
3
2009-08-10T17:41:25Z
1,258,883
<p>Well the fact that <code>login.py</code> tries accessing '\w' instead of your path shows that there is a family configuration issue.</p> <p>Your code is indented strangely: is <code>scriptpath</code> a member of the new Family class? as in:</p> <pre><code>class Family(family.Family): def __init__(self): ...
4
2009-08-11T07:29:46Z
[ "python", "https", "urllib2", "http-authentication", "pywikipedia" ]
Selecting related objects in django
1,256,387
<p>I have following problem:</p> <p>My application have 2 models:</p> <p>1)</p> <pre><code>class ActiveList(models.Model): user = models.ForeignKey(User, unique=True) updatedOn = models.DateTimeField(auto_now=True) def __unicode__(self): return self.user.username ''' GameClaim class, to store ga...
0
2009-08-10T18:17:02Z
1,256,513
<p>I'm not sure I entirely understand your question, but I think the information you're looking for might be here: <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/db/queries/</a></p> <p>Perhaps you could clarify the question if you don't find...
0
2009-08-10T18:42:15Z
[ "python", "django" ]
Selecting related objects in django
1,256,387
<p>I have following problem:</p> <p>My application have 2 models:</p> <p>1)</p> <pre><code>class ActiveList(models.Model): user = models.ForeignKey(User, unique=True) updatedOn = models.DateTimeField(auto_now=True) def __unicode__(self): return self.user.username ''' GameClaim class, to store ga...
0
2009-08-10T18:17:02Z
1,256,748
<p>What you are looking at doing belongs more properly in the view than the template. I think you want something like:</p> <pre><code>claimer = User.objects.get(name='test') claimed_opponents = User.objects.filter(gameclaim_opponent__me__user=claimer) </code></pre> <p>Then you can pass those into your template, and ...
1
2009-08-10T19:28:33Z
[ "python", "django" ]
Checking whether a command produced output
1,256,424
<p>I am using the following call for executing the 'aspell' command on some strings in Python:</p> <pre><code>r,w,e = popen2.popen3("echo " +str(m[i]) + " | aspell -l") </code></pre> <p>I want to test the success of the function looking at the stdout File Object <code>r</code>. If there is no output the command is su...
0
2009-08-10T18:25:57Z
1,256,449
<p>Best is to use the <code>subprocess</code> module of the standard Python library, see <a href="http://docs.python.org/library/subprocess.html?highlight=subprocess#module-subprocess" rel="nofollow">here</a> -- <code>popen2</code> is old and not recommended.</p> <p>Anyway, in your code, <code>if r.read(1):</code> is ...
2
2009-08-10T18:30:13Z
[ "python", "unix", "scripting" ]
Checking whether a command produced output
1,256,424
<p>I am using the following call for executing the 'aspell' command on some strings in Python:</p> <pre><code>r,w,e = popen2.popen3("echo " +str(m[i]) + " | aspell -l") </code></pre> <p>I want to test the success of the function looking at the stdout File Object <code>r</code>. If there is no output the command is su...
0
2009-08-10T18:25:57Z
1,256,483
<p>Why don't you use <code>aspell -a</code>?</p> <p>You could use subprocess as indicated by Alex, but keep the pipe open. Follow <a href="http://aspell.net/man-html/Through-A-Pipe.html#Through-A-Pipe" rel="nofollow">the directions</a> for using the pipe API of aspell, and it should be pretty efficient.</p> <p>The u...
2
2009-08-10T18:36:52Z
[ "python", "unix", "scripting" ]
Need help in refactoring my python script
1,256,704
<p>I have a python script which process a file line by line, if the line matches a regex, it calls a function to handle it.</p> <p>My question is is there a better write to refactor my script. The script works, but as it is, i need to keep indent to the right of the editor as I add more and more regex for my file.</p>...
3
2009-08-10T19:18:13Z
1,256,723
<p>I'd switch to using a data structure mapping regexes to functions. Something like:</p> <pre><code>map = { reg1: handleReg1, reg2: handleReg2, etc } </code></pre> <p>Then you just loop through them:</p> <pre><code>for reg, handler in map.items(): result = reg.match(line) if result: handler(result) ...
12
2009-08-10T19:24:29Z
[ "python" ]
Need help in refactoring my python script
1,256,704
<p>I have a python script which process a file line by line, if the line matches a regex, it calls a function to handle it.</p> <p>My question is is there a better write to refactor my script. The script works, but as it is, i need to keep indent to the right of the editor as I add more and more regex for my file.</p>...
3
2009-08-10T19:18:13Z
1,256,730
<p>Here's a trivial one:</p> <pre><code>handlers = { reg1 : handleReg1, ... } for line in fi.readlines(): for h in handlers: x = h.match(line) if x: handlers[h](x) </code></pre> <p>If there could be a line that matches several regexps this code will be different from the code you past...
1
2009-08-10T19:25:32Z
[ "python" ]
Need help in refactoring my python script
1,256,704
<p>I have a python script which process a file line by line, if the line matches a regex, it calls a function to handle it.</p> <p>My question is is there a better write to refactor my script. The script works, but as it is, i need to keep indent to the right of the editor as I add more and more regex for my file.</p>...
3
2009-08-10T19:18:13Z
1,256,782
<p>An alternate approach that might work for you is to combine all the regexps into one giant regexp and use m.group() to detect which matched. My intuition says this should be faster, but I haven't tested it.</p> <pre><code>&gt;&gt;&gt; reg = re.compile('(cat)|(dog)|(apple)') &gt;&gt;&gt; m = reg.search('we like dogs...
0
2009-08-10T19:37:16Z
[ "python" ]