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
sequence
javascript locals()?
39,960
<p>In python one can get a dictionary of all local and global variables in the current scope with the built-in functions locals() and globals(). Is there some equivalent way of doing this in javascript? For instance, I would like to do something like the following:</p> <pre><code>var foo = function(){ alert('foo'); }; var bar = function(){ alert('bar'); }; var s = 'foo'; locals()[s](); // alerts 'foo' </code></pre> <p>Is this at all possible, or should I just be using a local object for the lookup?</p>
17
2008-09-02T16:29:30Z
40,035
<p>@e-bartek, I think that window[functionName] won't work if you in some closure, and the function name is local to that closure. For example:</p> <pre><code>function foo() { var bar = function () { alert('hello world'); }; var s = 'bar'; window[s](); // this won't work } </code></pre> <p>In this case, s is 'bar', but the function 'bar' only exists inside the scope of the function 'foo'. It is not defined in the window scope.</p> <p>Of course, this doesn't really answer the original question, I just wanted to chime in on this response. I don't believe there is a way to do what the original question asked.</p>
0
2008-09-02T17:00:12Z
[ "javascript", "python" ]
javascript locals()?
39,960
<p>In python one can get a dictionary of all local and global variables in the current scope with the built-in functions locals() and globals(). Is there some equivalent way of doing this in javascript? For instance, I would like to do something like the following:</p> <pre><code>var foo = function(){ alert('foo'); }; var bar = function(){ alert('bar'); }; var s = 'foo'; locals()[s](); // alerts 'foo' </code></pre> <p>Is this at all possible, or should I just be using a local object for the lookup?</p>
17
2008-09-02T16:29:30Z
40,067
<p>@pkaeding</p> <p>Yes, you're right. <em>window[functionName]()</em> doesn't work in this case, but <em>eval</em> does. If I needed something like this, I'd create my own object to keep those functions together.</p> <pre><code>var func = {}; func.bar = ...; var s = "bar"; func[s](); </code></pre>
0
2008-09-02T17:14:25Z
[ "javascript", "python" ]
javascript locals()?
39,960
<p>In python one can get a dictionary of all local and global variables in the current scope with the built-in functions locals() and globals(). Is there some equivalent way of doing this in javascript? For instance, I would like to do something like the following:</p> <pre><code>var foo = function(){ alert('foo'); }; var bar = function(){ alert('bar'); }; var s = 'foo'; locals()[s](); // alerts 'foo' </code></pre> <p>Is this at all possible, or should I just be using a local object for the lookup?</p>
17
2008-09-02T16:29:30Z
40,173
<ul> <li><p>locals() - No. </p></li> <li><p>globals() - Yes.</p></li> </ul> <p><code>window</code> is a reference to the global scope, like <code>globals()</code> in python.</p> <pre><code>globals()["foo"] </code></pre> <p>is the same as:</p> <pre><code>window["foo"] </code></pre>
13
2008-09-02T18:01:29Z
[ "javascript", "python" ]
cx_Oracle: how do I get the ORA-xxxxx error number?
40,586
<p>In a try/except block, how do I extract the Oracle error number?</p>
1
2008-09-02T20:40:29Z
40,593
<pre><code>try: cursor.execute("select 1 / 0 from dual") except cx_Oracle.DatabaseError, exc: error, = exc print "Code:", error.code print "Message:", error.message </code></pre> <p>This results in the following output:</p> <pre><code>Code: 1476 Message: ORA-01476: divisor is equal to zero </code></pre>
9
2008-09-02T20:41:33Z
[ "python", "oracle", "cx-oracle" ]
Python deployment and /usr/bin/env portability
40,705
<p>At the beginning of all my executable Python scripts I put the <a href="http://en.wikipedia.org/wiki/Shebang_(Unix)">shebang</a> line:</p> <pre><code>#!/usr/bin/env python </code></pre> <p>I'm running these scripts on a system where <code>env python</code> yields a Python 2.2 environment. My scripts quickly fail because I have a manual check for a compatible Python version:</p> <pre><code>if sys.version_info &lt; (2, 4): raise ImportError("Cannot run with Python version &lt; 2.4") </code></pre> <p>I don't want to have to change the shebang line on every executable file, if it's possible; however, I don't have administrative access to the machine to change the result of <code>env python</code> and I don't want to force a particular version, as in:</p> <pre><code>#!/usr/bin/env python2.4 </code></pre> <p>I'd like to avoid this because system may have a newer version than Python 2.4, or may have Python 2.5 but no Python 2.4.</p> <p>What's the elegant solution?</p> <p>[Edit:] I wasn't specific enough in posing the question -- I'd like to let users execute the scripts without manual configuration (e.g. path alteration or symlinking in <code>~/bin</code> and ensuring your PATH has <code>~/bin</code> before the Python 2.2 path). Maybe some distribution utility is required to prevent the manual tweaks?</p>
12
2008-09-02T21:21:14Z
40,715
<p>"env" simply executes the first thing it finds in the PATH env var. To switch to different python, prepend the directory for that python's executable to the path before invoking your script.</p>
8
2008-09-02T21:25:40Z
[ "python", "executable", "environment", "shebang" ]
Python deployment and /usr/bin/env portability
40,705
<p>At the beginning of all my executable Python scripts I put the <a href="http://en.wikipedia.org/wiki/Shebang_(Unix)">shebang</a> line:</p> <pre><code>#!/usr/bin/env python </code></pre> <p>I'm running these scripts on a system where <code>env python</code> yields a Python 2.2 environment. My scripts quickly fail because I have a manual check for a compatible Python version:</p> <pre><code>if sys.version_info &lt; (2, 4): raise ImportError("Cannot run with Python version &lt; 2.4") </code></pre> <p>I don't want to have to change the shebang line on every executable file, if it's possible; however, I don't have administrative access to the machine to change the result of <code>env python</code> and I don't want to force a particular version, as in:</p> <pre><code>#!/usr/bin/env python2.4 </code></pre> <p>I'd like to avoid this because system may have a newer version than Python 2.4, or may have Python 2.5 but no Python 2.4.</p> <p>What's the elegant solution?</p> <p>[Edit:] I wasn't specific enough in posing the question -- I'd like to let users execute the scripts without manual configuration (e.g. path alteration or symlinking in <code>~/bin</code> and ensuring your PATH has <code>~/bin</code> before the Python 2.2 path). Maybe some distribution utility is required to prevent the manual tweaks?</p>
12
2008-09-02T21:21:14Z
40,721
<p>If you are running the scripts then you can set your PATH variable to point to a private bin directory first:</p> <pre><code>$ mkdir ~/bin $ ln -s `which python2.4` ~/bin/python $ export PATH=~/bin:$PATH </code></pre> <p>Then when you execute your python script it'll use python 2.4. You'll have to change your login scripts to change your PATH.</p> <p>Alternatively run your python script with the explicit interpreter you want:</p> <pre><code>$ /path/to/python2.4 &lt;your script&gt; </code></pre>
2
2008-09-02T21:28:03Z
[ "python", "executable", "environment", "shebang" ]
Python deployment and /usr/bin/env portability
40,705
<p>At the beginning of all my executable Python scripts I put the <a href="http://en.wikipedia.org/wiki/Shebang_(Unix)">shebang</a> line:</p> <pre><code>#!/usr/bin/env python </code></pre> <p>I'm running these scripts on a system where <code>env python</code> yields a Python 2.2 environment. My scripts quickly fail because I have a manual check for a compatible Python version:</p> <pre><code>if sys.version_info &lt; (2, 4): raise ImportError("Cannot run with Python version &lt; 2.4") </code></pre> <p>I don't want to have to change the shebang line on every executable file, if it's possible; however, I don't have administrative access to the machine to change the result of <code>env python</code> and I don't want to force a particular version, as in:</p> <pre><code>#!/usr/bin/env python2.4 </code></pre> <p>I'd like to avoid this because system may have a newer version than Python 2.4, or may have Python 2.5 but no Python 2.4.</p> <p>What's the elegant solution?</p> <p>[Edit:] I wasn't specific enough in posing the question -- I'd like to let users execute the scripts without manual configuration (e.g. path alteration or symlinking in <code>~/bin</code> and ensuring your PATH has <code>~/bin</code> before the Python 2.2 path). Maybe some distribution utility is required to prevent the manual tweaks?</p>
12
2008-09-02T21:21:14Z
42,516
<p>Pretty hackish solution - if your check fails, use this function (which probably could be significantly improved) to determine the best interpreter available, determine if it is acceptable, and if so relaunch your script with os.system or something similar and your sys.argv using the new interpreter.</p> <pre><code>import os import glob def best_python(): plist = [] for i in os.getenv("PATH").split(":"): for j in glob.glob(os.path.join(i, "python2.[0-9]")): plist.append(os.path.join(i, j)) plist.sort() plist.reverse() if len(plist) == 0: return None return plist[0] </code></pre>
4
2008-09-03T20:32:40Z
[ "python", "executable", "environment", "shebang" ]
Python deployment and /usr/bin/env portability
40,705
<p>At the beginning of all my executable Python scripts I put the <a href="http://en.wikipedia.org/wiki/Shebang_(Unix)">shebang</a> line:</p> <pre><code>#!/usr/bin/env python </code></pre> <p>I'm running these scripts on a system where <code>env python</code> yields a Python 2.2 environment. My scripts quickly fail because I have a manual check for a compatible Python version:</p> <pre><code>if sys.version_info &lt; (2, 4): raise ImportError("Cannot run with Python version &lt; 2.4") </code></pre> <p>I don't want to have to change the shebang line on every executable file, if it's possible; however, I don't have administrative access to the machine to change the result of <code>env python</code> and I don't want to force a particular version, as in:</p> <pre><code>#!/usr/bin/env python2.4 </code></pre> <p>I'd like to avoid this because system may have a newer version than Python 2.4, or may have Python 2.5 but no Python 2.4.</p> <p>What's the elegant solution?</p> <p>[Edit:] I wasn't specific enough in posing the question -- I'd like to let users execute the scripts without manual configuration (e.g. path alteration or symlinking in <code>~/bin</code> and ensuring your PATH has <code>~/bin</code> before the Python 2.2 path). Maybe some distribution utility is required to prevent the manual tweaks?</p>
12
2008-09-02T21:21:14Z
42,794
<p>@morais: That's an interesting idea, but I think maybe we can take it one step farther. Maybe there's a way to use <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">Ian Bicking's virtualenv</a> to:</p> <ul> <li>See if we're running in an acceptable environment to begin with, and if so, do nothing.</li> <li>Check if there exists a version-specific executable on the <code>PATH</code>, i.e. check if <code>python2.x</code> exists <code>for x in reverse(range(4, 10))</code>. If so, re-run the command with the better interpreter.</li> <li>If no better interpreter exists, use virtualenv to try and install a newer version of Python from the older version of Python and get any prerequisite packages.</li> </ul> <p>I have no idea if virtualenv is capable of this, so I'll go mess around with it sometime soon. :)</p>
0
2008-09-03T23:07:53Z
[ "python", "executable", "environment", "shebang" ]
Python deployment and /usr/bin/env portability
40,705
<p>At the beginning of all my executable Python scripts I put the <a href="http://en.wikipedia.org/wiki/Shebang_(Unix)">shebang</a> line:</p> <pre><code>#!/usr/bin/env python </code></pre> <p>I'm running these scripts on a system where <code>env python</code> yields a Python 2.2 environment. My scripts quickly fail because I have a manual check for a compatible Python version:</p> <pre><code>if sys.version_info &lt; (2, 4): raise ImportError("Cannot run with Python version &lt; 2.4") </code></pre> <p>I don't want to have to change the shebang line on every executable file, if it's possible; however, I don't have administrative access to the machine to change the result of <code>env python</code> and I don't want to force a particular version, as in:</p> <pre><code>#!/usr/bin/env python2.4 </code></pre> <p>I'd like to avoid this because system may have a newer version than Python 2.4, or may have Python 2.5 but no Python 2.4.</p> <p>What's the elegant solution?</p> <p>[Edit:] I wasn't specific enough in posing the question -- I'd like to let users execute the scripts without manual configuration (e.g. path alteration or symlinking in <code>~/bin</code> and ensuring your PATH has <code>~/bin</code> before the Python 2.2 path). Maybe some distribution utility is required to prevent the manual tweaks?</p>
12
2008-09-02T21:21:14Z
19,188,285
<p>Here's a solution if you're (1) absolutely set on using shebangs and (2) able to use Autotools in your build process.</p> <p>I just found last night that you can use the autoconf macro <code>AM_PATH_PYTHON</code> to find a minimal Python <strong>2</strong> binary. The how-to is <a href="http://stackoverflow.com/a/19173018/1207160">here</a>.</p> <p>So, your process would be:</p> <ul> <li>Issue an <code>AM_PATH_PYTHON(2.4)</code> in your <code>configure.ac</code></li> <li>Rename all of your <code>.py</code> scripts to <code>.py.in</code> (in my experience, this doesn't confuse <code>vi</code>)</li> <li>Name all of those Python scripts you want to generate with <code>AC_CONFIG_FILES</code>.</li> <li>Instead of starting with <code>#!/usr/bin/env python</code>, use <code>#!@PYTHON@</code></li> </ul> <p>Then your <em>resultant</em> Python scripts will always have an appropriate shebang.</p> <p>So, you have this solution, at least possible, if not practical.</p>
0
2013-10-04T18:27:17Z
[ "python", "executable", "environment", "shebang" ]
Always including the user in the django template context
41,547
<p>I am working on a small intranet site for a small company, where user should be able to post. I have imagined a very simple authentication mechanism where people just enter their email address, and gets sent a unique login url, that sets a cookie that will always identify them for future requests.</p> <p>In my template setup, I have base.html, and the other pages extend this. I want to show logged in or register button in the base.html, but how can I ensure that the necessary variables are always a part of the context? It seems that each view just sets up the context as they like, and there is no global context population. Is there a way of doing this without including the user in each context creation?</p> <p>Or will I have to make my own custom shortcuts to setup the context properly?</p>
25
2008-09-03T12:22:44Z
41,555
<p>If you can hook your authentication into the <a href="http://www.djangoproject.com/documentation/authentication/#authentication-in-web-requests" rel="nofollow">Django authentication scheme</a> you'll be able to use <code>request.user</code>.</p> <p>I think this should just be a case of calling <code>authenticate()</code> and <code>login()</code> based on the contents of your Cookie.</p> <p>Edit: @Staale - I always use the <a href="http://www.djangobook.com/en/1.0/chapter04/" rel="nofollow"><code>locals()</code> trick</a> for my context so all my templates can see <code>request</code> and so <code>request.user</code>. If you're not then I guess it wouldn't be so straightforward.</p>
2
2008-09-03T12:28:34Z
[ "python", "django", "authentication", "session", "cookies" ]
Always including the user in the django template context
41,547
<p>I am working on a small intranet site for a small company, where user should be able to post. I have imagined a very simple authentication mechanism where people just enter their email address, and gets sent a unique login url, that sets a cookie that will always identify them for future requests.</p> <p>In my template setup, I have base.html, and the other pages extend this. I want to show logged in or register button in the base.html, but how can I ensure that the necessary variables are always a part of the context? It seems that each view just sets up the context as they like, and there is no global context population. Is there a way of doing this without including the user in each context creation?</p> <p>Or will I have to make my own custom shortcuts to setup the context properly?</p>
25
2008-09-03T12:22:44Z
41,558
<p>In a more general sense of not having to explicitly set variables in each view, it sounds like you want to look at writing your own <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors">context processor</a>.</p> <p>From the docs:</p> <blockquote> <p>A context processor has a very simple interface: It's just a Python function that takes one argument, an HttpRequest object, and returns a dictionary that gets added to the template context. Each context processor must return a dictionary.</p> </blockquote>
18
2008-09-03T12:31:58Z
[ "python", "django", "authentication", "session", "cookies" ]
Always including the user in the django template context
41,547
<p>I am working on a small intranet site for a small company, where user should be able to post. I have imagined a very simple authentication mechanism where people just enter their email address, and gets sent a unique login url, that sets a cookie that will always identify them for future requests.</p> <p>In my template setup, I have base.html, and the other pages extend this. I want to show logged in or register button in the base.html, but how can I ensure that the necessary variables are always a part of the context? It seems that each view just sets up the context as they like, and there is no global context population. Is there a way of doing this without including the user in each context creation?</p> <p>Or will I have to make my own custom shortcuts to setup the context properly?</p>
25
2008-09-03T12:22:44Z
41,560
<p>@Dave To use {{user.username}} in my templates, I will then have to use requestcontext rather than just a normal map/hash: <a href="http://www.djangoproject.com/documentation/templates_python/#subclassing-context-requestcontext" rel="nofollow">http://www.djangoproject.com/documentation/templates_python/#subclassing-context-requestcontext</a></p> <p>So I guess there are no globals that the template engine checks.</p> <p>But the RequestContext has some prepopulate classes that I can look into to solve my problems. Thanks.</p>
2
2008-09-03T12:33:31Z
[ "python", "django", "authentication", "session", "cookies" ]
Always including the user in the django template context
41,547
<p>I am working on a small intranet site for a small company, where user should be able to post. I have imagined a very simple authentication mechanism where people just enter their email address, and gets sent a unique login url, that sets a cookie that will always identify them for future requests.</p> <p>In my template setup, I have base.html, and the other pages extend this. I want to show logged in or register button in the base.html, but how can I ensure that the necessary variables are always a part of the context? It seems that each view just sets up the context as they like, and there is no global context population. Is there a way of doing this without including the user in each context creation?</p> <p>Or will I have to make my own custom shortcuts to setup the context properly?</p>
25
2008-09-03T12:22:44Z
269,249
<p>@Ryan: Documentation about preprocessors is a bit small</p> <p>@Staale: Adding user to the Context every time one is calling the template in view, DRY</p> <p>Solution is very simple</p> <p><strong>A</strong>: In your settings add</p> <pre><code>TEMPLATE_CONTEXT_PROCESSORS = ( 'myapp.processor_file_name.user', ) </code></pre> <p><strong>B</strong>: In myapp/processor_file_name.py insert</p> <pre><code>def user(request): if hasattr(request, 'user'): return {'user':request.user } return {} </code></pre> <p>From now on you're able to use user object functionalities in your templates.</p> <pre><code>{{ user.get_full_name }} </code></pre>
31
2008-11-06T16:05:03Z
[ "python", "django", "authentication", "session", "cookies" ]
Always including the user in the django template context
41,547
<p>I am working on a small intranet site for a small company, where user should be able to post. I have imagined a very simple authentication mechanism where people just enter their email address, and gets sent a unique login url, that sets a cookie that will always identify them for future requests.</p> <p>In my template setup, I have base.html, and the other pages extend this. I want to show logged in or register button in the base.html, but how can I ensure that the necessary variables are always a part of the context? It seems that each view just sets up the context as they like, and there is no global context population. Is there a way of doing this without including the user in each context creation?</p> <p>Or will I have to make my own custom shortcuts to setup the context properly?</p>
25
2008-09-03T12:22:44Z
1,064,621
<p>There is <strong>no need</strong> to write a context processor for the user object if you already have the <a href="https://docs.djangoproject.com/en/dev/topics/auth/default/#authentication-data-in-templates"><code>"django.core.context_processors.auth"</code></a> in <a href="https://docs.djangoproject.com/en/dev/ref/settings/#std%3asetting-TEMPLATE_CONTEXT_PROCESSORS"><code>TEMPLATE_CONTEXT_PROCESSORS</code></a> <strong>and</strong> if you're using <a href="https://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext"><code>RequestContext</code></a> in your views. </p> <p>if you are using django 1.4 or latest the module has been moved to <code>django.contrib.auth.context_processors.auth</code></p>
43
2009-06-30T16:14:29Z
[ "python", "django", "authentication", "session", "cookies" ]
Always including the user in the django template context
41,547
<p>I am working on a small intranet site for a small company, where user should be able to post. I have imagined a very simple authentication mechanism where people just enter their email address, and gets sent a unique login url, that sets a cookie that will always identify them for future requests.</p> <p>In my template setup, I have base.html, and the other pages extend this. I want to show logged in or register button in the base.html, but how can I ensure that the necessary variables are always a part of the context? It seems that each view just sets up the context as they like, and there is no global context population. Is there a way of doing this without including the user in each context creation?</p> <p>Or will I have to make my own custom shortcuts to setup the context properly?</p>
25
2008-09-03T12:22:44Z
4,815,619
<p>its possible by default, by doing the following steps, ensure you have added the context 'django.contrib.auth.context_processors.auth' in your settings. By default its added in settings.py, so its looks like this </p> <pre><code>TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.auth',) </code></pre> <p>And you can access user object like this,</p> <pre><code>{% if user.is_authenticated %} &lt;p&gt;Welcome, {{ user.username }}. Thanks for logging in.&lt;/p&gt; {% else %} &lt;p&gt;Welcome, new user. Please log in.&lt;/p&gt; {% endif %} </code></pre> <p>For more information, refer here <a href="http://docs.djangoproject.com/en/1.2/topics/auth/#authentication-data-in-templates" rel="nofollow">http://docs.djangoproject.com/en/1.2/topics/auth/#authentication-data-in-templates</a> </p>
1
2011-01-27T11:15:12Z
[ "python", "django", "authentication", "session", "cookies" ]
Always including the user in the django template context
41,547
<p>I am working on a small intranet site for a small company, where user should be able to post. I have imagined a very simple authentication mechanism where people just enter their email address, and gets sent a unique login url, that sets a cookie that will always identify them for future requests.</p> <p>In my template setup, I have base.html, and the other pages extend this. I want to show logged in or register button in the base.html, but how can I ensure that the necessary variables are always a part of the context? It seems that each view just sets up the context as they like, and there is no global context population. Is there a way of doing this without including the user in each context creation?</p> <p>Or will I have to make my own custom shortcuts to setup the context properly?</p>
25
2008-09-03T12:22:44Z
11,878,636
<p>The hints are in every answer, but once again, from "scratch", for newbies:</p> <p>authentication data is in templates (almost) by default -- with a small trick:</p> <p>in <code>views.py</code>:</p> <pre><code>from django.template import RequestContext ... def index(request): return render_to_response('index.html', {'var': 'value'}, context_instance=RequestContext(request)) </code></pre> <p>in <code>index.html</code>:</p> <pre><code>... Hi, {{ user.username }} var: {{ value }} ... </code></pre> <p>From here: <a href="https://docs.djangoproject.com/en/1.4/topics/auth/#authentication-data-in-templates" rel="nofollow">https://docs.djangoproject.com/en/1.4/topics/auth/#authentication-data-in-templates</a></p> <blockquote> <p>This template context variable is not available if a <strong>RequestContext</strong> is not being used.</p> </blockquote>
3
2012-08-09T07:28:58Z
[ "python", "django", "authentication", "session", "cookies" ]
How do I do monkeypatching in python?
41,562
<p>I've had to do some introspection in python and it wasn't pretty:</p> <pre><code>name = sys._getframe(1).f_code name = "%s:%d %s()" %(os.path.split(name.co_filename)[1],name.co_firstlineno,name.co_name) </code></pre> <p>To get something like</p> <pre><code>foo.py:22 bar() blah blah </code></pre> <p>In our debugging output.</p> <p>I'd ideally like to prepend anything to stderr with this sort of information -- Is it possible to change the behaviour of print globally within python?</p>
7
2008-09-03T12:35:45Z
41,574
<p>A print statement does its IO through "sys.stdout.write" so you can override sys.stdout if you want to manipulate the print stream.</p>
3
2008-09-03T12:42:43Z
[ "python", "monkeypatching" ]
How do I do monkeypatching in python?
41,562
<p>I've had to do some introspection in python and it wasn't pretty:</p> <pre><code>name = sys._getframe(1).f_code name = "%s:%d %s()" %(os.path.split(name.co_filename)[1],name.co_firstlineno,name.co_name) </code></pre> <p>To get something like</p> <pre><code>foo.py:22 bar() blah blah </code></pre> <p>In our debugging output.</p> <p>I'd ideally like to prepend anything to stderr with this sort of information -- Is it possible to change the behaviour of print globally within python?</p>
7
2008-09-03T12:35:45Z
41,921
<p>The python <a href="http://www.python.org/doc/current/lib/module-inspect.html" rel="nofollow">inspect</a> module makes this a lot easier and cleaner. </p>
1
2008-09-03T15:21:20Z
[ "python", "monkeypatching" ]
Splitting tuples in Python - best practice?
41,701
<p>I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username)</p> <p>For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code like this: (jobId, label, username) = job</p> <p>I've realised, however, that this is a maintenance nightmare, because now I can never add new fields to the result set without breaking all of my existing code. How should I have written this?</p> <p>Here are my two best guesses: (jobId, label, username) = (job[0], job[1], job[2]) ...but that doesn't scale nicely when you have 15...20 fields</p> <p>or to convert the results from the SQL query to a dictionary straight away and pass that around (I don't have control over the fact that it starts life as a tuple, that's fixed for me)</p>
12
2008-09-03T13:48:30Z
41,707
<p>I'd say that a dictionary is definitely the best way to do it. It's easily extensible, allows you to give each value a sensible name, and Python has a lot of built-in language features for using and manipulating dictionaries. If you need to add more fields later, all you need to change is the code that converts the tuple to a dictionary and the code that actually makes use of the new values.</p> <p>For example:</p> <pre><code>job={} job['jobid'], job['label'], job['username']=&lt;querycode&gt; </code></pre>
13
2008-09-03T13:50:24Z
[ "python", "tuples" ]
Splitting tuples in Python - best practice?
41,701
<p>I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username)</p> <p>For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code like this: (jobId, label, username) = job</p> <p>I've realised, however, that this is a maintenance nightmare, because now I can never add new fields to the result set without breaking all of my existing code. How should I have written this?</p> <p>Here are my two best guesses: (jobId, label, username) = (job[0], job[1], job[2]) ...but that doesn't scale nicely when you have 15...20 fields</p> <p>or to convert the results from the SQL query to a dictionary straight away and pass that around (I don't have control over the fact that it starts life as a tuple, that's fixed for me)</p>
12
2008-09-03T13:48:30Z
41,709
<p>With a tuple it will always be a hassle to add or change fields. You're right that a dictionary will be much better. </p> <p>If you want something with slightly friendlier syntax you might want to take a look at the answers <a href="http://stackoverflow.com/questions/35988/c-like-structures-in-python" rel="nofollow">this question</a> about a simple 'struct-like' object. That way you can pass around an object, say <code>job</code>, and access its fields even more easily than a tuple or dict:</p> <pre><code>job.jobId, job.username = jobId, username </code></pre>
0
2008-09-03T13:51:53Z
[ "python", "tuples" ]
Splitting tuples in Python - best practice?
41,701
<p>I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username)</p> <p>For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code like this: (jobId, label, username) = job</p> <p>I've realised, however, that this is a maintenance nightmare, because now I can never add new fields to the result set without breaking all of my existing code. How should I have written this?</p> <p>Here are my two best guesses: (jobId, label, username) = (job[0], job[1], job[2]) ...but that doesn't scale nicely when you have 15...20 fields</p> <p>or to convert the results from the SQL query to a dictionary straight away and pass that around (I don't have control over the fact that it starts life as a tuple, that's fixed for me)</p>
12
2008-09-03T13:48:30Z
41,721
<p>Perhaps this is overkill for your case, but I would be tempted to create a "Job" class that takes the tuple as its constructor argument and has respective properties on it. I'd then pass instances of this class around instead.</p>
3
2008-09-03T13:57:15Z
[ "python", "tuples" ]
Splitting tuples in Python - best practice?
41,701
<p>I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username)</p> <p>For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code like this: (jobId, label, username) = job</p> <p>I've realised, however, that this is a maintenance nightmare, because now I can never add new fields to the result set without breaking all of my existing code. How should I have written this?</p> <p>Here are my two best guesses: (jobId, label, username) = (job[0], job[1], job[2]) ...but that doesn't scale nicely when you have 15...20 fields</p> <p>or to convert the results from the SQL query to a dictionary straight away and pass that around (I don't have control over the fact that it starts life as a tuple, that's fixed for me)</p>
12
2008-09-03T13:48:30Z
41,723
<p>I would use a dictionary. You can convert the tuple to a dictionary this way:</p> <pre><code>values = &lt;querycode&gt; keys = ["jobid", "label", "username"] job = dict([[keys[i], values [i]] for i in xrange(len(values ))]) </code></pre> <p>This will first create an array [["jobid", val1], ["label", val2], ["username", val3]] and then convert that to a dictionary. If the result order or count changes, you just need to change the list of keys to match the new result.</p> <p>PS still fresh on Python myself, so there might be better ways off doing this.</p>
2
2008-09-03T13:59:28Z
[ "python", "tuples" ]
Splitting tuples in Python - best practice?
41,701
<p>I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username)</p> <p>For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code like this: (jobId, label, username) = job</p> <p>I've realised, however, that this is a maintenance nightmare, because now I can never add new fields to the result set without breaking all of my existing code. How should I have written this?</p> <p>Here are my two best guesses: (jobId, label, username) = (job[0], job[1], job[2]) ...but that doesn't scale nicely when you have 15...20 fields</p> <p>or to convert the results from the SQL query to a dictionary straight away and pass that around (I don't have control over the fact that it starts life as a tuple, that's fixed for me)</p>
12
2008-09-03T13:48:30Z
41,730
<p>How about this:</p> <pre><code>class TypedTuple: def __init__(self, fieldlist, items): self.fieldlist = fieldlist self.items = items def __getattr__(self, field): return self.items[self.fieldlist.index(field)] </code></pre> <p>You could then do:</p> <pre><code>j = TypedTuple(["jobid", "label", "username"], job) print j.jobid </code></pre> <p>It should be easy to swap <code>self.fieldlist.index(field)</code> with a dictionary lookup later on... just edit your <code>__init__</code> method! Something like Staale does.</p>
-2
2008-09-03T14:02:37Z
[ "python", "tuples" ]
Splitting tuples in Python - best practice?
41,701
<p>I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username)</p> <p>For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code like this: (jobId, label, username) = job</p> <p>I've realised, however, that this is a maintenance nightmare, because now I can never add new fields to the result set without breaking all of my existing code. How should I have written this?</p> <p>Here are my two best guesses: (jobId, label, username) = (job[0], job[1], job[2]) ...but that doesn't scale nicely when you have 15...20 fields</p> <p>or to convert the results from the SQL query to a dictionary straight away and pass that around (I don't have control over the fact that it starts life as a tuple, that's fixed for me)</p>
12
2008-09-03T13:48:30Z
41,846
<p>@Staale</p> <p>There is a better way:</p> <pre><code>job = dict(zip(keys, values)) </code></pre>
13
2008-09-03T14:51:48Z
[ "python", "tuples" ]
Splitting tuples in Python - best practice?
41,701
<p>I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username)</p> <p>For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code like this: (jobId, label, username) = job</p> <p>I've realised, however, that this is a maintenance nightmare, because now I can never add new fields to the result set without breaking all of my existing code. How should I have written this?</p> <p>Here are my two best guesses: (jobId, label, username) = (job[0], job[1], job[2]) ...but that doesn't scale nicely when you have 15...20 fields</p> <p>or to convert the results from the SQL query to a dictionary straight away and pass that around (I don't have control over the fact that it starts life as a tuple, that's fixed for me)</p>
12
2008-09-03T13:48:30Z
387,242
<p>An old question, but since no one mentioned it I'll add this from the Python Cookbook: </p> <p><a href="http://code.activestate.com/recipes/81252/" rel="nofollow">Recipe 81252: Using dtuple for Flexible Query Result Access </a></p> <p>This recipe is specifically designed for dealing with database results, and the dtuple solution allows you to access the results by name OR index number. This avoids having to access everything by subscript which is very difficult to maintain, as noted in your question.</p>
2
2008-12-22T20:22:43Z
[ "python", "tuples" ]
Splitting tuples in Python - best practice?
41,701
<p>I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username)</p> <p>For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code like this: (jobId, label, username) = job</p> <p>I've realised, however, that this is a maintenance nightmare, because now I can never add new fields to the result set without breaking all of my existing code. How should I have written this?</p> <p>Here are my two best guesses: (jobId, label, username) = (job[0], job[1], job[2]) ...but that doesn't scale nicely when you have 15...20 fields</p> <p>or to convert the results from the SQL query to a dictionary straight away and pass that around (I don't have control over the fact that it starts life as a tuple, that's fixed for me)</p>
12
2008-09-03T13:48:30Z
1,144,246
<p>This is an old question, but...</p> <p>I'd suggest using a named tuple in this situation: <a href="http://docs.python.org/3.1/library/collections.html#collections.namedtuple">collections.namedtuple</a></p> <p>This is the part, in particular, that you'd find useful:</p> <blockquote> <p>Subclassing is not useful for adding new, stored fields. Instead, simply create a new named tuple type from the _fields attribute.</p> </blockquote>
5
2009-07-17T16:08:40Z
[ "python", "tuples" ]
Splitting tuples in Python - best practice?
41,701
<p>I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username)</p> <p>For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code like this: (jobId, label, username) = job</p> <p>I've realised, however, that this is a maintenance nightmare, because now I can never add new fields to the result set without breaking all of my existing code. How should I have written this?</p> <p>Here are my two best guesses: (jobId, label, username) = (job[0], job[1], job[2]) ...but that doesn't scale nicely when you have 15...20 fields</p> <p>or to convert the results from the SQL query to a dictionary straight away and pass that around (I don't have control over the fact that it starts life as a tuple, that's fixed for me)</p>
12
2008-09-03T13:48:30Z
2,609,123
<p>If you're using the MySQLdb package, you can set up your cursor objects to return dicts instead of tuples.</p> <pre><code>import MySQLdb, MySQLdb.cursors conn = MySQLdb.connect(..., cursorclass=MySQLdb.cursors.DictCursor) cur = conn.cursor() # a DictCursor cur2 = conn.cursor(cursorclass=MySQLdb.cursors.Cursor) # a "normal" tuple cursor </code></pre>
0
2010-04-09T16:28:06Z
[ "python", "tuples" ]
Standard way to open a folder window in linux?
41,969
<p>I want to open a folder window, in the appropriate file manager, from within a cross-platform (windows/mac/linux) Python application.</p> <p>On OSX, I can open a window in the finder with</p> <pre><code>os.system('open "%s"' % foldername) </code></pre> <p>and on Windows with</p> <pre><code>os.startfile(foldername) </code></pre> <p>What about unix/linux? Is there a standard way to do this or do I have to special case gnome/kde/etc and manually run the appropriate application (nautilus/konqueror/etc)?</p> <p>This looks like something that could be specified by the <a href="http://freedesktop.org">freedesktop.org</a> folks (a python module, similar to <code>webbrowser</code>, would also be nice!).</p>
6
2008-09-03T15:47:23Z
41,999
<p>this would probably have to be done manually, or have as a config item since there are many file managers that users may want to use. Providing a way for command options as well.</p> <p>There might be an function that launches the defaults for kde or gnome in their respective toolkits but I haven't had reason to look for them.</p>
0
2008-09-03T16:02:06Z
[ "python", "linux", "cross-platform", "desktop" ]
Standard way to open a folder window in linux?
41,969
<p>I want to open a folder window, in the appropriate file manager, from within a cross-platform (windows/mac/linux) Python application.</p> <p>On OSX, I can open a window in the finder with</p> <pre><code>os.system('open "%s"' % foldername) </code></pre> <p>and on Windows with</p> <pre><code>os.startfile(foldername) </code></pre> <p>What about unix/linux? Is there a standard way to do this or do I have to special case gnome/kde/etc and manually run the appropriate application (nautilus/konqueror/etc)?</p> <p>This looks like something that could be specified by the <a href="http://freedesktop.org">freedesktop.org</a> folks (a python module, similar to <code>webbrowser</code>, would also be nice!).</p>
6
2008-09-03T15:47:23Z
42,039
<p>You're going to have to do this based on the running window manager. OSX and Windows have a (defacto) standard way because there is only one choice.</p> <p>You shouldn't need to specify the exact filemanager application, though, this should be possible to do through the wm. I know Gnome does, and it's important to do this in KDE since there are two possible file managers (Konqueror/Dolphin) that may be in use.</p> <p>I agree that this would be a good thing for freedesktop.org to standardize, although I doubt it will happen unless someone steps up and volunteers to do it.</p> <p><hr /></p> <p>EDIT: I wasn't aware of xdg-open. Good to know!</p>
0
2008-09-03T16:15:43Z
[ "python", "linux", "cross-platform", "desktop" ]
Standard way to open a folder window in linux?
41,969
<p>I want to open a folder window, in the appropriate file manager, from within a cross-platform (windows/mac/linux) Python application.</p> <p>On OSX, I can open a window in the finder with</p> <pre><code>os.system('open "%s"' % foldername) </code></pre> <p>and on Windows with</p> <pre><code>os.startfile(foldername) </code></pre> <p>What about unix/linux? Is there a standard way to do this or do I have to special case gnome/kde/etc and manually run the appropriate application (nautilus/konqueror/etc)?</p> <p>This looks like something that could be specified by the <a href="http://freedesktop.org">freedesktop.org</a> folks (a python module, similar to <code>webbrowser</code>, would also be nice!).</p>
6
2008-09-03T15:47:23Z
42,046
<pre><code>os.system('xdg-open "%s"' % foldername) </code></pre> <p><code>xdg-open</code> can be used for files/urls also</p>
7
2008-09-03T16:18:25Z
[ "python", "linux", "cross-platform", "desktop" ]
What is a tuple useful for?
42,034
<p>I am learning Python for a class now, and we just covered tuples as one of the data types. I read the Wikipedia page on it, but, I could not figure out where such a data type would be useful in practice. Can I have some examples, perhaps in Python, where an immutable set of numbers would be needed? How is this different from a list?</p>
25
2008-09-03T16:13:06Z
42,048
<ul> <li>Tuples are used whenever you want to return multiple results from a function.</li> <li>Since they're immutable, they can be used as keys for a dictionary (lists can't).</li> </ul>
32
2008-09-03T16:18:53Z
[ "python", "tuples" ]
What is a tuple useful for?
42,034
<p>I am learning Python for a class now, and we just covered tuples as one of the data types. I read the Wikipedia page on it, but, I could not figure out where such a data type would be useful in practice. Can I have some examples, perhaps in Python, where an immutable set of numbers would be needed? How is this different from a list?</p>
25
2008-09-03T16:13:06Z
42,049
<p>I find them useful when you always deal with two or more objects as a set.</p>
2
2008-09-03T16:19:14Z
[ "python", "tuples" ]
What is a tuple useful for?
42,034
<p>I am learning Python for a class now, and we just covered tuples as one of the data types. I read the Wikipedia page on it, but, I could not figure out where such a data type would be useful in practice. Can I have some examples, perhaps in Python, where an immutable set of numbers would be needed? How is this different from a list?</p>
25
2008-09-03T16:13:06Z
42,050
<p>A list can always replace a tuple, with respect to functionality (except, apparently, as keys in a dict). However, a tuple can make things go faster. The same is true for, for example, immutable strings in Java -- when will you ever need to be unable to alter your strings? Never!</p> <p>I just read a decent discussion on limiting what you can do in order to make better programs; <a href="http://weblog.raganwald.com/2007/03/why-why-functional-programming-matters.html" rel="nofollow">Why Why Functional Programming Matters Matters</a></p>
1
2008-09-03T16:20:00Z
[ "python", "tuples" ]
What is a tuple useful for?
42,034
<p>I am learning Python for a class now, and we just covered tuples as one of the data types. I read the Wikipedia page on it, but, I could not figure out where such a data type would be useful in practice. Can I have some examples, perhaps in Python, where an immutable set of numbers would be needed? How is this different from a list?</p>
25
2008-09-03T16:13:06Z
42,052
<p>Tuples make good dictionary keys when you need to combine more than one piece of data into your key and don't feel like making a class for it.</p> <pre><code>a = {} a[(1,2,"bob")] = "hello!" a[("Hello","en-US")] = "Hi There!" </code></pre> <p>I've used this feature primarily to create a dictionary with keys that are coordinates of the vertices of a mesh. However, in my particular case, the exact comparison of the floats involved worked fine which might not always be true for your purposes [in which case I'd probably convert your incoming floats to some kind of fixed-point integer]</p>
14
2008-09-03T16:20:59Z
[ "python", "tuples" ]
What is a tuple useful for?
42,034
<p>I am learning Python for a class now, and we just covered tuples as one of the data types. I read the Wikipedia page on it, but, I could not figure out where such a data type would be useful in practice. Can I have some examples, perhaps in Python, where an immutable set of numbers would be needed? How is this different from a list?</p>
25
2008-09-03T16:13:06Z
42,055
<p>A tuple is useful for storing multiple values.. As you note a tuple is just like a list that is immutable - e.g. once created you cannot add/remove/swap elements.</p> <p>One benefit of being immutable is that because the tuple is fixed size it allows the run-time to perform certain optimizations. This is particularly beneficial when a tupple is used in the context of a return value or a parameter to a function.</p>
1
2008-09-03T16:23:48Z
[ "python", "tuples" ]
What is a tuple useful for?
42,034
<p>I am learning Python for a class now, and we just covered tuples as one of the data types. I read the Wikipedia page on it, but, I could not figure out where such a data type would be useful in practice. Can I have some examples, perhaps in Python, where an immutable set of numbers would be needed? How is this different from a list?</p>
25
2008-09-03T16:13:06Z
42,060
<p>Tuples and lists have the same uses in general. Immutable data types in general have many benefits, mostly about concurrency issues.</p> <p>So, when you have lists that are not volatile in nature and you need to guarantee that no consumer is altering it, you may use a tuple.</p> <p>Typical examples are fixed data in an application like company divisions, categories, etc. If this data change, typically a single producer rebuilts the tuple.</p>
2
2008-09-03T16:25:17Z
[ "python", "tuples" ]
What is a tuple useful for?
42,034
<p>I am learning Python for a class now, and we just covered tuples as one of the data types. I read the Wikipedia page on it, but, I could not figure out where such a data type would be useful in practice. Can I have some examples, perhaps in Python, where an immutable set of numbers would be needed? How is this different from a list?</p>
25
2008-09-03T16:13:06Z
48,414
<p>I like <a href="http://jtauber.com/blog/2006/04/15/python_tuples_are_not_just_constant_lists/">this explanation</a>.</p> <p>Basically, you should use tuples when there's a constant structure (the 1st position always holds one type of value and the second another, and so forth), and lists should be used for lists of homogeneous values.</p> <p>Of course there's always exceptions, but this is a good general guideline.</p>
7
2008-09-07T13:12:28Z
[ "python", "tuples" ]
What is a tuple useful for?
42,034
<p>I am learning Python for a class now, and we just covered tuples as one of the data types. I read the Wikipedia page on it, but, I could not figure out where such a data type would be useful in practice. Can I have some examples, perhaps in Python, where an immutable set of numbers would be needed? How is this different from a list?</p>
25
2008-09-03T16:13:06Z
51,200
<p>In addition to the places where they're syntactically required like the string % operation and for multiple return values, I use tuples as a form of lightweight classes. For example, suppose you have an object that passes out an opaque cookie to a caller from one method which is then passed into another method. A tuple is a good way to pack multiple values into that cookie without having to define a separate class to contain them.</p> <p>I try to be judicious about this particular use, though. If the cookies are used liberally throughout the code, it's better to create a class because it helps document their use. If they are only used in one place (e.g. one pair of methods) then I might use a tuple. In any case, because it's Python you can start with a tuple and then change it to an instance of a custom class without having to change any code in the caller.</p>
0
2008-09-09T03:56:09Z
[ "python", "tuples" ]
What is a tuple useful for?
42,034
<p>I am learning Python for a class now, and we just covered tuples as one of the data types. I read the Wikipedia page on it, but, I could not figure out where such a data type would be useful in practice. Can I have some examples, perhaps in Python, where an immutable set of numbers would be needed? How is this different from a list?</p>
25
2008-09-03T16:13:06Z
39,638,334
<p>A tuple is a sequence of values. The values can be any type, and they are indexed by integer, so tuples are not like lists. The most important difference is that <strong>tuples are immutable.</strong></p> <p>A tuple is a comma-separated list of values:</p> <pre><code>t = 'p', 'q', 'r', 's', 't' </code></pre> <p>it is good practice to enclose tuples in parentheses:</p> <pre><code>t = ('p', 'q', 'r', 's', 't') </code></pre>
0
2016-09-22T11:54:05Z
[ "python", "tuples" ]
Best way to extract text from a Word doc without using COM/automation?
42,482
<p>Is there a reasonable way to extract plain text from a Word file that doesn't depend on COM automation? (This is a a feature for a web app deployed on a non-Windows platform - that's non-negotiable in this case.)</p> <p>Antiword seems like it might be a reasonable option, but it seems like it might be abandoned.</p> <p>A Python solution would be ideal, but doesn't appear to be available.</p>
15
2008-09-03T20:18:47Z
42,485
<p>Open Office has an <a href="http://api.openoffice.org/" rel="nofollow">API</a></p>
2
2008-09-03T20:20:00Z
[ "python", "ms-word" ]
Best way to extract text from a Word doc without using COM/automation?
42,482
<p>Is there a reasonable way to extract plain text from a Word file that doesn't depend on COM automation? (This is a a feature for a web app deployed on a non-Windows platform - that's non-negotiable in this case.)</p> <p>Antiword seems like it might be a reasonable option, but it seems like it might be abandoned.</p> <p>A Python solution would be ideal, but doesn't appear to be available.</p>
15
2008-09-03T20:18:47Z
42,492
<p>If it is Word 2007 docx, you could unzip it and parse the XML files that are contained inside.</p>
0
2008-09-03T20:22:23Z
[ "python", "ms-word" ]
Best way to extract text from a Word doc without using COM/automation?
42,482
<p>Is there a reasonable way to extract plain text from a Word file that doesn't depend on COM automation? (This is a a feature for a web app deployed on a non-Windows platform - that's non-negotiable in this case.)</p> <p>Antiword seems like it might be a reasonable option, but it seems like it might be abandoned.</p> <p>A Python solution would be ideal, but doesn't appear to be available.</p>
15
2008-09-03T20:18:47Z
43,301
<p>Using the OpenOffice API, and Python, and <a href="http://www.pitonyak.org/oo.php" rel="nofollow">Andrew Pitonyak's excellent online macro book</a> I managed to do this. Section 7.16.4 is the place to start.</p> <p>One other tip to make it work without needing the screen at all is to use the Hidden property:</p> <pre><code>RO = PropertyValue('ReadOnly', 0, True, 0) Hidden = PropertyValue('Hidden', 0, True, 0) xDoc = desktop.loadComponentFromURL( docpath,"_blank", 0, (RO, Hidden,) ) </code></pre> <p>Otherwise the document flicks up on the screen (probably on the webserver console) when you open it.</p>
2
2008-09-04T07:45:26Z
[ "python", "ms-word" ]
Best way to extract text from a Word doc without using COM/automation?
42,482
<p>Is there a reasonable way to extract plain text from a Word file that doesn't depend on COM automation? (This is a a feature for a web app deployed on a non-Windows platform - that's non-negotiable in this case.)</p> <p>Antiword seems like it might be a reasonable option, but it seems like it might be abandoned.</p> <p>A Python solution would be ideal, but doesn't appear to be available.</p>
15
2008-09-03T20:18:47Z
43,364
<p>I use catdoc or antiword for this, whatever gives the result that is the easiest to parse. I have embedded this in python functions, so it is easy to use from the parsing system (which is written in python).</p> <pre><code>import os def doc_to_text_catdoc(filename): (fi, fo, fe) = os.popen3('catdoc -w "%s"' % filename) fi.close() retval = fo.read() erroroutput = fe.read() fo.close() fe.close() if not erroroutput: return retval else: raise OSError("Executing the command caused an error: %s" % erroroutput) # similar doc_to_text_antiword() </code></pre> <p>The -w switch to catdoc turns off line wrapping, BTW.</p>
8
2008-09-04T08:52:01Z
[ "python", "ms-word" ]
Best way to extract text from a Word doc without using COM/automation?
42,482
<p>Is there a reasonable way to extract plain text from a Word file that doesn't depend on COM automation? (This is a a feature for a web app deployed on a non-Windows platform - that's non-negotiable in this case.)</p> <p>Antiword seems like it might be a reasonable option, but it seems like it might be abandoned.</p> <p>A Python solution would be ideal, but doesn't appear to be available.</p>
15
2008-09-03T20:18:47Z
1,387,028
<p>For docx files, check out the Python script docx2txt available at</p> <p><a href="http://cobweb.ecn.purdue.edu/~kak/distMisc/docx2txt" rel="nofollow">http://cobweb.ecn.purdue.edu/~kak/distMisc/docx2txt</a></p> <p>for extracting the plain text from a docx document.</p>
1
2009-09-06T23:44:00Z
[ "python", "ms-word" ]
Best way to extract text from a Word doc without using COM/automation?
42,482
<p>Is there a reasonable way to extract plain text from a Word file that doesn't depend on COM automation? (This is a a feature for a web app deployed on a non-Windows platform - that's non-negotiable in this case.)</p> <p>Antiword seems like it might be a reasonable option, but it seems like it might be abandoned.</p> <p>A Python solution would be ideal, but doesn't appear to be available.</p>
15
2008-09-03T20:18:47Z
1,979,931
<p>(Same answer as <a href="http://stackoverflow.com/questions/125222/extracting-text-from-ms-word-files-in-python">extracting text from MS word files in python</a>)</p> <p>Use the native Python docx module which I made this week. Here's how to extract all the text from a doc:</p> <pre><code>document = opendocx('Hello world.docx') # This location is where most document content lives docbody = document.xpath('/w:document/w:body', namespaces=wordnamespaces)[0] # Extract all text print getdocumenttext(document) </code></pre> <p>See <a href="https://python-docx.readthedocs.org/en/latest/">Python DocX site</a></p> <p>100% Python, no COM, no .net, no Java, no parsing serialized XML with regexs, no crap.</p>
14
2009-12-30T12:23:05Z
[ "python", "ms-word" ]
Best way to extract text from a Word doc without using COM/automation?
42,482
<p>Is there a reasonable way to extract plain text from a Word file that doesn't depend on COM automation? (This is a a feature for a web app deployed on a non-Windows platform - that's non-negotiable in this case.)</p> <p>Antiword seems like it might be a reasonable option, but it seems like it might be abandoned.</p> <p>A Python solution would be ideal, but doesn't appear to be available.</p>
15
2008-09-03T20:18:47Z
20,663,596
<p>If all you want to do is extracting text from Word files (.docx), it's possible to do it only with Python. Like Guy Starbuck wrote it, you just need to unzip the file and then parse the XML. Inspired by <code>python-docx</code>, I have written a <a href="http://etienned.github.io/posts/extract-text-from-word-docx-simply/" rel="nofollow">simple function</a> to do this:</p> <pre><code>try: from xml.etree.cElementTree import XML except ImportError: from xml.etree.ElementTree import XML import zipfile """ Module that extract text from MS XML Word document (.docx). (Inspired by python-docx &lt;https://github.com/mikemaccana/python-docx&gt;) """ WORD_NAMESPACE = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}' PARA = WORD_NAMESPACE + 'p' TEXT = WORD_NAMESPACE + 't' def get_docx_text(path): """ Take the path of a docx file as argument, return the text in unicode. """ document = zipfile.ZipFile(path) xml_content = document.read('word/document.xml') document.close() tree = XML(xml_content) paragraphs = [] for paragraph in tree.getiterator(PARA): texts = [node.text for node in paragraph.getiterator(TEXT) if node.text] if texts: paragraphs.append(''.join(texts)) return '\n\n'.join(paragraphs) </code></pre>
1
2013-12-18T16:38:12Z
[ "python", "ms-word" ]
Best way to extract text from a Word doc without using COM/automation?
42,482
<p>Is there a reasonable way to extract plain text from a Word file that doesn't depend on COM automation? (This is a a feature for a web app deployed on a non-Windows platform - that's non-negotiable in this case.)</p> <p>Antiword seems like it might be a reasonable option, but it seems like it might be abandoned.</p> <p>A Python solution would be ideal, but doesn't appear to be available.</p>
15
2008-09-03T20:18:47Z
30,122,626
<p><a href="http://stackoverflow.com/questions/16516044/is-it-possible-to-read-word-files-doc-docx-in-python/30122239#30122239">This worked well</a> for .doc and .odt.</p> <p>It calls openoffice on the command line to convert your file to text, which you can then simply load into python.</p> <p>(It seems to have other format options, though they are not apparenlty documented.)</p>
0
2015-05-08T11:23:19Z
[ "python", "ms-word" ]
Python re.sub MULTILINE caret match
42,581
<p>The Python docs say:</p> <blockquote> <p>re.MULTILINE: When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline)... By default, '^' matches only at the beginning of the string...</p> </blockquote> <p>So what's going on when I get the following unexpected result?</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s = """// The quick brown fox. ... // Jumped over the lazy dog.""" &gt;&gt;&gt; re.sub('^//', '', s, re.MULTILINE) ' The quick brown fox.\n// Jumped over the lazy dog.' </code></pre>
31
2008-09-03T21:00:33Z
42,597
<p>Look at the definition of <a href="http://docs.python.org/library/re.html#re.sub"><code>re.sub</code></a>:</p> <pre><code>sub(pattern, repl, string[, count]) </code></pre> <p>The 4th argument is the count, you are using <code>re.MULTILINE</code> (which is 8) as the count, not as a flag.</p> <p>You have to compile your regex if you wish to use flags.</p> <pre><code>re.sub(re.compile('^//', re.MULTILINE), '', s) </code></pre> <p>A <code>flags</code> argument was added in Python 2.7, so the full definition is now:</p> <pre><code>re.sub(pattern, repl, string[, count, flags]) </code></pre> <p>Which means that:</p> <pre><code>re.sub('^//', '', s, flags=re.MULTILINE) </code></pre> <p>works.</p>
75
2008-09-03T21:08:02Z
[ "python", "regex", "python-2.x" ]
Python re.sub MULTILINE caret match
42,581
<p>The Python docs say:</p> <blockquote> <p>re.MULTILINE: When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline)... By default, '^' matches only at the beginning of the string...</p> </blockquote> <p>So what's going on when I get the following unexpected result?</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s = """// The quick brown fox. ... // Jumped over the lazy dog.""" &gt;&gt;&gt; re.sub('^//', '', s, re.MULTILINE) ' The quick brown fox.\n// Jumped over the lazy dog.' </code></pre>
31
2008-09-03T21:00:33Z
2,517,216
<pre><code>re.sub('(?m)^//', '', s) </code></pre>
6
2010-03-25T16:10:45Z
[ "python", "regex", "python-2.x" ]
Python re.sub MULTILINE caret match
42,581
<p>The Python docs say:</p> <blockquote> <p>re.MULTILINE: When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline)... By default, '^' matches only at the beginning of the string...</p> </blockquote> <p>So what's going on when I get the following unexpected result?</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s = """// The quick brown fox. ... // Jumped over the lazy dog.""" &gt;&gt;&gt; re.sub('^//', '', s, re.MULTILINE) ' The quick brown fox.\n// Jumped over the lazy dog.' </code></pre>
31
2008-09-03T21:00:33Z
7,248,027
<p>The full definition of <a href="http://docs.python.org/library/re.html#re.sub" rel="nofollow"><code>re.sub</code></a> is:</p> <pre><code>re.sub(pattern, repl, string[, count, flags]) </code></pre> <p>Which means that if you tell Python what the parameters are, then you can pass <code>flags</code> without passing <code>count</code>:</p> <pre><code>re.sub('^//', '', s, flags=re.MULTILINE) </code></pre> <p>or, more concisely:</p> <pre><code>re.sub('^//', '', s, flags=re.M) </code></pre>
3
2011-08-30T18:33:24Z
[ "python", "regex", "python-2.x" ]
Get Last Day of the Month in Python
42,950
<p>Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?</p> <p>If the standard library doesn't support that, does the dateutil package support this?</p>
306
2008-09-04T00:54:44Z
42,997
<p>EDIT: See @<a href="#43663">Blair Conrad's answer</a> for a cleaner solution</p> <p><hr /></p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; datetime.date (2000, 2, 1) - datetime.timedelta (days = 1) datetime.date(2000, 1, 31) &gt;&gt;&gt; </code></pre>
43
2008-09-04T01:26:33Z
[ "python", "date" ]
Get Last Day of the Month in Python
42,950
<p>Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?</p> <p>If the standard library doesn't support that, does the dateutil package support this?</p>
306
2008-09-04T00:54:44Z
43,088
<p>EDIT: see my other answer. It has a better implementation than this one, which I leave here just in case someone's interested in seeing how one might "roll your own" calculator.</p> <p>@<a href="#42997">John Millikin</a> gives a good answer, with the added complication of calculating the first day of the next month.</p> <p>The following isn't particularly elegant, but to figure out the last day of the month that any given date lives in, you could try:</p> <pre><code>def last_day_of_month(date): if date.month == 12: return date.replace(day=31) return date.replace(month=date.month+1, day=1) - datetime.timedelta(days=1) &gt;&gt;&gt; last_day_of_month(datetime.date(2002, 1, 17)) datetime.date(2002, 1, 31) &gt;&gt;&gt; last_day_of_month(datetime.date(2002, 12, 9)) datetime.date(2002, 12, 31) &gt;&gt;&gt; last_day_of_month(datetime.date(2008, 2, 14)) datetime.date(2008, 2, 29) </code></pre>
32
2008-09-04T02:25:50Z
[ "python", "date" ]
Get Last Day of the Month in Python
42,950
<p>Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?</p> <p>If the standard library doesn't support that, does the dateutil package support this?</p>
306
2008-09-04T00:54:44Z
43,663
<p>I didn't notice this earlier when I was looking at the <a href="https://docs.python.org/2/library/calendar.html">documentation for the calendar module</a>, but a method called <a href="http://docs.python.org/library/calendar.html#calendar.monthrange">monthrange</a> provides this information:</p> <blockquote> <p><b>monthrange(year, month)</b><br> &nbsp;&nbsp;&nbsp;&nbsp;Returns weekday of first day of the month and number of days in month, for the specified year and month. </p> </blockquote> <pre><code>&gt;&gt;&gt; import calendar &gt;&gt;&gt; calendar.monthrange(2002,1) (1, 31) &gt;&gt;&gt; calendar.monthrange(2008,2) (4, 29) &gt;&gt;&gt; calendar.monthrange(2100,2) (0, 28) </code></pre> <p>so:</p> <pre><code>calendar.monthrange(year, month)[1] </code></pre> <p>seems like the simplest way to go.</p> <p>Just to be clear, <code>monthrange</code> supports leap years as well:</p> <pre><code>&gt;&gt;&gt; from calendar import monthrange &gt;&gt;&gt; monthrange(2012, 2) (2, 29) </code></pre> <p><a href="http://stackoverflow.com/questions/42950/get-last-day-of-the-month-in-python#43088">My previous answer</a> still works, but is clearly suboptimal.</p>
552
2008-09-04T12:44:12Z
[ "python", "date" ]
Get Last Day of the Month in Python
42,950
<p>Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?</p> <p>If the standard library doesn't support that, does the dateutil package support this?</p>
306
2008-09-04T00:54:44Z
356,535
<p>Another solution would be to do something like this: </p> <pre><code>from datetime import datetime def last_day_of_month(year, month): """ Work out the last day of the month """ last_days = [31, 30, 29, 28, 27] for i in last_days: try: end = datetime(year, month, i) except ValueError: continue else: return end.date() return None </code></pre> <p>And use the function like this:</p> <pre><code>&gt;&gt;&gt; &gt;&gt;&gt; last_day_of_month(2008, 2) datetime.date(2008, 2, 29) &gt;&gt;&gt; last_day_of_month(2009, 2) datetime.date(2009, 2, 28) &gt;&gt;&gt; last_day_of_month(2008, 11) datetime.date(2008, 11, 30) &gt;&gt;&gt; last_day_of_month(2008, 12) datetime.date(2008, 12, 31) </code></pre>
10
2008-12-10T15:47:57Z
[ "python", "date" ]
Get Last Day of the Month in Python
42,950
<p>Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?</p> <p>If the standard library doesn't support that, does the dateutil package support this?</p>
306
2008-09-04T00:54:44Z
12,064,327
<p>i have a simple solution: </p> <pre><code>import datetime datetime.date(2012,2, 1).replace(day=1,month=datetime.date(2012,2,1).month+1)-timedelta(days=1) datetime.date(2012, 2, 29) </code></pre>
-6
2012-08-21T23:09:57Z
[ "python", "date" ]
Get Last Day of the Month in Python
42,950
<p>Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?</p> <p>If the standard library doesn't support that, does the dateutil package support this?</p>
306
2008-09-04T00:54:44Z
13,386,470
<p>This does not address the main question, but one nice trick to get the last <em>weekday</em> in a month is to use <code>calendar.monthcalendar</code>, which returns a matrix of dates, organized with Monday as the first column through Sunday as the last.</p> <pre><code># Some random date. some_date = datetime.date(2012, 5, 23) # Get last weekday last_weekday = np.asarray(calendar.monthcalendar(some_date.year, some_date.month))[:,0:-2].ravel().max() print last_weekday 31 </code></pre> <p>The whole <code>[0:-2]</code> thing is to shave off the weekend columns and throw them out. Dates that fall outside of the month are indicated by 0, so the max effectively ignores them.</p> <p>The use of <code>numpy.ravel</code> is not strictly necessary, but I hate relying on the <em>mere convention</em> that <code>numpy.ndarray.max</code> will flatten the array if not told which axis to calculate over.</p>
1
2012-11-14T20:06:26Z
[ "python", "date" ]
Get Last Day of the Month in Python
42,950
<p>Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?</p> <p>If the standard library doesn't support that, does the dateutil package support this?</p>
306
2008-09-04T00:54:44Z
13,565,185
<p>If you don't want to import the <code>calendar</code> module, a simple two-step function can also be:</p> <pre><code>import datetime def last_day_of_month(any_day): next_month = any_day.replace(day=28) + datetime.timedelta(days=4) # this will never fail return next_month - datetime.timedelta(days=next_month.day) </code></pre> <p>Outputs:</p> <pre><code>&gt;&gt;&gt; for month in range(1, 13): ... print last_day_of_month(datetime.date(2012, month, 1)) ... 2012-01-31 2012-02-29 2012-03-31 2012-04-30 2012-05-31 2012-06-30 2012-07-31 2012-08-31 2012-09-30 2012-10-31 2012-11-30 2012-12-31 </code></pre>
37
2012-11-26T12:48:40Z
[ "python", "date" ]
Get Last Day of the Month in Python
42,950
<p>Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?</p> <p>If the standard library doesn't support that, does the dateutil package support this?</p>
306
2008-09-04T00:54:44Z
14,994,380
<p>This is actually pretty easy with <code>dateutil.relativedelta</code> (package python-datetutil for pip). <code>day=31</code> will always always return the last day of the month.</p> <p>Example:</p> <pre><code>from datetime import datetime from dateutil.relativedelta import relativedelta date_in_feb = datetime.datetime(2013, 2, 21) print datetime.datetime(2013, 2, 21) + relativedelta(day=31) # End-of-month &gt;&gt;&gt; datetime.datetime(2013, 2, 28, 0, 0) </code></pre>
14
2013-02-21T04:09:09Z
[ "python", "date" ]
Get Last Day of the Month in Python
42,950
<p>Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?</p> <p>If the standard library doesn't support that, does the dateutil package support this?</p>
306
2008-09-04T00:54:44Z
17,135,571
<pre><code>import datetime now = datetime.datetime.now() start_month = datetime.datetime(now.year, now.month, 1) date_on_next_month = start_month + datetime.timedelta(35) start_next_month = datetime.datetime(date_on_next_month.year, date_on_next_month.month, 1) last_day_month = start_next_month - datetime.timedelta(1) </code></pre>
4
2013-06-16T16:51:42Z
[ "python", "date" ]
Get Last Day of the Month in Python
42,950
<p>Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?</p> <p>If the standard library doesn't support that, does the dateutil package support this?</p>
306
2008-09-04T00:54:44Z
23,383,345
<p>If you wand to make your own small function, this is a good starting point:</p> <pre><code>def eomday(year, month): """returns the number of days in a given month""" days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] d = days_per_month[month - 1] if month == 2 and (year % 4 == 0 and year % 100 != 0 or year % 400 == 0): d = 29 return d </code></pre> <p>For this you have to know the rules for the leap years:</p> <ul> <li>every fourth year</li> <li>with the exception of every 100 year</li> <li>but again every 400 years</li> </ul>
1
2014-04-30T08:33:57Z
[ "python", "date" ]
Get Last Day of the Month in Python
42,950
<p>Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?</p> <p>If the standard library doesn't support that, does the dateutil package support this?</p>
306
2008-09-04T00:54:44Z
23,447,523
<pre><code>from datetime import timedelta (any_day.replace(day=1) + timedelta(days=32)).replace(day=1) - timedelta(days=1) </code></pre>
7
2014-05-03T17:16:58Z
[ "python", "date" ]
Get Last Day of the Month in Python
42,950
<p>Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?</p> <p>If the standard library doesn't support that, does the dateutil package support this?</p>
306
2008-09-04T00:54:44Z
24,929,705
<p>For me it's the simplest way:</p> <pre><code>selected_date = date(some_year, some_month, some_day) if selected_date.month == 12: # December last_day_selected_month = date(selected_date.year, selected_date.month, 31) else: last_day_selected_month = date(selected_date.year, selected_date.month + 1, 1) - timedelta(days=1) </code></pre>
3
2014-07-24T09:16:25Z
[ "python", "date" ]
Get Last Day of the Month in Python
42,950
<p>Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?</p> <p>If the standard library doesn't support that, does the dateutil package support this?</p>
306
2008-09-04T00:54:44Z
27,667,421
<p>Using <code>relativedelta</code> you would get last date of month like this:</p> <pre><code>from dateutil.relativedelta import relativedelta last_date_of_month = datetime(mydate.year,mydate.month,1)+relativedelta(months=1,days=-1) </code></pre> <p>The idea is to get the fist day of month and use <code>relativedelta</code> to go 1 month ahead and 1 day back so you would get the last day of the month you wanted.</p>
3
2014-12-27T12:54:51Z
[ "python", "date" ]
Get Last Day of the Month in Python
42,950
<p>Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?</p> <p>If the standard library doesn't support that, does the dateutil package support this?</p>
306
2008-09-04T00:54:44Z
28,886,669
<pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; import calendar &gt;&gt;&gt; date = datetime.datetime.now() &gt;&gt;&gt; print date 2015-03-06 01:25:14.939574 &gt;&gt;&gt; print date.replace(day = 1) 2015-03-01 01:25:14.939574 &gt;&gt;&gt; print date.replace(day = calendar.monthrange(date.year, date.month)[1]) 2015-03-31 01:25:14.939574 </code></pre>
3
2015-03-05T20:02:18Z
[ "python", "date" ]
Get Last Day of the Month in Python
42,950
<p>Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?</p> <p>If the standard library doesn't support that, does the dateutil package support this?</p>
306
2008-09-04T00:54:44Z
31,618,852
<p>Use pandas!</p> <pre><code>def isMonthEnd(date): return date + pd.offsets.MonthEnd(0) == date isMonthEnd(datetime(1999, 12, 31)) True isMonthEnd(pd.Timestamp('1999-12-31')) True isMonthEnd(pd.Timestamp(1965, 1, 10)) False </code></pre>
0
2015-07-24T19:59:53Z
[ "python", "date" ]
Get Last Day of the Month in Python
42,950
<p>Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?</p> <p>If the standard library doesn't support that, does the dateutil package support this?</p>
306
2008-09-04T00:54:44Z
37,246,666
<pre><code>import calendar from time import gmtime, strftime calendar.monthrange(int(strftime("%Y", gmtime())), int(strftime("%m", gmtime())))[1] </code></pre> <p>Output:<br></p> <pre><code>31 </code></pre> <p><br><br> This will print the last day of whatever the current month is. In this example it was 15th May, 2016. So your output may be different, however the output will be as many days that the current month is. Great if you want to check the last day of the month by running a daily cron job. <p> So: <br></p> <pre><code>import calendar from time import gmtime, strftime lastDay = calendar.monthrange(int(strftime("%Y", gmtime())), int(strftime("%m", gmtime())))[1] today = strftime("%d", gmtime()) lastDay == today </code></pre> <p>Output:<br></p> <pre><code>False </code></pre> <p>Unless it IS the last day of the month.</p>
0
2016-05-16T04:22:18Z
[ "python", "date" ]
Get Last Day of the Month in Python
42,950
<p>Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?</p> <p>If the standard library doesn't support that, does the dateutil package support this?</p>
306
2008-09-04T00:54:44Z
39,141,916
<p>I prefer this way</p> <pre><code>import datetime import calendar date=datetime.datetime.now() month_end_date=datetime.datetime(date.year,date.month,1) + datetime.timedelta(days=calendar.monthrange(date.year,date.month)[1] - 1) </code></pre>
0
2016-08-25T09:48:05Z
[ "python", "date" ]
Get Last Day of the Month in Python
42,950
<p>Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?</p> <p>If the standard library doesn't support that, does the dateutil package support this?</p>
306
2008-09-04T00:54:44Z
39,223,365
<pre><code>from datetime import date, timedelta import calendar last_day = date.today().replace(day=calendar.monthrange(date.today().year, date.today().month)[1]) </code></pre>
0
2016-08-30T09:14:29Z
[ "python", "date" ]
Get Last Day of the Month in Python
42,950
<p>Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?</p> <p>If the standard library doesn't support that, does the dateutil package support this?</p>
306
2008-09-04T00:54:44Z
39,288,092
<p>You can calculate the end date yourself. the simple logic is to subtract a day from the start_date of next month. :) </p> <p>So write a custom method,</p> <pre><code>import datetime def end_date_of_a_month(date): start_date_of_this_month = date.replace(day=1) month = start_date_of_this_month.month year = start_date_of_this_month.year if month == 12: month = 1 year += 1 else: month += 1 next_month_start_date = start_date_of_this_month.replace(month=month, year=year) this_month_end_date = next_month_start_date - datetime.timedelta(days=1) return this_month_end_date </code></pre> <p>Calling, </p> <pre><code>end_date_of_a_month(datetime.datetime.now().date()) </code></pre> <p>It will return the end date of this month. Pass any date to this function. returns you the end date of that month. </p>
1
2016-09-02T08:47:11Z
[ "python", "date" ]
How can I get a commit message from a bzr post-commit hook?
43,099
<p>I'm trying to write a bzr post-commit hook for my private bugtracker, but I'm stuck at the function signature of post_commit(local, master, old_revno, old_revid, new_revno, mew_revid). How can I extract the commit message for the branch from this with bzrlib in Python?</p>
3
2008-09-04T02:34:41Z
43,172
<p>And the answer is like so:</p> <pre><code>def check_commit_msg(local, master, old_revno, old_revid, new_revno, new_revid): branch = local or master revision = branch.repository.get_revision(new_revid) print revision.message </code></pre> <p>local and master are Branch objects, so once you have a revision, it's easy to extract the message.</p>
5
2008-09-04T04:09:00Z
[ "python", "dvcs", "bazaar" ]
How to generate urls in django
43,290
<p>In Django's template language, you can use <code>{% url [viewname] [args] %}</code> to generate a URL to a specific view with parameters. How can you programatically do the same in Python code?</p> <p>What I need is to create a list of menu items where each item has name, URL, and an active flag (whether it's the current page or not). This is because it will be a lot cleaner to do this in Python than the template language.</p>
22
2008-09-04T07:36:39Z
43,312
<p>If you need to use something similar to the <code>{% url %}</code> template tag in your code, Django provides the <code>django.core.urlresolvers.reverse()</code>. The <code>reverse</code> function has the following signature:</p> <pre><code>reverse(viewname, urlconf=None, args=None, kwargs=None) </code></pre> <p><a href="https://docs.djangoproject.com/en/dev/ref/urlresolvers/">https://docs.djangoproject.com/en/dev/ref/urlresolvers/</a></p>
32
2008-09-04T07:54:57Z
[ "python", "django", "url", "django-urls" ]
How to generate urls in django
43,290
<p>In Django's template language, you can use <code>{% url [viewname] [args] %}</code> to generate a URL to a specific view with parameters. How can you programatically do the same in Python code?</p> <p>What I need is to create a list of menu items where each item has name, URL, and an active flag (whether it's the current page or not). This is because it will be a lot cleaner to do this in Python than the template language.</p>
22
2008-09-04T07:36:39Z
55,734
<p>I'm using two different approaches in my <code>models.py</code>. The first is the <code>permalink</code> decorator:</p> <pre><code>from django.db.models import permalink def get_absolute_url(self): """Construct the absolute URL for this Item.""" return ('project.app.views.view_name', [str(self.id)]) get_absolute_url = permalink(get_absolute_url) </code></pre> <p>You can also call <code>reverse</code> directly:</p> <pre><code>from django.core.urlresolvers import reverse def get_absolute_url(self): """Construct the absolute URL for this Item.""" return reverse('project.app.views.view_name', None, [str(self.id)]) </code></pre>
8
2008-09-11T03:05:27Z
[ "python", "django", "url", "django-urls" ]
How to generate urls in django
43,290
<p>In Django's template language, you can use <code>{% url [viewname] [args] %}</code> to generate a URL to a specific view with parameters. How can you programatically do the same in Python code?</p> <p>What I need is to create a list of menu items where each item has name, URL, and an active flag (whether it's the current page or not). This is because it will be a lot cleaner to do this in Python than the template language.</p>
22
2008-09-04T07:36:39Z
72,249
<p>Be aware that using <code>reverse()</code> requires that your urlconf module is 100% error free and can be processed - iow no <code>ViewDoesNotExist</code> errors or so, or you get the dreaded <code>NoReverseMatch</code> exception (errors in templates usually fail silently resulting in <code>None</code>).</p>
4
2008-09-16T13:36:56Z
[ "python", "django", "url", "django-urls" ]
Can I write native iPhone apps using Python
43,315
<p>Using <a href="http://pyobjc.sourceforge.net/">PyObjC</a>, you can use Python to write Cocoa applications for OS X. Can I write native iPhone apps using Python and if so, how?</p>
78
2008-09-04T07:59:57Z
43,331
<p>Not currently, currently the only languages available to access the iPhone SDK are C/C++, Objective C and Swift.</p> <p>There is no technical reason why this could not change in the future but I wouldn't hold your breath for this happening in the short term.</p> <p>That said, Objective-C and Swift really are not too scary...</p> <blockquote> <h1>2016 edit</h1> <p>Javascript with NativeScript framework is available to use now.</p> </blockquote>
32
2008-09-04T08:21:31Z
[ "iphone", "python", "cocoa-touch" ]
Can I write native iPhone apps using Python
43,315
<p>Using <a href="http://pyobjc.sourceforge.net/">PyObjC</a>, you can use Python to write Cocoa applications for OS X. Can I write native iPhone apps using Python and if so, how?</p>
78
2008-09-04T07:59:57Z
43,358
<p>You can use PyObjC on the iPhone as well, due to the excellent work by Jay Freeman (saurik). See <a href="http://www.saurik.com/id/5">iPhone Applications in Python</a>.</p> <p>Note that this requires a jailbroken iPhone at the moment.</p>
51
2008-09-04T08:44:11Z
[ "iphone", "python", "cocoa-touch" ]
Can I write native iPhone apps using Python
43,315
<p>Using <a href="http://pyobjc.sourceforge.net/">PyObjC</a>, you can use Python to write Cocoa applications for OS X. Can I write native iPhone apps using Python and if so, how?</p>
78
2008-09-04T07:59:57Z
145,071
<p>The iPhone SDK agreement is also rather vague about whether you're even allowed to run scripting languages (outside of a WebView's Javascript). My reading is that it is OK - as long as none of the scripts you execute are downloaded from the network (so pre-installed and user-edited scripts seem to be OK).</p> <p>IANAL etc etc.</p>
5
2008-09-28T02:51:14Z
[ "iphone", "python", "cocoa-touch" ]
Can I write native iPhone apps using Python
43,315
<p>Using <a href="http://pyobjc.sourceforge.net/">PyObjC</a>, you can use Python to write Cocoa applications for OS X. Can I write native iPhone apps using Python and if so, how?</p>
78
2008-09-04T07:59:57Z
739,098
<p>You can do this with PyObjC, with a jailbroken phone of course. But if you want to get it into the App Store, they will not allow it because it "interprets code." However, you may be able to use <a href="http://code.google.com/p/shedskin/" rel="nofollow">Shed Skin</a>, although I'm not aware of anyone doing this. I can't think of any good reason to do this though, as you lose dynamic typing, and might as well use ObjC.</p>
1
2009-04-10T22:49:09Z
[ "iphone", "python", "cocoa-touch" ]
Can I write native iPhone apps using Python
43,315
<p>Using <a href="http://pyobjc.sourceforge.net/">PyObjC</a>, you can use Python to write Cocoa applications for OS X. Can I write native iPhone apps using Python and if so, how?</p>
78
2008-09-04T07:59:57Z
2,005,197
<p>The only significant "external" language for iPhone development that I'm aware of with semi-significant support in terms of frameworks and compatibility is <a href="http://monotouch.net/" rel="nofollow">MonoTouch</a>, a C#/.NET environment for developing on the iPhone.</p>
0
2010-01-05T09:56:51Z
[ "iphone", "python", "cocoa-touch" ]
Can I write native iPhone apps using Python
43,315
<p>Using <a href="http://pyobjc.sourceforge.net/">PyObjC</a>, you can use Python to write Cocoa applications for OS X. Can I write native iPhone apps using Python and if so, how?</p>
78
2008-09-04T07:59:57Z
2,167,033
<p>Yes you can. You write your code in tinypy (which is restricted Python), then use tinypy to convert it to C++, and finally compile this with XCode into a native iPhone app. Phil Hassey has published a game called Elephants! using this approach. Here are more details,</p> <p><a href="http://www.philhassey.com/blog/2009/12/23/elephants-is-free-on-the-app-store/">http://www.philhassey.com/blog/2009/12/23/elephants-is-free-on-the-app-store/</a></p>
22
2010-01-30T06:03:39Z
[ "iphone", "python", "cocoa-touch" ]
Can I write native iPhone apps using Python
43,315
<p>Using <a href="http://pyobjc.sourceforge.net/">PyObjC</a>, you can use Python to write Cocoa applications for OS X. Can I write native iPhone apps using Python and if so, how?</p>
78
2008-09-04T07:59:57Z
2,637,228
<p>An update to the iOS Developer Agreement means that you can use whatever you like, as long as you meet the developer guidelines. Section 3.3.1, which restricted what developers could use for iOS development, has been entirely removed.</p> <p>Source: <a href="http://daringfireball.net/2010/09/app_store_guidelines">http://daringfireball.net/2010/09/app_store_guidelines</a></p>
20
2010-04-14T12:18:15Z
[ "iphone", "python", "cocoa-touch" ]
Can I write native iPhone apps using Python
43,315
<p>Using <a href="http://pyobjc.sourceforge.net/">PyObjC</a>, you can use Python to write Cocoa applications for OS X. Can I write native iPhone apps using Python and if so, how?</p>
78
2008-09-04T07:59:57Z
2,768,536
<p>Technically, as long as the interpreted code ISN'T downloaded (excluding JavaScript), the app may be approved. Rhomobiles "Rhodes" framework does just that, bundling mobile Ruby, a lightweight version of Rails, and your app for distribution via the app-store. Because both the interpreter and the interpreted code are packaged into the final application - Apple doesn't find it objectionable. </p> <p><a href="http://rhomobile.com/products/rhodes/" rel="nofollow">http://rhomobile.com/products/rhodes/</a></p> <p>Even after the latest apple press release - rhodes apps (mobile ruby) are still viable on the app-store. I'd find it hard to believe that tinyPy or pyObjC wouldn't find a place if there is a willing developer community.</p>
2
2010-05-04T19:54:20Z
[ "iphone", "python", "cocoa-touch" ]
Can I write native iPhone apps using Python
43,315
<p>Using <a href="http://pyobjc.sourceforge.net/">PyObjC</a>, you can use Python to write Cocoa applications for OS X. Can I write native iPhone apps using Python and if so, how?</p>
78
2008-09-04T07:59:57Z
3,684,714
<p>It seems this is now something developers are allowed to do: the iOS Developer Agreement was changed yesterday and appears to have been ammended in a such a way as to make embedding a Python interpretter in your application legal:</p> <p><strong>SECTION 3.3.2 — INTERPRETERS</strong></p> <p><strong>Old:</strong></p> <blockquote> <p>3.3.2 An Application may not itself install or launch other executable code by any means, including without limitation through the use of a plug-in architecture, calling other frameworks, other APIs or otherwise. Unless otherwise approved by Apple in writing, no interpreted code may be downloaded or used in an Application except for code that is interpreted and run by Apple’s Documented APIs and built-in interpreter(s). Notwithstanding the foregoing, with Apple’s prior written consent, an Application may use embedded interpreted code in a limited way if such use is solely for providing minor features or functionality that are consistent with the intended and advertised purpose of the Application.</p> </blockquote> <p><strong>New:</strong></p> <blockquote> <p>3.3.2 An Application may not download or install executable code. Interpreted code may only be used in an Application if all scripts, code and interpreters are packaged in the Application and not downloaded. The only exception to the foregoing is scripts and code downloaded and run by Apple’s built-in WebKit framework.</p> </blockquote>
21
2010-09-10T12:48:14Z
[ "iphone", "python", "cocoa-touch" ]
Can I write native iPhone apps using Python
43,315
<p>Using <a href="http://pyobjc.sourceforge.net/">PyObjC</a>, you can use Python to write Cocoa applications for OS X. Can I write native iPhone apps using Python and if so, how?</p>
78
2008-09-04T07:59:57Z
11,069,342
<p>I think it was not possible earlier but I recently heard about PyMob, which seems interesting because the apps are written in Python and the final outputs are native source codes in various platforms (Obj-C for iOS, Java for Android etc). This is certainly quite unique. <a href="http://pyzia.com/technology.html" rel="nofollow">This</a> webpage explains it in more detail.</p> <p>I haven't given it a shot yet, but will take a look soon.</p>
1
2012-06-17T06:20:58Z
[ "iphone", "python", "cocoa-touch" ]
Can I write native iPhone apps using Python
43,315
<p>Using <a href="http://pyobjc.sourceforge.net/">PyObjC</a>, you can use Python to write Cocoa applications for OS X. Can I write native iPhone apps using Python and if so, how?</p>
78
2008-09-04T07:59:57Z
11,448,458
<p>Yes, nowadays you can develop apps for iOS in Python. </p> <p>There are two frameworks that you may want to checkout: <a href="http://kivy.org/">Kivy</a> and <a href="http://pyzia.com/technology.html">PyMob</a>.</p> <p>Please consider the answers to <a href="http://stackoverflow.com/questions/10664196/is-it-possible-to-use-python-to-write-cross-platform-apps-for-both-ios-and-andro">this question</a> too, as they are more up-to-date than this one.</p>
15
2012-07-12T09:07:42Z
[ "iphone", "python", "cocoa-touch" ]
Can I write native iPhone apps using Python
43,315
<p>Using <a href="http://pyobjc.sourceforge.net/">PyObjC</a>, you can use Python to write Cocoa applications for OS X. Can I write native iPhone apps using Python and if so, how?</p>
78
2008-09-04T07:59:57Z
18,601,032
<p><a href="http://omz-software.com/pythonista">Pythonista</a> has an Export to Xcode feature that allows you to export your Python scripts as Xcode projects that build standalone iOS apps.</p>
6
2013-09-03T20:36:35Z
[ "iphone", "python", "cocoa-touch" ]
A python web application framework for tight DB/GUI coupling?
43,368
<p>I'm a firm believer of the heretic thought of tight coupling between the backend and frontend: I want existing, implied knowledge about a backend to be automatically made use of when generating user interfaces. E.g., if a VARCHAR column has a maximum with of 20 characters, there GUIs should automatically constrain the user from typing more than 20 characters in a related form field.</p> <p>And I have strong antipathy to ORMs which want to define my database tables, or are based on some hack where every table needs to have extra numeric ID columns because of the ORM.</p> <p>I've looked a bit into Python database frameworks and I think I can conclude the SQLAlchemy fits best to my mentality.</p> <p>Now, I need to find a web application framework which fits naturally with SQLAlchemy (or an equivalent) and perhaps even with my appetite for coupling. With "web application framework", I mean products/project such as Pyhons, Django, TurboGears, web2py, etc.</p> <p>E.g., it should ideally be able to:</p> <ul> <li><strong>automatically select a suitable form widget</strong> for data entering a given column if told to do so; e.g., if the column has a foreign key to a column with 10 different values, widget should display the 10 possible values as a dropdown</li> <li><strong>auto-generate javascript form validation code</strong> which gives the end-user quick error feedback if a string is entered into a field which is about to end up in an INTEGER column, etc</li> <li>auto-generate a <strong>calendar widget</strong> for data which will end up in a DATE column</li> <li><strong>hint NOT NULL constraints</strong> as javascript which complains about empty or whitespace-only data in a related input field</li> <li>generate javascript validation code which matches relevant (simple) <strong>CHECK-constraints</strong></li> <li>make it easy to <strong>avoid SQL injection</strong>, by using prepared statements and/or validation of externally derived data</li> <li>make it easy to <strong>avoid cross site scripting</strong> by automatically escape outgoing strings when appropriate</li> <li><strong>make use of constraint names</strong> to generate somewhat user friendly error messages in case a constrataint is violated</li> </ul> <p>All this should happen dynamically, so table adjustments are automatically reflected on the frontend - probably with a caching mechanism, so that all the model introspection wouldn't kill performance. In other words, I don't want to repeat my model definition in an XML file (or alike) when it has already been carefully been defined in my database.</p> <p>Does such a framework exist for Python (or for any language, for that matter)? If not: Which of the several Python web application frameworks will be least in the way if I were to add parts of the above features myself?</p>
11
2008-09-04T08:53:58Z
43,386
<p>You should have a look at django and especially its <a href="http://www.djangoproject.com/documentation/forms/" rel="nofollow">newforms</a> and <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#ref-contrib-admin" rel="nofollow">admin</a> modules. The newforms module provides a nice possibility to do server side validation with automated generation of error messages/pages for the user. Adding ajax validation is also <a href="http://lukeplant.me.uk/blog.php?id=1107301681" rel="nofollow">possible</a> </p>
3
2008-09-04T09:12:27Z
[ "python", "sql", "metadata", "coupling", "data-driven" ]
A python web application framework for tight DB/GUI coupling?
43,368
<p>I'm a firm believer of the heretic thought of tight coupling between the backend and frontend: I want existing, implied knowledge about a backend to be automatically made use of when generating user interfaces. E.g., if a VARCHAR column has a maximum with of 20 characters, there GUIs should automatically constrain the user from typing more than 20 characters in a related form field.</p> <p>And I have strong antipathy to ORMs which want to define my database tables, or are based on some hack where every table needs to have extra numeric ID columns because of the ORM.</p> <p>I've looked a bit into Python database frameworks and I think I can conclude the SQLAlchemy fits best to my mentality.</p> <p>Now, I need to find a web application framework which fits naturally with SQLAlchemy (or an equivalent) and perhaps even with my appetite for coupling. With "web application framework", I mean products/project such as Pyhons, Django, TurboGears, web2py, etc.</p> <p>E.g., it should ideally be able to:</p> <ul> <li><strong>automatically select a suitable form widget</strong> for data entering a given column if told to do so; e.g., if the column has a foreign key to a column with 10 different values, widget should display the 10 possible values as a dropdown</li> <li><strong>auto-generate javascript form validation code</strong> which gives the end-user quick error feedback if a string is entered into a field which is about to end up in an INTEGER column, etc</li> <li>auto-generate a <strong>calendar widget</strong> for data which will end up in a DATE column</li> <li><strong>hint NOT NULL constraints</strong> as javascript which complains about empty or whitespace-only data in a related input field</li> <li>generate javascript validation code which matches relevant (simple) <strong>CHECK-constraints</strong></li> <li>make it easy to <strong>avoid SQL injection</strong>, by using prepared statements and/or validation of externally derived data</li> <li>make it easy to <strong>avoid cross site scripting</strong> by automatically escape outgoing strings when appropriate</li> <li><strong>make use of constraint names</strong> to generate somewhat user friendly error messages in case a constrataint is violated</li> </ul> <p>All this should happen dynamically, so table adjustments are automatically reflected on the frontend - probably with a caching mechanism, so that all the model introspection wouldn't kill performance. In other words, I don't want to repeat my model definition in an XML file (or alike) when it has already been carefully been defined in my database.</p> <p>Does such a framework exist for Python (or for any language, for that matter)? If not: Which of the several Python web application frameworks will be least in the way if I were to add parts of the above features myself?</p>
11
2008-09-04T08:53:58Z
43,414
<p>I believe that Django models does not support composite primary keys (see <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#automatic-primary-key-fields" rel="nofollow">documentation</a>). But perhaps you can use SQLAlchemy in Django? A <a href="http://www.google.com/search?q=sqlalchemy+django" rel="nofollow">google search</a> indicates that you can. I have not used Django, so I don't know.</p> <p>I suggest you take a look at:</p> <ul> <li><a href="http://toscawidgets.org/" rel="nofollow">ToscaWidgets</a></li> <li><a href="http://code.google.com/p/dbsprockets/" rel="nofollow">DBSprockets</a>, including <a href="http://code.google.com/p/dbsprockets/wiki/DBMechanic" rel="nofollow">DBMechanic</a></li> <li><a href="http://www.checkandshare.com/catwalk/" rel="nofollow">Catwalk</a>. Catwalk is an application for TurboGears 1.0 that uses SQLObject, not SQLAlchemy. Also check out this <a href="http://www.checkandshare.com/blog/?p=41" rel="nofollow">blog post</a> and <a href="http://www.checkandshare.com/CATWALK2/lview/index.html" rel="nofollow">screencast</a>.</li> <li><a href="http://docs.turbogears.org/1.0/DataController" rel="nofollow">FastData</a>. Also uses SQLObject.</li> <li><a href="http://code.google.com/p/formalchemy/" rel="nofollow">formalchemy</a></li> <li><a href="http://rumdemo.toscawidgets.org/" rel="nofollow">Rum</a></li> </ul> <p>I do not have any deep knowledge of any of the projects above. I am just in the process of trying to add something similar to one of my own applications as what the original question mentions. The above list is simply a list of interesting projects that I have stumbled across.</p> <p>As to web application frameworks for Python, I recommend TurboGears 2. Not that I have any experience with any of the other frameworks, I just like TurboGears...</p> <p>If the original question's author finds a solution that works well, please update or answer this thread.</p>
1
2008-09-04T09:42:10Z
[ "python", "sql", "metadata", "coupling", "data-driven" ]
A python web application framework for tight DB/GUI coupling?
43,368
<p>I'm a firm believer of the heretic thought of tight coupling between the backend and frontend: I want existing, implied knowledge about a backend to be automatically made use of when generating user interfaces. E.g., if a VARCHAR column has a maximum with of 20 characters, there GUIs should automatically constrain the user from typing more than 20 characters in a related form field.</p> <p>And I have strong antipathy to ORMs which want to define my database tables, or are based on some hack where every table needs to have extra numeric ID columns because of the ORM.</p> <p>I've looked a bit into Python database frameworks and I think I can conclude the SQLAlchemy fits best to my mentality.</p> <p>Now, I need to find a web application framework which fits naturally with SQLAlchemy (or an equivalent) and perhaps even with my appetite for coupling. With "web application framework", I mean products/project such as Pyhons, Django, TurboGears, web2py, etc.</p> <p>E.g., it should ideally be able to:</p> <ul> <li><strong>automatically select a suitable form widget</strong> for data entering a given column if told to do so; e.g., if the column has a foreign key to a column with 10 different values, widget should display the 10 possible values as a dropdown</li> <li><strong>auto-generate javascript form validation code</strong> which gives the end-user quick error feedback if a string is entered into a field which is about to end up in an INTEGER column, etc</li> <li>auto-generate a <strong>calendar widget</strong> for data which will end up in a DATE column</li> <li><strong>hint NOT NULL constraints</strong> as javascript which complains about empty or whitespace-only data in a related input field</li> <li>generate javascript validation code which matches relevant (simple) <strong>CHECK-constraints</strong></li> <li>make it easy to <strong>avoid SQL injection</strong>, by using prepared statements and/or validation of externally derived data</li> <li>make it easy to <strong>avoid cross site scripting</strong> by automatically escape outgoing strings when appropriate</li> <li><strong>make use of constraint names</strong> to generate somewhat user friendly error messages in case a constrataint is violated</li> </ul> <p>All this should happen dynamically, so table adjustments are automatically reflected on the frontend - probably with a caching mechanism, so that all the model introspection wouldn't kill performance. In other words, I don't want to repeat my model definition in an XML file (or alike) when it has already been carefully been defined in my database.</p> <p>Does such a framework exist for Python (or for any language, for that matter)? If not: Which of the several Python web application frameworks will be least in the way if I were to add parts of the above features myself?</p>
11
2008-09-04T08:53:58Z
48,284
<p><a href="http://www.turbogears.org/" rel="nofollow">TurboGears</a> currently uses <a href="http://www.sqlobject.org/" rel="nofollow">SQLObject</a> by default but you can use it with <a href="http://docs.turbogears.org/1.0/SQLAlchemy" rel="nofollow">SQLAlchemy</a>. They are saying that the next major release of TurboGears (1.1) will use SQLAlchemy by default.</p>
1
2008-09-07T10:03:48Z
[ "python", "sql", "metadata", "coupling", "data-driven" ]
A python web application framework for tight DB/GUI coupling?
43,368
<p>I'm a firm believer of the heretic thought of tight coupling between the backend and frontend: I want existing, implied knowledge about a backend to be automatically made use of when generating user interfaces. E.g., if a VARCHAR column has a maximum with of 20 characters, there GUIs should automatically constrain the user from typing more than 20 characters in a related form field.</p> <p>And I have strong antipathy to ORMs which want to define my database tables, or are based on some hack where every table needs to have extra numeric ID columns because of the ORM.</p> <p>I've looked a bit into Python database frameworks and I think I can conclude the SQLAlchemy fits best to my mentality.</p> <p>Now, I need to find a web application framework which fits naturally with SQLAlchemy (or an equivalent) and perhaps even with my appetite for coupling. With "web application framework", I mean products/project such as Pyhons, Django, TurboGears, web2py, etc.</p> <p>E.g., it should ideally be able to:</p> <ul> <li><strong>automatically select a suitable form widget</strong> for data entering a given column if told to do so; e.g., if the column has a foreign key to a column with 10 different values, widget should display the 10 possible values as a dropdown</li> <li><strong>auto-generate javascript form validation code</strong> which gives the end-user quick error feedback if a string is entered into a field which is about to end up in an INTEGER column, etc</li> <li>auto-generate a <strong>calendar widget</strong> for data which will end up in a DATE column</li> <li><strong>hint NOT NULL constraints</strong> as javascript which complains about empty or whitespace-only data in a related input field</li> <li>generate javascript validation code which matches relevant (simple) <strong>CHECK-constraints</strong></li> <li>make it easy to <strong>avoid SQL injection</strong>, by using prepared statements and/or validation of externally derived data</li> <li>make it easy to <strong>avoid cross site scripting</strong> by automatically escape outgoing strings when appropriate</li> <li><strong>make use of constraint names</strong> to generate somewhat user friendly error messages in case a constrataint is violated</li> </ul> <p>All this should happen dynamically, so table adjustments are automatically reflected on the frontend - probably with a caching mechanism, so that all the model introspection wouldn't kill performance. In other words, I don't want to repeat my model definition in an XML file (or alike) when it has already been carefully been defined in my database.</p> <p>Does such a framework exist for Python (or for any language, for that matter)? If not: Which of the several Python web application frameworks will be least in the way if I were to add parts of the above features myself?</p>
11
2008-09-04T08:53:58Z
48,479
<p>I know that you specificity ask for a framework but I thought I would let you know about what I get up to here. I have just undergone converting my company's web application from a custom in-house ORM layer into sqlAlchemy so I am far from an expert but something that occurred to me was that sqlAlchemy has types for all of the attributes it maps from the database so why not use that to help output the right html onto the page. So we use sqlAlchemy for the back end and Cheetah templates for the front end but everything in between is basically our own still.</p> <p>We have never managed to find a framework that does exactly what we want without compromise and prefer to get all the bits that work right for us and write the glue our selves. </p> <p>Step 1. For each data type sqlAlchemy.types.INTEGER etc. Add an extra function toHtml (or many maybe toHTMLReadOnly, toHTMLAdminEdit whatever) and just have that return the template for the html, now you don't even have to care what data type your displaying if you just want to spit out a whole table you can just do (as a cheetah template or what ever your templating engine is).</p> <p>Step 2</p> <p><code>&lt;table&gt;</code></p> <p><code> &lt;tr&gt;</code></p> <p><code> #for $field in $dbObject.c:</code></p> <p><code> &lt;th&gt;$field.name&lt;/th&gt;</code></p> <p><code> #end for </code></p> <p><code> &lt;/tr&gt; </code></p> <p><code> &lt;tr&gt;</code></p> <p><code> #for $field in dbObject.c:</code></p> <p><code> &lt;td&gt;$field.type.toHtml($field.name, $field.value)&lt;/td&gt;</code></p> <p><code> #end for </code></p> <p><code> &lt;/tr&gt;</code></p> <p><code>&lt;/table&gt;</code></p> <p>Using this basic method and stretching pythons introspection to its potential, in an afternoon I managed to make create read update and delete code for our whole admin section of out database, not yet with the polish of django but more then good enough for my needs.</p> <p>Step 3 Discovered the need for a third step just on Friday, wanted to upload files which as you know needs more then just the varchar data types default text box. No sweat, I just overrode the rows class in my table definition from VARCHAR to FilePath(VARCHAR) where the only difference was FilePath had a different toHtml method. Worked flawlessly.</p> <p>All that said, if there is a shrink wrapped one out there that does just what you want, use that.</p> <p>Disclaimer: This code was written from memory after midnight and probably wont produce a functioning web page.</p>
1
2008-09-07T14:39:14Z
[ "python", "sql", "metadata", "coupling", "data-driven" ]
A python web application framework for tight DB/GUI coupling?
43,368
<p>I'm a firm believer of the heretic thought of tight coupling between the backend and frontend: I want existing, implied knowledge about a backend to be automatically made use of when generating user interfaces. E.g., if a VARCHAR column has a maximum with of 20 characters, there GUIs should automatically constrain the user from typing more than 20 characters in a related form field.</p> <p>And I have strong antipathy to ORMs which want to define my database tables, or are based on some hack where every table needs to have extra numeric ID columns because of the ORM.</p> <p>I've looked a bit into Python database frameworks and I think I can conclude the SQLAlchemy fits best to my mentality.</p> <p>Now, I need to find a web application framework which fits naturally with SQLAlchemy (or an equivalent) and perhaps even with my appetite for coupling. With "web application framework", I mean products/project such as Pyhons, Django, TurboGears, web2py, etc.</p> <p>E.g., it should ideally be able to:</p> <ul> <li><strong>automatically select a suitable form widget</strong> for data entering a given column if told to do so; e.g., if the column has a foreign key to a column with 10 different values, widget should display the 10 possible values as a dropdown</li> <li><strong>auto-generate javascript form validation code</strong> which gives the end-user quick error feedback if a string is entered into a field which is about to end up in an INTEGER column, etc</li> <li>auto-generate a <strong>calendar widget</strong> for data which will end up in a DATE column</li> <li><strong>hint NOT NULL constraints</strong> as javascript which complains about empty or whitespace-only data in a related input field</li> <li>generate javascript validation code which matches relevant (simple) <strong>CHECK-constraints</strong></li> <li>make it easy to <strong>avoid SQL injection</strong>, by using prepared statements and/or validation of externally derived data</li> <li>make it easy to <strong>avoid cross site scripting</strong> by automatically escape outgoing strings when appropriate</li> <li><strong>make use of constraint names</strong> to generate somewhat user friendly error messages in case a constrataint is violated</li> </ul> <p>All this should happen dynamically, so table adjustments are automatically reflected on the frontend - probably with a caching mechanism, so that all the model introspection wouldn't kill performance. In other words, I don't want to repeat my model definition in an XML file (or alike) when it has already been carefully been defined in my database.</p> <p>Does such a framework exist for Python (or for any language, for that matter)? If not: Which of the several Python web application frameworks will be least in the way if I were to add parts of the above features myself?</p>
11
2008-09-04T08:53:58Z
198,348
<p>web2py does most of what you ask:</p> <p>Based on a field type and its validators it will render the field with the appropriate widget. You can override with</p> <pre><code>db.table.field.widget=... </code></pre> <p>and use a third party widget.</p> <p>web2py has js to blocks the user from entering a non-integer in a integer field or a non-double in a double field. time, date and datetime fields have their own pickers. These js validation work with (not instead) of server side validation.</p> <p>There is <code>IS_EMPTY_OR(...)</code> validator.</p> <p>The DAL prevents SQL injections since everthing is escaped when goes in the DB.</p> <p>web2py prevents XSS because in {{=variable}}, 'variable' is escaped unless specified otherwise {{=XML(variable)}} or {{=XML(variable,sanitize=True)}}</p> <p>Error messages are arguments of validators for example</p> <pre><code>db.table.field.requires=IS_NOT_EMPTY(error_message=T('hey! write something in here')) </code></pre> <p>T is for internationalization.</p>
5
2008-10-13T17:31:38Z
[ "python", "sql", "metadata", "coupling", "data-driven" ]
How to find the mime type of a file in python?
43,580
<p>Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer.</p> <p>Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in the HTTP response.</p> <p>Based on that assumption, in addition to the bytes of the file, you also want to save the MIME type.</p> <p>How would you find the MIME type of a file? I'm currently on a Mac, but this should also work on Windows. </p> <p>Does the browser add this information when posting the file to the web page?</p> <p>Is there a neat python library for finding this information? A WebService or (even better) a downloadable database?</p>
101
2008-09-04T12:07:27Z
43,588
<p>The <a href="https://docs.python.org/library/mimetypes.html">mimetypes module</a> in the standard library will determine/guess the MIME type from a file extension.</p> <p>If users are uploading files the HTTP post will contain the MIME type of the file alongside the data. For example, Django makes this data available as an attribute of the <a href="https://docs.djangoproject.com/en/dev/topics/http/file-uploads/#uploadedfile-objects">UploadedFile</a> object.</p>
53
2008-09-04T12:12:20Z
[ "python", "mime" ]
How to find the mime type of a file in python?
43,580
<p>Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer.</p> <p>Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in the HTTP response.</p> <p>Based on that assumption, in addition to the bytes of the file, you also want to save the MIME type.</p> <p>How would you find the MIME type of a file? I'm currently on a Mac, but this should also work on Windows. </p> <p>Does the browser add this information when posting the file to the web page?</p> <p>Is there a neat python library for finding this information? A WebService or (even better) a downloadable database?</p>
101
2008-09-04T12:07:27Z
43,616
<p>You didn't state what web server you were using, but Apache has a nice little module called <a href="http://httpd.apache.org/docs/1.3/mod/mod_mime_magic.html" rel="nofollow">Mime Magic</a> which it uses to determine the type of a file when told to do so. It reads some of the file's content and tries to figure out what type it is based on the characters found. And as <a href="http://stackoverflow.com/questions/43580/how-to-find-the-mime-type-of-a-file-in-python#43588" rel="nofollow">Dave Webb Mentioned</a> the <a href="http://docs.python.org/lib/module-mimetypes.html" rel="nofollow">MimeTypes Module</a> under python will work, provided an extension is handy.</p> <p>Alternatively, if you are sitting on a UNIX box you can use <code>sys.popen('file -i ' + fileName, mode='r')</code> to grab the MIME type. Windows should have an equivalent command, but I'm unsure as to what it is. </p>
5
2008-09-04T12:22:55Z
[ "python", "mime" ]
How to find the mime type of a file in python?
43,580
<p>Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer.</p> <p>Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in the HTTP response.</p> <p>Based on that assumption, in addition to the bytes of the file, you also want to save the MIME type.</p> <p>How would you find the MIME type of a file? I'm currently on a Mac, but this should also work on Windows. </p> <p>Does the browser add this information when posting the file to the web page?</p> <p>Is there a neat python library for finding this information? A WebService or (even better) a downloadable database?</p>
101
2008-09-04T12:07:27Z
1,662,074
<p>in python 2.6:</p> <pre><code>mime = subprocess.Popen("/usr/bin/file --mime PATH", shell=True, \ stdout=subprocess.PIPE).communicate()[0] </code></pre>
8
2009-11-02T15:48:09Z
[ "python", "mime" ]
How to find the mime type of a file in python?
43,580
<p>Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer.</p> <p>Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in the HTTP response.</p> <p>Based on that assumption, in addition to the bytes of the file, you also want to save the MIME type.</p> <p>How would you find the MIME type of a file? I'm currently on a Mac, but this should also work on Windows. </p> <p>Does the browser add this information when posting the file to the web page?</p> <p>Is there a neat python library for finding this information? A WebService or (even better) a downloadable database?</p>
101
2008-09-04T12:07:27Z
2,133,843
<p>More reliable way than to use the mimetypes library would be to use the python-magic package.</p> <pre><code>import magic m = magic.open(magic.MAGIC_MIME) m.load() m.file("/tmp/document.pdf") </code></pre> <p>This would be equivalent to using file(1).</p> <p>On Django one could also make sure that the MIME type matches that of UploadedFile.content_type.</p>
39
2010-01-25T16:39:06Z
[ "python", "mime" ]
How to find the mime type of a file in python?
43,580
<p>Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer.</p> <p>Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in the HTTP response.</p> <p>Based on that assumption, in addition to the bytes of the file, you also want to save the MIME type.</p> <p>How would you find the MIME type of a file? I'm currently on a Mac, but this should also work on Windows. </p> <p>Does the browser add this information when posting the file to the web page?</p> <p>Is there a neat python library for finding this information? A WebService or (even better) a downloadable database?</p>
101
2008-09-04T12:07:27Z
2,753,385
<p>The python-magic method suggested by toivotuo is outdated. <a href="http://github.com/ahupp/python-magic">Python-magic's</a> current trunk is at Github and based on the readme there, finding the MIME-type, is done like this.</p> <pre><code># For MIME types &gt;&gt;&gt; import magic &gt;&gt;&gt; mime = magic.Magic(mime=True) &gt;&gt;&gt; mime.from_file("testdata/test.pdf") 'application/pdf' &gt;&gt;&gt; </code></pre>
111
2010-05-02T12:02:45Z
[ "python", "mime" ]
How to find the mime type of a file in python?
43,580
<p>Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer.</p> <p>Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in the HTTP response.</p> <p>Based on that assumption, in addition to the bytes of the file, you also want to save the MIME type.</p> <p>How would you find the MIME type of a file? I'm currently on a Mac, but this should also work on Windows. </p> <p>Does the browser add this information when posting the file to the web page?</p> <p>Is there a neat python library for finding this information? A WebService or (even better) a downloadable database?</p>
101
2008-09-04T12:07:27Z
10,713,515
<p>you can use <strong>imghdr</strong> Python module.</p>
-2
2012-05-23T04:37:49Z
[ "python", "mime" ]
How to find the mime type of a file in python?
43,580
<p>Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer.</p> <p>Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in the HTTP response.</p> <p>Based on that assumption, in addition to the bytes of the file, you also want to save the MIME type.</p> <p>How would you find the MIME type of a file? I'm currently on a Mac, but this should also work on Windows. </p> <p>Does the browser add this information when posting the file to the web page?</p> <p>Is there a neat python library for finding this information? A WebService or (even better) a downloadable database?</p>
101
2008-09-04T12:07:27Z
11,101,343
<p>The mimetypes module just recognise an file type based on file extension. If you will try to recover a file type of a file without extension, the mimetypes will not works.</p>
3
2012-06-19T12:51:55Z
[ "python", "mime" ]
How to find the mime type of a file in python?
43,580
<p>Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer.</p> <p>Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in the HTTP response.</p> <p>Based on that assumption, in addition to the bytes of the file, you also want to save the MIME type.</p> <p>How would you find the MIME type of a file? I'm currently on a Mac, but this should also work on Windows. </p> <p>Does the browser add this information when posting the file to the web page?</p> <p>Is there a neat python library for finding this information? A WebService or (even better) a downloadable database?</p>
101
2008-09-04T12:07:27Z
12,297,929
<p>There are 3 different libraries that wraps libmagic.</p> <p>2 of them are available on pypi (so pip install will work):</p> <ul> <li>filemagic</li> <li>python-magic</li> </ul> <p>And another, similar to python-magic is available directly in the latest libmagic sources, and it is the one you probably have in your linux distribution.</p> <p>In Debian the package python-magic is about this one and it is used as toivotuo said and it is not obsoleted as Simon Zimmermann said (IMHO).</p> <p>It seems to me another take (by the original author of libmagic).</p> <p>Too bad is not available directly on pypi.</p>
9
2012-09-06T10:22:50Z
[ "python", "mime" ]
How to find the mime type of a file in python?
43,580
<p>Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer.</p> <p>Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in the HTTP response.</p> <p>Based on that assumption, in addition to the bytes of the file, you also want to save the MIME type.</p> <p>How would you find the MIME type of a file? I'm currently on a Mac, but this should also work on Windows. </p> <p>Does the browser add this information when posting the file to the web page?</p> <p>Is there a neat python library for finding this information? A WebService or (even better) a downloadable database?</p>
101
2008-09-04T12:07:27Z
21,755,201
<p>This seems to be very easy </p> <pre><code>&gt;&gt;&gt; from mimetypes import MimeTypes &gt;&gt;&gt; import urllib &gt;&gt;&gt; mime = MimeTypes() &gt;&gt;&gt; url = urllib.pathname2url('Upload.xml') &gt;&gt;&gt; mime_type = mime.guess_type(url) &gt;&gt;&gt; print mime_type ('application/xml', None) </code></pre> <p>Please refer <a href="http://stackoverflow.com/a/14412233/1182058">Old Post</a></p>
13
2014-02-13T13:09:49Z
[ "python", "mime" ]
How to find the mime type of a file in python?
43,580
<p>Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer.</p> <p>Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in the HTTP response.</p> <p>Based on that assumption, in addition to the bytes of the file, you also want to save the MIME type.</p> <p>How would you find the MIME type of a file? I'm currently on a Mac, but this should also work on Windows. </p> <p>Does the browser add this information when posting the file to the web page?</p> <p>Is there a neat python library for finding this information? A WebService or (even better) a downloadable database?</p>
101
2008-09-04T12:07:27Z
28,306,825
<p>@toivotuo 's method worked best and most reliably for me under python3. My goal was to identify gzipped files which do not have a reliable .gz extension. I installed python3-magic.</p> <pre><code>import magic filename = "./datasets/test" def file_mime_type(filename): m = magic.open(magic.MAGIC_MIME) m.load() return(m.file(filename)) print(file_mime_type(filename)) </code></pre> <p>for a gzipped file it returns: application/gzip; charset=binary</p> <p>for an unzipped txt file (iostat data): text/plain; charset=us-ascii</p> <p>for a tar file: application/x-tar; charset=binary</p> <p>for a bz2 file: application/x-bzip2; charset=binary</p> <p>and last but not least for me a .zip file: application/zip; charset=binary</p>
4
2015-02-03T19:09:32Z
[ "python", "mime" ]