title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Storing Python scripts on a webserver
905,902
<p>Following on my previous question, if I have some hosting how can I put a python script on their that I can then run from there? Do I need to do something special to run it/install something? EDIT-Clarification-I would like to be able to upload the script which does stuff on the internet-no data is stored on my computer. I then need to schedule it to run once a day.</p>
0
2009-05-25T08:42:53Z
905,924
<p>Usually python is already installed, but it depends on your hoster. Ask them.</p>
0
2009-05-25T08:49:29Z
[ "python", "hosting" ]
Storing Python scripts on a webserver
905,902
<p>Following on my previous question, if I have some hosting how can I put a python script on their that I can then run from there? Do I need to do something special to run it/install something? EDIT-Clarification-I would like to be able to upload the script which does stuff on the internet-no data is stored on my computer. I then need to schedule it to run once a day.</p>
0
2009-05-25T08:42:53Z
906,016
<p>You have to ensure your hoster system supports Python.</p> <p>You can ask them about that.</p> <p>To run the script once it is there, you can act in several ways, depending on what you want to do.</p> <p>You can have your server side language to invoke it (i.e. from the backend of a web page), or if you have a shell access to the machine you can invoke it manually.</p> <p>Btw, very often hosting providers give a scheduling tool (i.e. an interface for crontab or at) via the hosting plan administration panel, which you could use to start your script. </p> <p>First thing, anyway, you have to ask your hoster and check Python availability.</p>
1
2009-05-25T09:15:32Z
[ "python", "hosting" ]
Python Twisted protocol unregistering?
906,496
<p>I've came up with problem regarding unregistering protocols from reactor in twisted while application is running. </p> <p>I use hardware modems connected to PC by USB and that's why this scenario is so important for my solution. Has anyone an idea how to do it?</p> <p>Greets, Chris</p>
6
2009-05-25T12:12:09Z
907,370
<p>When you first call <code>reactor.listen</code> on your protocol factory, it returns an object that implements <code>IListeningPort</code>, see <a href="http://twistedmatrix.com/documents/8.2.0/api/twisted.internet.interfaces.IListeningPort.html">http://twistedmatrix.com/documents/8.2.0/api/twisted.internet.interfaces.IListeningPort.html</a> -- just save that object somewhere and when you want to stop listening on that protocol factori, call that object's <code>stopListening</code> method.</p> <p>I assume that <code>reactor.listen</code> on the protocol factory is what you implicitly mean by "registering" a protocol (which logically should be what you're trying to undo by "unregistering" it), if you mean something else please clarify exactly how you "register a protocol" and we'll work out how to undo <em>that</em>!-)</p>
6
2009-05-25T16:47:28Z
[ "python", "twisted", "protocols" ]
show lyrics on ubuntu
906,509
<p>I'm writing a little script for Ubuntu. My intention is to call rhythmbox lyrics plug-in with a global short-cut (configuring gnome) . I can call it from rhythmbox python console, but I don't know how to import rhythmbox built-in modules (eg. rhythmdb).<br /> Any ideas?</p>
0
2009-05-25T12:16:07Z
1,450,802
<p>You can't import rhythmbox "built-in" modules from a standard python console. </p> <p>As far as I know they aren't real modules, they are just objects from the rhythmbox process exposed to plugins. So you can access them only if you are running your script from the rhythmbox process.</p>
1
2009-09-20T11:12:17Z
[ "python", "plugins", "gnome", "rhythmbox" ]
show lyrics on ubuntu
906,509
<p>I'm writing a little script for Ubuntu. My intention is to call rhythmbox lyrics plug-in with a global short-cut (configuring gnome) . I can call it from rhythmbox python console, but I don't know how to import rhythmbox built-in modules (eg. rhythmdb).<br /> Any ideas?</p>
0
2009-05-25T12:16:07Z
4,594,514
<p>in this case i guess you'll have to write the whole plugin yourself and , then listen to dbus for change of songs in rhythmbox , to detect which song is being played .</p>
0
2011-01-04T14:10:41Z
[ "python", "plugins", "gnome", "rhythmbox" ]
How do I inspect the scope of a function where Python raises an exception?
906,649
<p>I've recently discovered the very useful '-i' flag to Python</p> <pre> -i : inspect interactively after running script, (also PYTHONINSPECT=x) and force prompts, even if stdin does not appear to be a terminal </pre> <p>this is great for inspecting objects in the global scope, but what happens if the exception was raised in a function call, and I'd like to inspect the local variables of the function? Naturally, I'm interested in the scope of where the exception was first raised, is there any way to get to it?</p>
1
2009-05-25T12:58:43Z
906,665
<p>use ipython: <a href="http://mail.scipy.org/pipermail/ipython-user/2007-January/003985.html" rel="nofollow">http://mail.scipy.org/pipermail/ipython-user/2007-January/003985.html</a></p> <p>Usage example:</p> <pre><code>from IPython.Debugger import Tracer; debug_here = Tracer() #... later in your code debug_here() # -&gt; will open up the debugger at that point. </code></pre> <p>"Once the debugger activates, you can use all of its regular commands to step through code, set breakpoints, etc. See the pdb documentation from the Python standard library for usage details."</p>
4
2009-05-25T13:02:13Z
[ "python", "debugging" ]
How do I inspect the scope of a function where Python raises an exception?
906,649
<p>I've recently discovered the very useful '-i' flag to Python</p> <pre> -i : inspect interactively after running script, (also PYTHONINSPECT=x) and force prompts, even if stdin does not appear to be a terminal </pre> <p>this is great for inspecting objects in the global scope, but what happens if the exception was raised in a function call, and I'd like to inspect the local variables of the function? Naturally, I'm interested in the scope of where the exception was first raised, is there any way to get to it?</p>
1
2009-05-25T12:58:43Z
906,892
<p>In ipython, you can inspect variables at the location where your code crashed without having to modify it:</p> <pre><code>&gt;&gt;&gt; %pdb on &gt;&gt;&gt; %run my_script.py </code></pre>
5
2009-05-25T14:16:25Z
[ "python", "debugging" ]
How do I inspect the scope of a function where Python raises an exception?
906,649
<p>I've recently discovered the very useful '-i' flag to Python</p> <pre> -i : inspect interactively after running script, (also PYTHONINSPECT=x) and force prompts, even if stdin does not appear to be a terminal </pre> <p>this is great for inspecting objects in the global scope, but what happens if the exception was raised in a function call, and I'd like to inspect the local variables of the function? Naturally, I'm interested in the scope of where the exception was first raised, is there any way to get to it?</p>
1
2009-05-25T12:58:43Z
931,275
<p>At the interactive prompt, immediately type</p> <pre><code>&gt;&gt;&gt; import pdb &gt;&gt;&gt; pdb.pm() </code></pre> <p>pdb.pm() is the "post-mortem" debugger. It will put you at the scope where the exception was raised, and then you can use the usual pdb commands.</p> <p>I use this <em>all the time</em>. It's part of the standard library (no ipython necessary) and doesn't require editing debugging commands into your source code.</p> <p>The only trick is to remember to do it right away; if you type any other commands first, you'll lose the scope where the exception occurred.</p>
5
2009-05-31T04:37:45Z
[ "python", "debugging" ]
Alternative to innerhtml that includes header?
906,660
<p>I'm trying to extract data from the following page:</p> <p><a href="http://www.bmreports.com/servlet/com.logica.neta.bwp_PanBMDataServlet?param1=&amp;param2=&amp;param3=&amp;param4=&amp;param5=2009-04-22&amp;param6=37#" rel="nofollow">http://www.bmreports.com/servlet/com.logica.neta.bwp_PanBMDataServlet?param1=&amp;param2=&amp;param3=&amp;param4=&amp;param5=2009-04-22&amp;param6=37#</a></p> <p>Which, conveniently and inefficiently enough, includes all the data embedded as a csv file in the header, set as a variable called gs_csv. </p> <p>How do I extract this? <code>Document.body.innerhtml</code> skips the header where the data is, what is the alternative that includes the header (or better yet, the value associated with <code>gs_csv</code>)?</p> <p>(Sorry, new to all this, I've been searching through loads of documentation, and trying a lot of them, but nothing so far has worked). </p> <p><hr /></p> <p>Thanks to Sinan (this is mostly his solution transcribed into Python).</p> <pre><code>import win32com.client import time import os import os.path ie = Dispatch("InternetExplorer.Application") ie.Visible=False ie.Navigate("http://www.bmreports.com/servlet/com.logica.neta.bwp_PanBMDataServlet?param1=&amp;param2=&amp;param3=&amp;param4=&amp;param5=2009-04-22&amp;param6=37#") time.sleep(20) webpage=ie.document.body.innerHTML s1=ie.document.scripts(1).text s1=s1[s1.find("gs_csv")+8:-11] scriptfilepath="c:\FO Share\bmreports\script.txt" scriptfile = open(scriptfilepath, 'wb') scriptfile.write(s1.replace('\n','\n')) scriptfile.close() ie.quit </code></pre>
0
2009-05-25T13:00:59Z
906,689
<p><strong>Untested:</strong> Did you try looking at what <a href="http://msdn.microsoft.com/en-us/library/aa752604%28VS.85%29.aspx" rel="nofollow">Document.scripts</a> contains?</p> <p><strong>UPDATE:</strong></p> <p>For some reason, I am having immense difficulty getting this to work using the Windows Scripting Host (but then, I don't use it very often, apologies). Anyway, here is the Perl source that works:</p> <pre><code>use strict; use warnings; use Win32::OLE; $Win32::OLE::Warn = 3; my $ie = get_ie(); $ie-&gt;{Visible} = 1; $ie-&gt;Navigate( 'http://www.bmreports.com/servlet/com.logica.neta.bwp_PanBMDataServlet?' .'param1=&amp;param2=&amp;param3=&amp;param4=&amp;param5=2009-04-22&amp;param6=37#' ); sleep 1 until is_ready( $ie ); my $scripts = $ie-&gt;Document-&gt;{scripts}; for my $script (in $scripts ) { print $script-&gt;text; } sub is_ready { $_[0]-&gt;{ReadyState} == 4 } sub get_ie { Win32::OLE-&gt;new('InternetExplorer.Application', sub { $_[0] and $_[0]-&gt;Quit }, ); } __END__ C:\Temp&gt; ie &gt; output </code></pre> <p><code>output</code> now contains everything within the script tags.</p>
1
2009-05-25T13:10:39Z
[ "python", "html", "css", "dom", "com" ]
Alternative to innerhtml that includes header?
906,660
<p>I'm trying to extract data from the following page:</p> <p><a href="http://www.bmreports.com/servlet/com.logica.neta.bwp_PanBMDataServlet?param1=&amp;param2=&amp;param3=&amp;param4=&amp;param5=2009-04-22&amp;param6=37#" rel="nofollow">http://www.bmreports.com/servlet/com.logica.neta.bwp_PanBMDataServlet?param1=&amp;param2=&amp;param3=&amp;param4=&amp;param5=2009-04-22&amp;param6=37#</a></p> <p>Which, conveniently and inefficiently enough, includes all the data embedded as a csv file in the header, set as a variable called gs_csv. </p> <p>How do I extract this? <code>Document.body.innerhtml</code> skips the header where the data is, what is the alternative that includes the header (or better yet, the value associated with <code>gs_csv</code>)?</p> <p>(Sorry, new to all this, I've been searching through loads of documentation, and trying a lot of them, but nothing so far has worked). </p> <p><hr /></p> <p>Thanks to Sinan (this is mostly his solution transcribed into Python).</p> <pre><code>import win32com.client import time import os import os.path ie = Dispatch("InternetExplorer.Application") ie.Visible=False ie.Navigate("http://www.bmreports.com/servlet/com.logica.neta.bwp_PanBMDataServlet?param1=&amp;param2=&amp;param3=&amp;param4=&amp;param5=2009-04-22&amp;param6=37#") time.sleep(20) webpage=ie.document.body.innerHTML s1=ie.document.scripts(1).text s1=s1[s1.find("gs_csv")+8:-11] scriptfilepath="c:\FO Share\bmreports\script.txt" scriptfile = open(scriptfilepath, 'wb') scriptfile.write(s1.replace('\n','\n')) scriptfile.close() ie.quit </code></pre>
0
2009-05-25T13:00:59Z
906,695
<p>fetch the source of that page using ajax, and parse the response text like XML using jquery. It should be simple enought to get the text of the first tag you encounter inside the </p> <p>I'm out of touch with jquery, or I would have posted code examples.</p> <p>EDIT: I assume you are talking about fetching the csv on the client side.</p>
0
2009-05-25T13:12:16Z
[ "python", "html", "css", "dom", "com" ]
Alternative to innerhtml that includes header?
906,660
<p>I'm trying to extract data from the following page:</p> <p><a href="http://www.bmreports.com/servlet/com.logica.neta.bwp_PanBMDataServlet?param1=&amp;param2=&amp;param3=&amp;param4=&amp;param5=2009-04-22&amp;param6=37#" rel="nofollow">http://www.bmreports.com/servlet/com.logica.neta.bwp_PanBMDataServlet?param1=&amp;param2=&amp;param3=&amp;param4=&amp;param5=2009-04-22&amp;param6=37#</a></p> <p>Which, conveniently and inefficiently enough, includes all the data embedded as a csv file in the header, set as a variable called gs_csv. </p> <p>How do I extract this? <code>Document.body.innerhtml</code> skips the header where the data is, what is the alternative that includes the header (or better yet, the value associated with <code>gs_csv</code>)?</p> <p>(Sorry, new to all this, I've been searching through loads of documentation, and trying a lot of them, but nothing so far has worked). </p> <p><hr /></p> <p>Thanks to Sinan (this is mostly his solution transcribed into Python).</p> <pre><code>import win32com.client import time import os import os.path ie = Dispatch("InternetExplorer.Application") ie.Visible=False ie.Navigate("http://www.bmreports.com/servlet/com.logica.neta.bwp_PanBMDataServlet?param1=&amp;param2=&amp;param3=&amp;param4=&amp;param5=2009-04-22&amp;param6=37#") time.sleep(20) webpage=ie.document.body.innerHTML s1=ie.document.scripts(1).text s1=s1[s1.find("gs_csv")+8:-11] scriptfilepath="c:\FO Share\bmreports\script.txt" scriptfile = open(scriptfilepath, 'wb') scriptfile.write(s1.replace('\n','\n')) scriptfile.close() ie.quit </code></pre>
0
2009-05-25T13:00:59Z
906,852
<p>If this is just a one off script then exctracting this csv data is as simple as this:</p> <pre><code>import urllib2 response = urllib2.urlopen('http://www.bmreports.com/foo?bar?') html = response.read() csv = data.split('gs_csv=')[1].split('&lt;/SCRIPT&gt;')[0] #process csv data here </code></pre>
0
2009-05-25T14:02:46Z
[ "python", "html", "css", "dom", "com" ]
Alternative to innerhtml that includes header?
906,660
<p>I'm trying to extract data from the following page:</p> <p><a href="http://www.bmreports.com/servlet/com.logica.neta.bwp_PanBMDataServlet?param1=&amp;param2=&amp;param3=&amp;param4=&amp;param5=2009-04-22&amp;param6=37#" rel="nofollow">http://www.bmreports.com/servlet/com.logica.neta.bwp_PanBMDataServlet?param1=&amp;param2=&amp;param3=&amp;param4=&amp;param5=2009-04-22&amp;param6=37#</a></p> <p>Which, conveniently and inefficiently enough, includes all the data embedded as a csv file in the header, set as a variable called gs_csv. </p> <p>How do I extract this? <code>Document.body.innerhtml</code> skips the header where the data is, what is the alternative that includes the header (or better yet, the value associated with <code>gs_csv</code>)?</p> <p>(Sorry, new to all this, I've been searching through loads of documentation, and trying a lot of them, but nothing so far has worked). </p> <p><hr /></p> <p>Thanks to Sinan (this is mostly his solution transcribed into Python).</p> <pre><code>import win32com.client import time import os import os.path ie = Dispatch("InternetExplorer.Application") ie.Visible=False ie.Navigate("http://www.bmreports.com/servlet/com.logica.neta.bwp_PanBMDataServlet?param1=&amp;param2=&amp;param3=&amp;param4=&amp;param5=2009-04-22&amp;param6=37#") time.sleep(20) webpage=ie.document.body.innerHTML s1=ie.document.scripts(1).text s1=s1[s1.find("gs_csv")+8:-11] scriptfilepath="c:\FO Share\bmreports\script.txt" scriptfile = open(scriptfilepath, 'wb') scriptfile.write(s1.replace('\n','\n')) scriptfile.close() ie.quit </code></pre>
0
2009-05-25T13:00:59Z
907,209
<p>Thanks to Sinan (this is mostly his solution transcribed into Python).</p> <p>import win32com.client </p> <p>import time import os </p> <p>import os.path</p> <p>ie = Dispatch("InternetExplorer.Application") ie.Visible=False </p> <p>ie.Navigate("http://www.bmreports.com/servlet/com.logica.neta.bwp_PanBMDataServlet?param1=&amp;param2=&amp;param3=&amp;param4=&amp;param5=2009-04-22&amp;param6=37#")</p> <p>time.sleep(20)</p> <p>webpage=ie.document.body.innerHTML</p> <p>s1=ie.document.scripts(1).text s1=s1[s1.find("gs_csv")+8:-11]</p> <p>scriptfilepath="c:\FO Share\bmreports\script.txt" </p> <p>scriptfile = open(scriptfilepath, 'wb') </p> <p>scriptfile.write(s1.replace('\n','\n')) </p> <p>scriptfile.close()</p> <p>ie.quit</p>
0
2009-05-25T15:47:11Z
[ "python", "html", "css", "dom", "com" ]
exec statement with/without prior compile
906,920
<p>These weekend I've been tearing down to pieces Michele Simionato's <a href="http://pypi.python.org/pypi/decorator/3.0.1" rel="nofollow">decorator module</a>, that builds signature-preserving decorators. At the heart of it all there is a dynamically generated function, which works something similar to this...</p> <pre><code>src = """def function(a,b,c) :\n return _caller_(a,b,c)\n""" evaldict = {'_caller_' : _caller_} code = compile(src, '&lt;string&gt;', 'single') exec code in evaldict new_func = evaldict[function] </code></pre> <p>I have found, fooling around with this code, that the compile step can be completely avoided and go for a single:</p> <pre><code>exec src in evaldict </code></pre> <p>Now, I'm sure there is a good reason for that additional step, but I haven't been able to find what the difference between both approaches is. Performance?</p> <p>And since I'm asking, could something similar, i.e. define a new function and get a handle to it, be achieved with eval? I tried, but couldn't get that to work...</p>
1
2009-05-25T14:26:02Z
907,127
<p>There are a few differences that I see. Firstly, <a href="http://www.python.org/doc/2.6.2/library/functions.html#compile" rel="nofollow"><code>compile</code></a> has slightly better semantics in the face of syntax errors than <a href="http://www.python.org/doc/2.6.2/reference/simple%5Fstmts.html#the-exec-statement" rel="nofollow"><code>exec</code></a>. I suspect that the real reason is that the definition of <code>compile</code> is very explicit with respect to the handling of new line characters where <code>exec</code> is a little less precise.</p> <p>I was curious as to why <code>compile</code> and <code>exec</code> where being used in lieu of inner functions. I didn't know that <code>compile</code>/<code>exec</code> lets you control what globals are available. Very interesting.</p>
2
2009-05-25T15:19:16Z
[ "python", "compilation", "eval", "exec" ]
exec statement with/without prior compile
906,920
<p>These weekend I've been tearing down to pieces Michele Simionato's <a href="http://pypi.python.org/pypi/decorator/3.0.1" rel="nofollow">decorator module</a>, that builds signature-preserving decorators. At the heart of it all there is a dynamically generated function, which works something similar to this...</p> <pre><code>src = """def function(a,b,c) :\n return _caller_(a,b,c)\n""" evaldict = {'_caller_' : _caller_} code = compile(src, '&lt;string&gt;', 'single') exec code in evaldict new_func = evaldict[function] </code></pre> <p>I have found, fooling around with this code, that the compile step can be completely avoided and go for a single:</p> <pre><code>exec src in evaldict </code></pre> <p>Now, I'm sure there is a good reason for that additional step, but I haven't been able to find what the difference between both approaches is. Performance?</p> <p>And since I'm asking, could something similar, i.e. define a new function and get a handle to it, be achieved with eval? I tried, but couldn't get that to work...</p>
1
2009-05-25T14:26:02Z
907,818
<p>compile() allows you to control the code object created and its name and source, while exec is not so flexible. it is also worth doing so that others, when reading your code, will learn they are separate steps and have this in mind later, when they need to exec the same code more than once (where compile() once, exec multiple times would be faster), and writing your code to educate the next who reads it is always a worthy influence on design choices.</p>
2
2009-05-25T19:37:26Z
[ "python", "compilation", "eval", "exec" ]
A neat way of extending a class attribute in subclasses
907,324
<p>Let's say I have the following class</p> <pre><code>class Parent(object): Options = { 'option1': 'value1', 'option2': 'value2' } </code></pre> <p>And a subclass called Child</p> <pre><code>class Child(Parent): Options = Parent.Options.copy() Options.update({ 'option2': 'value2', 'option3': 'value3' }) </code></pre> <p>I want to be able to override or add options in the child class. The solution I'm using works. But I'm sure there is a better way of doing it.</p> <p><hr /></p> <p><strong>EDIT</strong></p> <p>I don't want to add options as class attributes because I have other class attributes that aren't options and I prefer to keep all options in one place. This is just a simple example, the actual code is more complicated than that. </p>
15
2009-05-25T16:28:54Z
907,335
<p>Why not just use class attributes?</p> <pre><code>class Parent(object): option1 = 'value1' option2 = 'value2' class Child(Parent): option2 = 'value2' option3 = 'value3' </code></pre>
4
2009-05-25T16:38:01Z
[ "python" ]
A neat way of extending a class attribute in subclasses
907,324
<p>Let's say I have the following class</p> <pre><code>class Parent(object): Options = { 'option1': 'value1', 'option2': 'value2' } </code></pre> <p>And a subclass called Child</p> <pre><code>class Child(Parent): Options = Parent.Options.copy() Options.update({ 'option2': 'value2', 'option3': 'value3' }) </code></pre> <p>I want to be able to override or add options in the child class. The solution I'm using works. But I'm sure there is a better way of doing it.</p> <p><hr /></p> <p><strong>EDIT</strong></p> <p>I don't want to add options as class attributes because I have other class attributes that aren't options and I prefer to keep all options in one place. This is just a simple example, the actual code is more complicated than that. </p>
15
2009-05-25T16:28:54Z
907,338
<pre><code>class ParentOptions: option1 = 'value1' option2 = 'value2' class ChildOptions(ParentOptions): option2 = 'value2' option3 = 'value3' class Parent(object): options = ParentOptions() class Child(Parent): options = ChildOptions() </code></pre>
2
2009-05-25T16:38:38Z
[ "python" ]
A neat way of extending a class attribute in subclasses
907,324
<p>Let's say I have the following class</p> <pre><code>class Parent(object): Options = { 'option1': 'value1', 'option2': 'value2' } </code></pre> <p>And a subclass called Child</p> <pre><code>class Child(Parent): Options = Parent.Options.copy() Options.update({ 'option2': 'value2', 'option3': 'value3' }) </code></pre> <p>I want to be able to override or add options in the child class. The solution I'm using works. But I'm sure there is a better way of doing it.</p> <p><hr /></p> <p><strong>EDIT</strong></p> <p>I don't want to add options as class attributes because I have other class attributes that aren't options and I prefer to keep all options in one place. This is just a simple example, the actual code is more complicated than that. </p>
15
2009-05-25T16:28:54Z
907,423
<p>One way would be to use keyword arguments to dict to specify additional keys:</p> <pre><code>Parent.options = dict( option1='value1', option2='value2', ) Child.options = dict(Parent.options, option2='value2a', option3='value3', ) </code></pre> <p>If you want to get fancier, then using the descriptor protocol you can create a proxy object that will encapsulate the lookup. (just walk the owner.__mro__ from the owner attribute to the __get__(self, instance, owner) method). Or even fancier, crossing into the probably-not-a-good-idea territory, metaclasses/class decorators.</p>
8
2009-05-25T17:05:43Z
[ "python" ]
A neat way of extending a class attribute in subclasses
907,324
<p>Let's say I have the following class</p> <pre><code>class Parent(object): Options = { 'option1': 'value1', 'option2': 'value2' } </code></pre> <p>And a subclass called Child</p> <pre><code>class Child(Parent): Options = Parent.Options.copy() Options.update({ 'option2': 'value2', 'option3': 'value3' }) </code></pre> <p>I want to be able to override or add options in the child class. The solution I'm using works. But I'm sure there is a better way of doing it.</p> <p><hr /></p> <p><strong>EDIT</strong></p> <p>I don't want to add options as class attributes because I have other class attributes that aren't options and I prefer to keep all options in one place. This is just a simple example, the actual code is more complicated than that. </p>
15
2009-05-25T16:28:54Z
907,476
<p>Semantically equivalent to your code but arguably neater:</p> <pre><code>class Child(Parent): Options = dict(Parent.Options, option2='value2', option3='value3') </code></pre> <p>Remember, "life is better without braces", and by calling <code>dict</code> explicitly you can often avoid braces (and extra quotes around keys that are constant identifier-like strings).</p> <p>See <a href="http://docs.python.org/library/stdtypes.html#dict">http://docs.python.org/library/stdtypes.html#dict</a> for more details -- the key bit is "If a key is specified both in the positional argument and as a keyword argument, the value associated with the keyword is retained", i.e. keyword args <em>override</em> key-value associations in the positional arg, just like the <code>update</code> method lets you override them).</p>
19
2009-05-25T17:25:19Z
[ "python" ]
A neat way of extending a class attribute in subclasses
907,324
<p>Let's say I have the following class</p> <pre><code>class Parent(object): Options = { 'option1': 'value1', 'option2': 'value2' } </code></pre> <p>And a subclass called Child</p> <pre><code>class Child(Parent): Options = Parent.Options.copy() Options.update({ 'option2': 'value2', 'option3': 'value3' }) </code></pre> <p>I want to be able to override or add options in the child class. The solution I'm using works. But I'm sure there is a better way of doing it.</p> <p><hr /></p> <p><strong>EDIT</strong></p> <p>I don't want to add options as class attributes because I have other class attributes that aren't options and I prefer to keep all options in one place. This is just a simple example, the actual code is more complicated than that. </p>
15
2009-05-25T16:28:54Z
907,481
<p>After thinking more about it, and thanks to @SpliFF suggestion this is what I came up with:</p> <pre><code>class Parent(object): class Options: option1 = 'value1' option2 = 'value2' class Child(Parent): class Options(Parent.Options): option2 = 'value2' option3 = 'value3' </code></pre> <p>I'm still open to better solutions though.</p>
6
2009-05-25T17:26:22Z
[ "python" ]
A neat way of extending a class attribute in subclasses
907,324
<p>Let's say I have the following class</p> <pre><code>class Parent(object): Options = { 'option1': 'value1', 'option2': 'value2' } </code></pre> <p>And a subclass called Child</p> <pre><code>class Child(Parent): Options = Parent.Options.copy() Options.update({ 'option2': 'value2', 'option3': 'value3' }) </code></pre> <p>I want to be able to override or add options in the child class. The solution I'm using works. But I'm sure there is a better way of doing it.</p> <p><hr /></p> <p><strong>EDIT</strong></p> <p>I don't want to add options as class attributes because I have other class attributes that aren't options and I prefer to keep all options in one place. This is just a simple example, the actual code is more complicated than that. </p>
15
2009-05-25T16:28:54Z
3,219,533
<p>Here is a way using a metaclass</p> <pre><code>class OptionMeta(type): @property def options(self): result = {} for d in self.__mro__[::-1]: result.update(getattr(d,'_options',{})) return result class Parent(object): __metaclass__ = OptionMeta _options = dict( option1='value1', option2='value2', ) class Child(Parent): _options = dict( option2='value2a', option3='value3', ) print Parent.options print Child.options </code></pre>
2
2010-07-10T14:23:27Z
[ "python" ]
European date input in Django Admin
907,351
<p>Django has a DATE_FORMAT and a DATE_TIME_FORMAT options that allow us to choose which format to use when viewing dates, but doesn't apparently let me change the input format for the date when editing or adding in the Django Admin.</p> <p>The default for the admin is: YYYY-MM-DD</p> <p>But would be awesome to use: DD-MM-YYYY</p> <p>Is this integrated in any case in i18n? Can this be changed without a custom model?</p>
6
2009-05-25T16:42:52Z
909,154
<p>Looks like this is <a href="http://code.djangoproject.com/ticket/6483" rel="nofollow">not yet supported</a>, as I understand it, so yes, you'll have to do some custom work for now.</p>
1
2009-05-26T06:19:51Z
[ "python", "django", "date", "django-admin" ]
European date input in Django Admin
907,351
<p>Django has a DATE_FORMAT and a DATE_TIME_FORMAT options that allow us to choose which format to use when viewing dates, but doesn't apparently let me change the input format for the date when editing or adding in the Django Admin.</p> <p>The default for the admin is: YYYY-MM-DD</p> <p>But would be awesome to use: DD-MM-YYYY</p> <p>Is this integrated in any case in i18n? Can this be changed without a custom model?</p>
6
2009-05-25T16:42:52Z
912,041
<p>You have to do this yourself for now, but it's quite easy to do with a custom form field class that sets the input_formats argument of DateField. This should do it:</p> <pre><code>class MyDateField(forms.DateField): def __init__(self, *args, **kwargs): kwargs.setdefault('input_formats', ("%d-%m-%Y",)) super(MyDateField, self).__init__(*args, **kwargs) </code></pre> <p>Note that input_formats is a list, so you can specify multiple possibilities and it will try them in order when parsing user input.</p>
2
2009-05-26T18:28:37Z
[ "python", "django", "date", "django-admin" ]
European date input in Django Admin
907,351
<p>Django has a DATE_FORMAT and a DATE_TIME_FORMAT options that allow us to choose which format to use when viewing dates, but doesn't apparently let me change the input format for the date when editing or adding in the Django Admin.</p> <p>The default for the admin is: YYYY-MM-DD</p> <p>But would be awesome to use: DD-MM-YYYY</p> <p>Is this integrated in any case in i18n? Can this be changed without a custom model?</p>
6
2009-05-25T16:42:52Z
1,437,608
<p>Based on this idea I made new db.fields class EuDateField:</p> <p>mydbfields.py</p> <pre><code>from django import forms from django.forms.fields import DEFAULT_DATE_INPUT_FORMATS from django.db import models class EuDateFormField(forms.DateField): def __init__(self, *args, **kwargs): kwargs.update({'input_formats': ("%d.%m.%Y",)+DEFAULT_DATE_INPUT_FORMATS}) super(EuDateFormField, self).__init__(*args, **kwargs) class EuDateField(models.DateField): def formfield(self, **kwargs): kwargs.update({'form_class': EuDateFormField}) return super(EuDateField, self).formfield(**kwargs) </code></pre> <p>Note that it adds my format (e.g. 31.12.2007) to existing "standard" django formats at first place.</p> <p>Usage: </p> <pre><code>from mydbfields import EuDateField class Person(models.Model): ... birthday = EuDateField("Birthday", null=True, blank=True, help_text="") </code></pre> <p>In my case this renders good in admin, but most probably will in ModelForm too (haven't tried it).</p> <p>My django version is: </p> <pre><code>&gt;&gt;&gt; import django &gt;&gt;&gt; django.get_version() u'1.1 alpha 1 SVN-10105' </code></pre>
2
2009-09-17T08:59:25Z
[ "python", "django", "date", "django-admin" ]
European date input in Django Admin
907,351
<p>Django has a DATE_FORMAT and a DATE_TIME_FORMAT options that allow us to choose which format to use when viewing dates, but doesn't apparently let me change the input format for the date when editing or adding in the Django Admin.</p> <p>The default for the admin is: YYYY-MM-DD</p> <p>But would be awesome to use: DD-MM-YYYY</p> <p>Is this integrated in any case in i18n? Can this be changed without a custom model?</p>
6
2009-05-25T16:42:52Z
8,604,000
<p>I've modified settings so that it disables l10n and set date format explicite:</p> <pre><code>USE_L10N = False DATE_FORMAT = 'd-m-Y' DATETIME_FORMAT = 'd-m-Y H:i' </code></pre> <p>You can set DATE_INPUT_FORMATS as well. </p>
2
2011-12-22T12:42:20Z
[ "python", "django", "date", "django-admin" ]
European date input in Django Admin
907,351
<p>Django has a DATE_FORMAT and a DATE_TIME_FORMAT options that allow us to choose which format to use when viewing dates, but doesn't apparently let me change the input format for the date when editing or adding in the Django Admin.</p> <p>The default for the admin is: YYYY-MM-DD</p> <p>But would be awesome to use: DD-MM-YYYY</p> <p>Is this integrated in any case in i18n? Can this be changed without a custom model?</p>
6
2009-05-25T16:42:52Z
8,860,276
<p>There is an official way to do this now since the closing of <a href="https://code.djangoproject.com/ticket/6483">Django ticket 6483</a> &amp; release of Django 1.2.</p> <p>If you have <a href="https://docs.djangoproject.com/en/1.3/ref/settings/#std%3asetting-USE_L10N"><code>USE_L10N</code></a> set to <code>False</code>, what you should do is specify the <a href="https://docs.djangoproject.com/en/1.3//ref/settings/#date-input-formats"><code>DATE_INPUT_FORMATS</code></a> and <a href="https://docs.djangoproject.com/en/1.3//ref/settings/#datetime-input-formats"><code>DATETIME_INPUT_FORMATS</code></a> in your <code>settings.py</code>. Here are the settings I use for this, based on converting the defaults:</p> <pre><code>#dd/mm/yyyy and dd/mm/yy date &amp; datetime input field settings DATE_INPUT_FORMATS = ('%d-%m-%Y', '%d/%m/%Y', '%d/%m/%y', '%d %b %Y', '%d %b, %Y', '%d %b %Y', '%d %b, %Y', '%d %B, %Y', '%d %B %Y') DATETIME_INPUT_FORMATS = ('%d/%m/%Y %H:%M:%S', '%d/%m/%Y %H:%M', '%d/%m/%Y', '%d/%m/%y %H:%M:%S', '%d/%m/%y %H:%M', '%d/%m/%y', '%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d') </code></pre> <p>If you have <code>USE_L10N</code> set to <code>True</code>, then you will need to use the <a href="https://docs.djangoproject.com/en/1.3/ref/settings/#format-module-path"><code>FORMAT_MODULE_PATH</code></a> instead.</p> <p>For example, my <a href="https://docs.djangoproject.com/en/1.3/ref/settings/#language-code"><code>LANGUAGE_CODE</code></a> is set to <code>en-au</code>, my site is called <code>golf</code>, and my <code>FORMAT_MODULE_PATH</code> is set to <code>golf.formats</code>, so my directory structure looks like this:</p> <pre><code>golf/ settings.py ... formats/ __init__.py en/ __init__.py formats.py </code></pre> <p>and the <code>DATE_INPUT_FORMATS</code> and <code>DATETIME_INPUT_FORMATS</code> settings are in <code>formats.py</code> instead of <code>settings.py</code>.</p>
8
2012-01-14T05:03:44Z
[ "python", "django", "date", "django-admin" ]
European date input in Django Admin
907,351
<p>Django has a DATE_FORMAT and a DATE_TIME_FORMAT options that allow us to choose which format to use when viewing dates, but doesn't apparently let me change the input format for the date when editing or adding in the Django Admin.</p> <p>The default for the admin is: YYYY-MM-DD</p> <p>But would be awesome to use: DD-MM-YYYY</p> <p>Is this integrated in any case in i18n? Can this be changed without a custom model?</p>
6
2009-05-25T16:42:52Z
16,724,725
<p>just beware not to write it as a string but as a tuple. eg:</p> <pre><code>DATE_INPUT_FORMATS = ('%d.%m.%Y',) </code></pre> <p>if you want to have only one valid way of writing date in a form.</p>
0
2013-05-23T22:10:38Z
[ "python", "django", "date", "django-admin" ]
Making a Python script executable chmod755?
907,579
<p>My hosting provider says my python script must be made to be executable(chmod755). What does this mean &amp; how do I do it?</p> <p>Cheers!</p>
4
2009-05-25T18:05:23Z
907,585
<p>on the shell (such as bash), just type</p> <pre><code>chmod 755 file.py </code></pre> <p>to make it executable. You can use</p> <pre><code>ls -l file.py </code></pre> <p>to verify the execution permission is set (the "x" in "rwxr-xr-x")</p>
0
2009-05-25T18:06:57Z
[ "python", "hosting" ]
Making a Python script executable chmod755?
907,579
<p>My hosting provider says my python script must be made to be executable(chmod755). What does this mean &amp; how do I do it?</p> <p>Cheers!</p>
4
2009-05-25T18:05:23Z
907,591
<p>Unix-like systems have "file modes" that say who can read/write/execute a file. The mode 755 means owner can read/write/execute, and everyone else can read/execute but not write. To make your Python script have this mode, you type</p> <pre><code>chmod 0755 script.py </code></pre> <p>You also need a shebang like</p> <pre><code>#!/usr/bin/python </code></pre> <p>on the very first line of the file to tell the operating system what kind of script it is.</p>
5
2009-05-25T18:08:55Z
[ "python", "hosting" ]
Making a Python script executable chmod755?
907,579
<p>My hosting provider says my python script must be made to be executable(chmod755). What does this mean &amp; how do I do it?</p> <p>Cheers!</p>
4
2009-05-25T18:05:23Z
907,595
<p>If you have ssh access to your web space, connect and issue</p> <pre><code>chmod 755 nameofyourscript.py </code></pre> <p>If you do not have ssh access but rather connect by FTP, check your FTP application to see whether it supports setting the permissions.</p> <p>As to the meaning of 755:</p> <ul> <li>first digit is user settings (yourself)</li> <li>second digit is group settings</li> <li>third digit is the rest of the system</li> </ul> <p>The digits are constructed by adding the permision values. 1 = executable, 2 = writable and 4 = readable. I.e. 755 means that you yourself can read, write and execute the file and everybody else can read and execute it.</p>
5
2009-05-25T18:09:51Z
[ "python", "hosting" ]
Making a Python script executable chmod755?
907,579
<p>My hosting provider says my python script must be made to be executable(chmod755). What does this mean &amp; how do I do it?</p> <p>Cheers!</p>
4
2009-05-25T18:05:23Z
907,605
<p>In addition to the other fine answers here, you should be aware that most FTP clients have a <code>chmod</code> command to allow you to set permissions on files at the server. You may not need this if permissions come across properly, but there's a good chance they do not.</p>
0
2009-05-25T18:13:18Z
[ "python", "hosting" ]
Making a Python script executable chmod755?
907,579
<p>My hosting provider says my python script must be made to be executable(chmod755). What does this mean &amp; how do I do it?</p> <p>Cheers!</p>
4
2009-05-25T18:05:23Z
907,625
<p>It means, that somebody (the user, a group or everybody) has the right so execute (or read or write) the script (or a file in general). </p> <p>The permissions are expressed in different ways:</p> <pre><code>$ chmod +x file.py # makes it executable by anyone $ chmod +w file.py # makes it writeabel by anyone $ chmod +r file.py # makes it readably by anyone $ chmod u+x file.py # makes it executable for the owner (user) of the file $ chmod g+x file.py # makes it executable for the group (of the file) $ chmod o+x file.py # makes it executable for the others (everybody) </code></pre> <p>You can take away permissions in the same way, just substitute the <code>+</code> by a <code>-</code></p> <pre><code>$ chmod o-x file.py # makes a file non-executable for the others (everybody) $ ... </code></pre> <p>Octal numbers express the same in a different way. 4 is reading, 2 writing, 1 execution. </p> <p>simple math:</p> <pre><code>read + execute = 5 read + write + execute = 7 execute + write = 3 ... </code></pre> <p>packed all in one short and sweet command:</p> <pre><code># 1st digit: user permissions # 2nd digit: group permissions # 3rd digit: 'other' permissions # add the owner all perms., # the group and other only write and execution $ chmod 755 file.py </code></pre>
1
2009-05-25T18:20:19Z
[ "python", "hosting" ]
Gather all Python modules used into one folder?
907,660
<p>I don't think this has been asked before-I have a folder that has lots of different .py files. The script I've made only uses some-but some call others &amp; I don't know all the ones being used. Is there a program that will get everything needed to make that script run into one folder?</p> <p>Cheers!</p>
6
2009-05-25T18:31:23Z
907,683
<p><a href="http://wiki.python.org/moin/Freeze" rel="nofollow">Freeze</a> does pretty close to what you describe. It does an extra step of generating C files to create a stand-alone executable, but you could use the log output it produces to get the list of modules your script uses. From there it's a simple matter to copy them all into a directory to be zipped up (or whatever).</p>
0
2009-05-25T18:41:05Z
[ "python" ]
Gather all Python modules used into one folder?
907,660
<p>I don't think this has been asked before-I have a folder that has lots of different .py files. The script I've made only uses some-but some call others &amp; I don't know all the ones being used. Is there a program that will get everything needed to make that script run into one folder?</p> <p>Cheers!</p>
6
2009-05-25T18:31:23Z
907,736
<pre><code># zipmod.py - make a zip archive consisting of Python modules and their dependencies as reported by modulefinder # To use: cd to the directory containing your Python module tree and type # $ python zipmod.py archive.zip mod1.py mod2.py ... # Only modules in the current working directory and its subdirectories will be included. # Written and tested on Mac OS X, but it should work on other platforms with minimal modifications. import modulefinder import os import sys import zipfile def main(output, *mnames): mf = modulefinder.ModuleFinder() for mname in mnames: mf.run_script(mname) cwd = os.getcwd() zf = zipfile.ZipFile(output, 'w') for mod in mf.modules.itervalues(): if not mod.__file__: continue modfile = os.path.abspath(mod.__file__) if os.path.commonprefix([cwd, modfile]) == cwd: zf.write(modfile, os.path.relpath(modfile)) zf.close() if __name__ == '__main__': main(*sys.argv[1:]) </code></pre>
6
2009-05-25T19:00:04Z
[ "python" ]
Gather all Python modules used into one folder?
907,660
<p>I don't think this has been asked before-I have a folder that has lots of different .py files. The script I've made only uses some-but some call others &amp; I don't know all the ones being used. Is there a program that will get everything needed to make that script run into one folder?</p> <p>Cheers!</p>
6
2009-05-25T18:31:23Z
907,744
<p>Use the <code>modulefinder</code> module in the standard library, see e.g. <a href="http://docs.python.org/library/modulefinder.html" rel="nofollow">http://docs.python.org/library/modulefinder.html</a></p>
6
2009-05-25T19:04:03Z
[ "python" ]
How to let Django's generic view use a form with initial values?
907,858
<p>I know how to set initial values to a form from the view. But how do I go about letting a generic view set initial values to a form? I can write a wrapper view for the generic view, but I still have no access to the form object instantiation.</p> <p>The specific goal I'm trying to achieve is to have a user create a new object, using the create_object generic view. However, I'd like to set a field of the object 'user' to the currently logged in user, which is only accessible as request.user. How can the form be initialized to have this field?</p> <p>Edit: I came across __new__. Could this call its own constructor with some default arguments?</p> <p>Many thanks.</p>
2
2009-05-25T19:51:55Z
908,038
<p>Unfortunately, you cannot achieve this behavior through Django's <code>create_object</code> generic view; you will have to write your own. However, this is rather simple.</p> <p>To start off, you must create a new form class, like this:</p> <pre><code>from django import forms class MyForm(forms.ModelForm): class Meta: model = MyModel # model has a user field </code></pre> <p>Then you would be able to create a view like this:</p> <pre><code>from django.shortcuts import render_to_response from django.template import RequestContext from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required @login_required def create_mymodel(request): if request.method == 'POST': # Get data from form form = MyForm(request.POST) # If the form is valid, create a new object and redirect to it. if form.is_valid(): newObject = form.save() return HttpResponseRedirect(newObject.get_absolute_url()) else: # Fill in the field with the current user by default form = MyForm(initial={'user': request.user}) # Render our template return render_to_response('path/to/template.html', {'form': form}, context_instance=RequestContext(request)) </code></pre>
4
2009-05-25T20:59:36Z
[ "python", "django", "forms", "user" ]
How to let Django's generic view use a form with initial values?
907,858
<p>I know how to set initial values to a form from the view. But how do I go about letting a generic view set initial values to a form? I can write a wrapper view for the generic view, but I still have no access to the form object instantiation.</p> <p>The specific goal I'm trying to achieve is to have a user create a new object, using the create_object generic view. However, I'd like to set a field of the object 'user' to the currently logged in user, which is only accessible as request.user. How can the form be initialized to have this field?</p> <p>Edit: I came across __new__. Could this call its own constructor with some default arguments?</p> <p>Many thanks.</p>
2
2009-05-25T19:51:55Z
912,099
<p>You could do this in a generic view wrapper by dynamically constructing a form class and passing it to the generic view, but that cure is probably worse than the disease. Just write your own view, and wait eagerly for <a href="http://code.djangoproject.com/ticket/6735" rel="nofollow">this</a> to land.</p>
3
2009-05-26T18:42:41Z
[ "python", "django", "forms", "user" ]
How to let Django's generic view use a form with initial values?
907,858
<p>I know how to set initial values to a form from the view. But how do I go about letting a generic view set initial values to a form? I can write a wrapper view for the generic view, but I still have no access to the form object instantiation.</p> <p>The specific goal I'm trying to achieve is to have a user create a new object, using the create_object generic view. However, I'd like to set a field of the object 'user' to the currently logged in user, which is only accessible as request.user. How can the form be initialized to have this field?</p> <p>Edit: I came across __new__. Could this call its own constructor with some default arguments?</p> <p>Many thanks.</p>
2
2009-05-25T19:51:55Z
8,945,139
<p>If you want all the features of the generic view then you can just create a new generic view using the original as a template.</p> <p>Eg:</p> <pre><code>def create_object_with_initial(request, model=None, template_name=None, template_loader=loader, extra_context=None, post_save_redirect=None, login_required=False, context_processors=None, form_class=None, initial=None): if extra_context is None: extra_context = {} if login_required and not request.user.is_authenticated(): return redirect_to_login(request.path) model, form_class = get_model_and_form_class(model, form_class) if request.method == 'POST': form = form_class(request.POST, request.FILES) if form.is_valid(): new_object = form.save() msg = ugettext("The %(verbose_name)s was created successfully.") %\ {"verbose_name": model._meta.verbose_name} messages.success(request, msg, fail_silently=True) return redirect(post_save_redirect, new_object) else: print "creating", form_class, " with initial data ", initial form = form_class(initial=initial) # Create the template, context, response if not template_name: template_name = "%s/%s_form.html" % (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) c = RequestContext(request, { 'form': form, }, context_processors) apply_extra_context(extra_context, c) return HttpResponse(t.render(c)) </code></pre> <p>This is copied from /site-packages/django/views/generic/create_update.py with only lines 3 and 21 changing to incorporate the initial data.</p> <p>Then use it as you might expect:</p> <pre><code>object_info = { 'model': YourModel, 'initial': {'data' : 'Initial Value'}, 'template_name': 'template.html' } url(r'^path/$', login_required(create_object_with_initial), object_info, name='url_name'), </code></pre> <p>That should work.</p>
0
2012-01-20T17:07:26Z
[ "python", "django", "forms", "user" ]
Generating file to download with Django
908,258
<p>Is it possible to make a zip archive and offer it to download, but still not save a file to the hard drive?</p>
76
2009-05-25T22:26:01Z
908,266
<p>Yes, you can use the <a href="http://www.python.org/doc/2.5.2/lib/zipfile-objects.html">zipfile module</a>, <a href="http://www.python.org/doc/2.5.2/lib/module-zlib.html">zlib module</a> or other <a href="http://www.python.org/doc/2.5.2/lib/archiving.html">compression modules</a> to create a zip archive in memory. You can make your view write the zip archive to the <code>HttpResponse</code> object that the Django view returns instead of sending a context to a template. Lastly, you'll need to set the mimetype to the appropriate format to <a href="http://docs.djangoproject.com/en/dev/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment">tell the browser to treat the response as a file</a>.</p>
8
2009-05-25T22:29:21Z
[ "python", "django" ]
Generating file to download with Django
908,258
<p>Is it possible to make a zip archive and offer it to download, but still not save a file to the hard drive?</p>
76
2009-05-25T22:26:01Z
908,293
<p>You'll be happier creating a temporary file. This saves a lot of memory. When you have more than one or two users concurrently, you'll find the memory saving is very, very important.</p> <p>You can, however, write to a <a href="http://docs.python.org/library/stringio.html">StringIO</a> object.</p> <pre><code>&gt;&gt;&gt; import zipfile &gt;&gt;&gt; import StringIO &gt;&gt;&gt; buffer= StringIO.StringIO() &gt;&gt;&gt; z= zipfile.ZipFile( buffer, "w" ) &gt;&gt;&gt; z.write( "idletest" ) &gt;&gt;&gt; z.close() &gt;&gt;&gt; len(buffer.getvalue()) 778 </code></pre> <p>The "buffer" object is file-like with a 778 byte ZIP archive.</p>
24
2009-05-25T22:42:00Z
[ "python", "django" ]
Generating file to download with Django
908,258
<p>Is it possible to make a zip archive and offer it to download, but still not save a file to the hard drive?</p>
76
2009-05-25T22:26:01Z
909,088
<p>To trigger a download you need to set <code>Content-Disposition</code> header:</p> <pre><code>from django.http import HttpResponse from wsgiref.util import FileWrapper # generate the file response = HttpResponse(FileWrapper(myfile.getvalue()), content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=myfile.zip' return response </code></pre> <p>If you don't want the file on disk you need to use <code>StringIO</code></p> <pre><code>import cStringIO as StringIO myfile = StringIO.StringIO() while not_finished: # generate chunk myfile.write(chunk) </code></pre> <p>Optionally you can set <code>Content-Length</code> header as well:</p> <pre><code>response['Content-Length'] = myfile.tell() </code></pre>
95
2009-05-26T05:53:30Z
[ "python", "django" ]
Generating file to download with Django
908,258
<p>Is it possible to make a zip archive and offer it to download, but still not save a file to the hard drive?</p>
76
2009-05-25T22:26:01Z
5,905,850
<p>There is a code example at <a href="http://djangosnippets.org/snippets/365/">http://djangosnippets.org/snippets/365/</a></p>
5
2011-05-06T01:14:46Z
[ "python", "django" ]
Generating file to download with Django
908,258
<p>Is it possible to make a zip archive and offer it to download, but still not save a file to the hard drive?</p>
76
2009-05-25T22:26:01Z
6,922,996
<h3>models.py</h3> <pre><code>from django.db import models class PageHeader(models.Model): image = models.ImageField(upload_to='uploads') </code></pre> <h3>views.py</h3> <pre><code>from django.http import HttpResponse from StringIO import StringIO from models import * import os, mimetypes, urllib def random_header_image(request): header = PageHeader.objects.order_by('?')[0] image = StringIO(file(header.image.path, "rb").read()) mimetype = mimetypes.guess_type(os.path.basename(header.image.name))[0] return HttpResponse(image.read(), mimetype=mimetype) </code></pre>
5
2011-08-03T07:24:04Z
[ "python", "django" ]
Generating file to download with Django
908,258
<p>Is it possible to make a zip archive and offer it to download, but still not save a file to the hard drive?</p>
76
2009-05-25T22:26:01Z
7,353,876
<p>Why not make a tar file instead? Like so:</p> <pre><code>def downloadLogs(req, dir): response = HttpResponse(mimetype='application/x-gzip') response['Content-Disposition'] = 'attachment; filename=download.tar.gz' tarred = tarfile.open(fileobj=response, mode='w:gz') tarred.add(dir) tarred.close() return response </code></pre>
6
2011-09-08T20:12:00Z
[ "python", "django" ]
Generating file to download with Django
908,258
<p>Is it possible to make a zip archive and offer it to download, but still not save a file to the hard drive?</p>
76
2009-05-25T22:26:01Z
38,659,790
<pre><code>def download_zip(request,file_name): filePath = '&lt;path&gt;/'+file_name fsock = open(file_name_with_path,"rb") response = HttpResponse(fsock, content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=myfile.zip' return response </code></pre> <p>You can replace zip and content type as per your requirement.</p>
3
2016-07-29T13:10:32Z
[ "python", "django" ]
Secure plugin system for python application
908,285
<p>I have an application written in python. I created a plugin system for the application that uses egg files. Egg files contain compiled python files and can be easily decompiled and used to hack the application. Is there a way to secure this system? I'd like to use digital signature for this - sign these egg files and check the signature before loading such egg file. Is there a way to do this programmatically from python? Maybe using winapi?</p>
2
2009-05-25T22:39:48Z
908,307
<p>Maybe some crypto library like this <a href="http://chandlerproject.org/Projects/MeTooCrypto" rel="nofollow">http://chandlerproject.org/Projects/MeTooCrypto</a> helps to build an ad-hoc solution. Example usage: <a href="http://tdilshod.livejournal.com/38040.html" rel="nofollow">http://tdilshod.livejournal.com/38040.html</a></p>
1
2009-05-25T22:49:00Z
[ "python", "plugins", "signing" ]
Secure plugin system for python application
908,285
<p>I have an application written in python. I created a plugin system for the application that uses egg files. Egg files contain compiled python files and can be easily decompiled and used to hack the application. Is there a way to secure this system? I'd like to use digital signature for this - sign these egg files and check the signature before loading such egg file. Is there a way to do this programmatically from python? Maybe using winapi?</p>
2
2009-05-25T22:39:48Z
908,846
<blockquote> <p>Is there a way to secure this system?</p> </blockquote> <p>The answer is "that depends".</p> <p>The two questions you should ask is "what are people supposed to be able to do" and "what are people able to do (for a given implementation)". If there exists an implementation where the latter is a subset of the former, the system can be secured.</p> <p>One of my friend is working on a programming competition judge: a program which runs a user-submitted program on some test data and compares its output to a reference output. That's damn hard to secure: you want to run other peoples' code, but you don't want to let them run <em>arbitrary</em> code. Is your scenario somewhat similar to this? Then the answer is "it's difficult".</p> <p>Do you want users to download untrustworthy code from the web and run it with some assurance that it won't hose their machine? Then look at various web languages. One solution is not offering access to system calls (JavaScript) or offering limited access to certain potentially dangerous calls (Java's SecurityManager). None of them can be done in python as far as I'm aware, but you can always hack the interpreter and disallow the loading of external modules not on some whitelist. This is probably error-prone.</p> <p>Do you want users to write plugins, and not be able to tinker with what the main body of code in your application does? Consider that users can decompile .pyc files and modify them. Assume that those running your code can always modify it, and consider the gold-farming bots for WoW.</p> <p>One Linux-only solution, similar to the sandboxed web-ish model, is to use AppArmor, which limits which files your app can access and which system calls it can make. This might be a feasible solution, but I don't know much about it so I can't give you advice other than "investigate".</p> <p>If all you worry about is evil people modifying code while it's in transit in the intertubes, standard cryptographic solutions exist (SSL). If you want to only load signed plugins (because you want to control what the users do?), signing code sounds like the right solution (but beware of crafty users or evil people who edit the .pyc files and disables the is-it-signed check).</p>
3
2009-05-26T03:51:12Z
[ "python", "plugins", "signing" ]
How to write binary data in stdout in python 3?
908,331
<p>In python 2.x I could do this:</p> <pre><code>import sys, array a = array.array('B', range(100)) a.tofile(sys.stdout)</code></pre> <p>Now however, I get a <code>TypeError: can't write bytes to text stream</code>. Is there some secret encoding that I should use?</p>
32
2009-05-25T23:04:05Z
908,339
<pre><code>import os os.write(1, a.tostring()) </code></pre> <p>or, <code>os.write(sys.stdout.fileno(), …)</code> if that's more readable than <code>1</code> for you.</p>
5
2009-05-25T23:11:15Z
[ "python", "python-3.x" ]
How to write binary data in stdout in python 3?
908,331
<p>In python 2.x I could do this:</p> <pre><code>import sys, array a = array.array('B', range(100)) a.tofile(sys.stdout)</code></pre> <p>Now however, I get a <code>TypeError: can't write bytes to text stream</code>. Is there some secret encoding that I should use?</p>
32
2009-05-25T23:04:05Z
908,440
<p>A better way:</p> <pre><code>import sys sys.stdout.buffer.write(b"some binary data") </code></pre>
51
2009-05-26T00:09:34Z
[ "python", "python-3.x" ]
How to write binary data in stdout in python 3?
908,331
<p>In python 2.x I could do this:</p> <pre><code>import sys, array a = array.array('B', range(100)) a.tofile(sys.stdout)</code></pre> <p>Now however, I get a <code>TypeError: can't write bytes to text stream</code>. Is there some secret encoding that I should use?</p>
32
2009-05-25T23:04:05Z
29,606,070
<p>In case you would like to specify an encoding in python3 you can still use the bytes command like below:</p> <pre><code>import os os.write(1,bytes('Your string to Stdout','UTF-8')) </code></pre> <p>where 1 is the corresponding usual number for stdout --> sys.stdout.fileno()</p> <p>Otherwise if you don't care of the encoding just use:</p> <pre><code>import sys sys.stdout.write("Your string to Stdout\n") </code></pre> <p>If you want to use the os.write without the encoding, then try to use the below:</p> <pre><code>import os os.write(1,b"Your string to Stdout\n") </code></pre>
0
2015-04-13T13:05:25Z
[ "python", "python-3.x" ]
Python Getting date online?
908,550
<p>How can I get the current date, month &amp; year online using Python? Thanks!</p> <p>EDIT-By this I mean, rather than getting it from the computer's date-visit a website &amp; get it, so it doesn't rely on the computer.</p>
2
2009-05-26T01:21:57Z
908,572
<p>here is a python module for hitting NIST online <a href="http://freshmeat.net/projects/mxdatetime" rel="nofollow">http://freshmeat.net/projects/mxdatetime</a>. </p>
0
2009-05-26T01:31:04Z
[ "python" ]
Python Getting date online?
908,550
<p>How can I get the current date, month &amp; year online using Python? Thanks!</p> <p>EDIT-By this I mean, rather than getting it from the computer's date-visit a website &amp; get it, so it doesn't rely on the computer.</p>
2
2009-05-26T01:21:57Z
908,582
<p>Perhaps you mean the NTP protocol? This project may help: <a href="http://pypi.python.org/pypi/ntplib/0.1.3" rel="nofollow">http://pypi.python.org/pypi/ntplib/0.1.3</a></p>
0
2009-05-26T01:35:23Z
[ "python" ]
Python Getting date online?
908,550
<p>How can I get the current date, month &amp; year online using Python? Thanks!</p> <p>EDIT-By this I mean, rather than getting it from the computer's date-visit a website &amp; get it, so it doesn't rely on the computer.</p>
2
2009-05-26T01:21:57Z
908,604
<p>If you can't use NTP, but rather want to stick with HTTP, you could <code>urllib.urlget("http://developer.yahooapis.com/TimeService/V1/getTime")</code> and parse the results:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;Error xmlns="urn:yahoo:api"&gt; The following errors were detected: &lt;Message&gt;Appid missing or other error &lt;/Message&gt; &lt;/Error&gt; &lt;!-- p6.ydn.sp1.yahoo.com uncompressed/chunked Mon May 25 18:42:11 PDT 2009 --&gt; </code></pre> <p>Note that the datetime (in PDT) is in the final comment (the error message is due to lack of APP ID). There probably are more suitable web services to get the current date and time in HTTP (without requiring registration &amp;c), since e.g. making such a service freely available on Google App Engine would be so trivial, but I don't know of one offhand.</p>
3
2009-05-26T01:44:55Z
[ "python" ]
Python Getting date online?
908,550
<p>How can I get the current date, month &amp; year online using Python? Thanks!</p> <p>EDIT-By this I mean, rather than getting it from the computer's date-visit a website &amp; get it, so it doesn't rely on the computer.</p>
2
2009-05-26T01:21:57Z
908,649
<p>So thinking about the "would be so trivial" part I went ahead and just made <a href="http://just-the-time.appspot.com/">a google app engine web app</a> -- when you visit it, it returns a simple response claiming to be HTML but actually just a string such as <code>2009-05-26 02:01:12 UTC\n</code>. Any feature requests?-)</p>
24
2009-05-26T02:04:50Z
[ "python" ]
Regex Subtitution in Python
908,739
<p>I have a CSV file with several entries, and each entry has 2 unix timestamp formatted dates.</p> <p>I have a method called <code>convert()</code>, which takes in the timestamp and converts it to <code>YYYYMMDD</code>.</p> <p>Now, since I have 2 timestamps in each line, how would I replace each one with the new value?</p> <p>EDIT: Just to clarify, I would like to convert each occurrence of the timestamp into the <code>YYYYMMDD</code> format. This is what is bugging me, as <code>re.findall()</code> returns a list.</p>
2
2009-05-26T02:48:22Z
908,751
<p>If you know the replacement:</p> <pre><code>p = re.compile( r',\d{8},') p.sub( ','+someval+',', csvstring ) </code></pre> <p>if it's a format change:</p> <pre><code>p = re.compile( r',(\d{4})(\d\d)(\d\d),') p.sub( r',\3-\2-\1,', csvstring ) </code></pre> <p>EDIT: sorry, just realised you said python, modified above</p>
3
2009-05-26T02:53:37Z
[ "python", "regex", "timestamp" ]
Regex Subtitution in Python
908,739
<p>I have a CSV file with several entries, and each entry has 2 unix timestamp formatted dates.</p> <p>I have a method called <code>convert()</code>, which takes in the timestamp and converts it to <code>YYYYMMDD</code>.</p> <p>Now, since I have 2 timestamps in each line, how would I replace each one with the new value?</p> <p>EDIT: Just to clarify, I would like to convert each occurrence of the timestamp into the <code>YYYYMMDD</code> format. This is what is bugging me, as <code>re.findall()</code> returns a list.</p>
2
2009-05-26T02:48:22Z
908,800
<p>I assume that by "unix timestamp formatted date" you mean a number of seconds since the epoch. This assumes that every number in the file is a UNIX timestamp. If that isn't the case you'll need to adjust the regex:</p> <pre><code>import re, sys # your convert function goes here regex = re.compile(r'(\d+)') for line in sys.stdin: sys.stdout.write(regex.sub(lambda m: convert(int(m.group(1))), line)) </code></pre> <p>This reads from stdin and calls convert on each number found.</p> <p>The "trick" here is that <code>re.sub</code> can take a function that transforms from a match object into a string. I'm assuming your convert function expects an int and returns a string, so I've used a lambda as an adapter function to grab the first group of the match, convert it to an int, and then pass that resulting int to convert.</p>
1
2009-05-26T03:20:59Z
[ "python", "regex", "timestamp" ]
Regex Subtitution in Python
908,739
<p>I have a CSV file with several entries, and each entry has 2 unix timestamp formatted dates.</p> <p>I have a method called <code>convert()</code>, which takes in the timestamp and converts it to <code>YYYYMMDD</code>.</p> <p>Now, since I have 2 timestamps in each line, how would I replace each one with the new value?</p> <p>EDIT: Just to clarify, I would like to convert each occurrence of the timestamp into the <code>YYYYMMDD</code> format. This is what is bugging me, as <code>re.findall()</code> returns a list.</p>
2
2009-05-26T02:48:22Z
908,851
<p>I'd use something along these lines. A lot like Laurence's response but with the timestamp conversion that you requested and takes the filename as a param. This code assumes you are working with recent dates (after 9/9/2001). If you need earlier dates, lower 10 to 9 or less.</p> <pre><code>import re, sys, time regex = re.compile(r'(\d{10,})') def convert(unixtime): return time.strftime("%Y%m%d", time.gmtime(unixtime)) for line in open(sys.argv[1]): sys.stdout.write(regex.sub(lambda m: convert(int(m.group(0))), line)) </code></pre> <p>EDIT: Cleaned up the code.</p> <p><strong>Sample Input</strong></p> <pre><code>foo,1234567890,bar,1243310263 cat,1243310263,pants,1234567890 baz,987654321,raz,1 </code></pre> <p><strong>Output</strong></p> <pre><code>foo,20090213,bar,20090526 cat,20090526,pants,20090213 baz,987654321,raz,1 # not converted (too short to be a recent) </code></pre>
0
2009-05-26T03:55:32Z
[ "python", "regex", "timestamp" ]
Regex Subtitution in Python
908,739
<p>I have a CSV file with several entries, and each entry has 2 unix timestamp formatted dates.</p> <p>I have a method called <code>convert()</code>, which takes in the timestamp and converts it to <code>YYYYMMDD</code>.</p> <p>Now, since I have 2 timestamps in each line, how would I replace each one with the new value?</p> <p>EDIT: Just to clarify, I would like to convert each occurrence of the timestamp into the <code>YYYYMMDD</code> format. This is what is bugging me, as <code>re.findall()</code> returns a list.</p>
2
2009-05-26T02:48:22Z
909,261
<p>Not able to comment your question, but did you take a look at the CSV module of python? <a href="http://docs.python.org/library/csv.html#module-csv" rel="nofollow">http://docs.python.org/library/csv.html#module-csv</a></p>
1
2009-05-26T06:55:48Z
[ "python", "regex", "timestamp" ]
How can I mine an XML document with awk, Perl, or Python?
909,062
<p>I have a XML file with the following data format:</p> <pre><code>&lt;net NetName="abc" attr1="123" attr2="234" attr3="345".../&gt; &lt;net NetName="cde" attr1="456" attr2="567" attr3="678".../&gt; .... </code></pre> <p>Can anyone tell me how could I data mine the XML file using an awk one-liner? For example, I would like to know attr3 of abc. It will return 345 to me.</p>
3
2009-05-26T05:35:57Z
909,076
<p>In general, <a href="http://stackoverflow.com/questions/701166/can-you-provide-some-examples-of-why-it-is-hard-to-parse-xml-and-html-with-a-rege">you don't</a>. XML/HTML parsing is hard enough without trying to do it concisely, and while you may be able to hack together a solution that succeeds with a limited subset of XML, eventually it will break.</p> <p>Besides, <a href="http://stackoverflow.com/questions/773340/can-you-provide-an-example-of-parsing-html-with-your-favorite-parser">there are many great languages with great XML parsers already written</a>, so why not use one of them and make your life easier?</p> <p>I don't know whether or not there's an XML parser built for awk, but I'm afraid that if you want to parse XML with awk you're going to get a lot of "hammers are for nails, screwdrivers are for screws" answers. I'm sure it can be done, but it's probably going to be easier for you to write something quick in Perl that uses XML::Simple (my personal favorite) or some other XML parsing module.</p> <p>Just for completeness, I'd like to note that if your snippet is an example of the entire file, it is not valid XML. Valid XML should have start and end tags, like so:</p> <pre><code>&lt;netlist&gt; &lt;net NetName="abc" attr1="123" attr2="234" attr3="345".../&gt; &lt;net NetName="cde" attr1="456" attr2="567" attr3="678".../&gt; .... &lt;/netlist&gt; </code></pre> <p>I'm sure invalid XML has its uses, but some XML parsers may whine about it, so unless you're dead set on using an awk one-liner to try to half-ass "parse" your "XML," you may want to consider making your XML valid.</p> <p>In response to your edits, I still won't do it as a one-liner, but here's a Perl script that you can use:</p> <pre><code>#!/usr/bin/perl use strict; use warnings; use XML::Simple; sub usage { die "Usage: $0 [NetName] ([attr])\n"; } my $file = XMLin("file.xml", KeyAttr =&gt; { net =&gt; 'NetName' }); usage() if @ARGV == 0; exists $file-&gt;{net}{$ARGV[0]} or die "$ARGV[0] does not exist.\n"; if(@ARGV == 2) { exists $file-&gt;{net}{$ARGV[0]}{$ARGV[1]} or die "NetName $ARGV[0] does not have attribute $ARGV[1].\n"; print "$file-&gt;{net}{$ARGV[0]}{$ARGV[1]}.\n"; } elsif(@ARGV == 1) { print "$ARGV[0]:\n"; print " $_ = $file-&gt;{net}{$ARGV[0]}{$_}\n" for keys %{ $file-&gt;{net}{$ARGV[0]} }; } else { usage(); } </code></pre> <p>Run this script from the command line with 1 or 2 arguments. The first argument is the <code>'NetName'</code> you want to look up, and the second is the attribute you want to look up. If no attribute is given, it should just list all the attributes for that <code>'NetName'</code>.</p>
7
2009-05-26T05:47:28Z
[ "python", "xml", "perl", "awk" ]
How can I mine an XML document with awk, Perl, or Python?
909,062
<p>I have a XML file with the following data format:</p> <pre><code>&lt;net NetName="abc" attr1="123" attr2="234" attr3="345".../&gt; &lt;net NetName="cde" attr1="456" attr2="567" attr3="678".../&gt; .... </code></pre> <p>Can anyone tell me how could I data mine the XML file using an awk one-liner? For example, I would like to know attr3 of abc. It will return 345 to me.</p>
3
2009-05-26T05:35:57Z
909,363
<p>I have written a tool called <code>xml_grep2</code>, based on <a href="http://search.cpan.org/dist/XML-LibXML" rel="nofollow">XML::LibXML</a>, the perl interface to <a href="http://xmlsoft.org" rel="nofollow">libxml2</a>.</p> <p>You would find the value you're looking for by doing this:</p> <pre><code>xml_grep2 -t '//net[@NetName="abc"]/@attr3' to_grep.xml </code></pre> <p>The tool can be found at <a href="http://xmltwig.com/tool/" rel="nofollow">http://xmltwig.com/tool/</a></p>
7
2009-05-26T07:23:43Z
[ "python", "xml", "perl", "awk" ]
How can I mine an XML document with awk, Perl, or Python?
909,062
<p>I have a XML file with the following data format:</p> <pre><code>&lt;net NetName="abc" attr1="123" attr2="234" attr3="345".../&gt; &lt;net NetName="cde" attr1="456" attr2="567" attr3="678".../&gt; .... </code></pre> <p>Can anyone tell me how could I data mine the XML file using an awk one-liner? For example, I would like to know attr3 of abc. It will return 345 to me.</p>
3
2009-05-26T05:35:57Z
910,520
<p>xmlgawk can use XML very easily.</p> <pre><code>$ xgawk -lxml 'XMLATTR["NetName"]=="abc"{print XMLATTR["attr3"]}' test.xml </code></pre> <p>This one liner can parse XML and print "345".</p>
5
2009-05-26T12:53:00Z
[ "python", "xml", "perl", "awk" ]
How can I mine an XML document with awk, Perl, or Python?
909,062
<p>I have a XML file with the following data format:</p> <pre><code>&lt;net NetName="abc" attr1="123" attr2="234" attr3="345".../&gt; &lt;net NetName="cde" attr1="456" attr2="567" attr3="678".../&gt; .... </code></pre> <p>Can anyone tell me how could I data mine the XML file using an awk one-liner? For example, I would like to know attr3 of abc. It will return 345 to me.</p>
3
2009-05-26T05:35:57Z
910,614
<p>If you do not have xmlgawk and your XML format is fixed, normal awk can do.</p> <pre><code>$ nawk -F '[ ="]+' '/abc/{for(i=1;i&lt;=NF;i++){if($i=="attr3"){print $(i+1)}}}' test.xml </code></pre> <p>This script can return "345". But I think it is very dangerous because normal awk can not use XML.</p>
2
2009-05-26T13:16:07Z
[ "python", "xml", "perl", "awk" ]
How can I mine an XML document with awk, Perl, or Python?
909,062
<p>I have a XML file with the following data format:</p> <pre><code>&lt;net NetName="abc" attr1="123" attr2="234" attr3="345".../&gt; &lt;net NetName="cde" attr1="456" attr2="567" attr3="678".../&gt; .... </code></pre> <p>Can anyone tell me how could I data mine the XML file using an awk one-liner? For example, I would like to know attr3 of abc. It will return 345 to me.</p>
3
2009-05-26T05:35:57Z
19,667,533
<p>You might try this nifty little script: <a href="http://awk.info/?doc/tools/xmlparse.html" rel="nofollow">http://awk.info/?doc/tools/xmlparse.html</a></p>
0
2013-10-29T19:33:42Z
[ "python", "xml", "perl", "awk" ]
Why is the compiler package discontinued in Python 3?
909,092
<p>I was just pleasantly surprised to came across the documentation of <a href="http://docs.python.org/library/compiler">Python's compiler package</a>, but noticed that it's gone in Python 3.0, without any clear replacement or explanation.</p> <p>I can't seem to find any discussion on python-dev about how this decision was made - does anyone have any insight inot this decision?</p>
29
2009-05-26T05:54:30Z
909,172
<p>I believe the functionality is now built in:</p> <ul> <li><a href="http://docs.python.org/3/library/functions.html#compile">compile</a></li> <li><a href="http://docs.python.org/3.3/library/ast.html">ast</a></li> </ul>
29
2009-05-26T06:24:50Z
[ "python", "compiler-construction", "python-3.x" ]
Python code that needs some overview
909,279
<p>im currently learning python (in the very begining), so I still have some doubts about good code manners and how should I proceed with it.</p> <p>Today I created this code that should random trought 01 to 60 (but is running from 01 to 69)</p> <pre><code>import random dez = ['0', '1', '2', '3', '4', '5', '6'] uni = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] sort = [] while len(sort) &lt;= 5: random.shuffle(dez) random.shuffle(uni) w = random.choice(dez) z = random.choice(uni) chosen = str(w) + str(z) if chosen != "00" and chosen not in sort: sort.append(chosen) print chosen </code></pre> <p>I'm also in doubt how to make the code stop at "60".</p>
1
2009-05-26T07:02:10Z
909,293
<p>You do realize you can write the exact same code in 1 line, right? It is easy using <a href="http://docs.python.org/library/random.html#random.randint" rel="nofollow">randint</a>:</p> <pre><code>&gt;&gt;&gt; [random.randint(1,60) for _ in range(6)] [22, 29, 48, 18, 20, 22] </code></pre> <p>This will give you a list of 6 random <em>integers</em> between 1 and 60. In your code you are creating <em>strings</em> that have these numbers. If you are deliberately creating them as strings, however, you then can do this:</p> <pre><code>&gt;&gt;&gt; [str(random.randint(1,60)) for _ in range(6)] ['55', '54', '15', '46', '42', '37'] </code></pre>
4
2009-05-26T07:05:48Z
[ "python" ]
Python code that needs some overview
909,279
<p>im currently learning python (in the very begining), so I still have some doubts about good code manners and how should I proceed with it.</p> <p>Today I created this code that should random trought 01 to 60 (but is running from 01 to 69)</p> <pre><code>import random dez = ['0', '1', '2', '3', '4', '5', '6'] uni = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] sort = [] while len(sort) &lt;= 5: random.shuffle(dez) random.shuffle(uni) w = random.choice(dez) z = random.choice(uni) chosen = str(w) + str(z) if chosen != "00" and chosen not in sort: sort.append(chosen) print chosen </code></pre> <p>I'm also in doubt how to make the code stop at "60".</p>
1
2009-05-26T07:02:10Z
909,296
<p>you will get no real benefit by shuffling on each loop. Do it once before the loop.</p> <p>choosen isn't a word</p>
0
2009-05-26T07:06:29Z
[ "python" ]
Python code that needs some overview
909,279
<p>im currently learning python (in the very begining), so I still have some doubts about good code manners and how should I proceed with it.</p> <p>Today I created this code that should random trought 01 to 60 (but is running from 01 to 69)</p> <pre><code>import random dez = ['0', '1', '2', '3', '4', '5', '6'] uni = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] sort = [] while len(sort) &lt;= 5: random.shuffle(dez) random.shuffle(uni) w = random.choice(dez) z = random.choice(uni) chosen = str(w) + str(z) if chosen != "00" and chosen not in sort: sort.append(chosen) print chosen </code></pre> <p>I'm also in doubt how to make the code stop at "60".</p>
1
2009-05-26T07:02:10Z
909,302
<p>You can just use </p> <pre><code>random.randrange(1,60) </code></pre>
2
2009-05-26T07:07:45Z
[ "python" ]
Python code that needs some overview
909,279
<p>im currently learning python (in the very begining), so I still have some doubts about good code manners and how should I proceed with it.</p> <p>Today I created this code that should random trought 01 to 60 (but is running from 01 to 69)</p> <pre><code>import random dez = ['0', '1', '2', '3', '4', '5', '6'] uni = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] sort = [] while len(sort) &lt;= 5: random.shuffle(dez) random.shuffle(uni) w = random.choice(dez) z = random.choice(uni) chosen = str(w) + str(z) if chosen != "00" and chosen not in sort: sort.append(chosen) print chosen </code></pre> <p>I'm also in doubt how to make the code stop at "60".</p>
1
2009-05-26T07:02:10Z
2,477,769
<p>To get 6 unique random integers in the range from 1 to 59:</p> <pre><code>sample = random.sample(xrange(1, 60), 6) # -&gt; [8, 34, 16, 28, 46, 39] </code></pre> <p>To get strings:</p> <pre><code>['%02d' % i for i in sample] # -&gt; ['08', '34', '16', '28', '46', '39'] </code></pre>
1
2010-03-19T13:49:53Z
[ "python" ]
Factory for Callback methods - Python TKinter
909,551
<p>Writing a test app to emulate PIO lines, I have a very simple Python/Tk GUI app. Using the numeric Keys 1 to 8 to simulate PIO pins 1 to 8. Press the key down = PIO High, release the Key = PIO goes low. What I need it for is not the problem. I kind of went down a rabbit hole trying to use a factory to create the key press call back functions. </p> <p>Here is some stripped down code:</p> <pre><code>#!usr/bin/env python """ Python + Tk GUI interface to simulate a 8 Pio lines. """ from Tkinter import * def cb_factory(numberic_key): """ Return a call back function for a specific keyboard numeric key (0-9) """ def cb( self, event, key=numberic_key ): bit_val = 1&lt;&lt;numberic_key-1 if int(event.type) == 2 and not (bit_val &amp; self.bitfield): self.bitfield |= bit_val self.message("Key %d Down" % key) elif int(event.type) == 3 and (bit_val &amp; self.bitfield): self.bitfield &amp;= (~bit_val &amp; 0xFF) self.message("Key %d Up" % key) else: # Key repeat return print hex(self.bitfield) self.display_bitfield() return cb class App( Frame ): """ Main TK App class """ cb1 = cb_factory(1) cb2 = cb_factory(2) cb3 = cb_factory(3) cb4 = cb_factory(4) cb5 = cb_factory(5) cb6 = cb_factory(6) cb7 = cb_factory(7) cb8 = cb_factory(8) def __init__(self, parent): "Init" self.parent = parent self.bitfield = 0x00 Frame.__init__(self, parent) self.messages = StringVar() self.messages.set("Initialised") Label( parent, bd=1, relief=SUNKEN, anchor=W, textvariable=self.messages, text="Testing" ).pack(fill=X) self.bf_label = StringVar() self.bf_label.set("0 0 0 0 0 0 0 0") Label( parent, bd=1, relief=SUNKEN, anchor=W, textvariable=self.bf_label, text="Testing" ).pack(fill=X) # This Doesn't work! Get a traceback saying 'cb' expected 2 arguements # but only got 1? # # for x in xrange(1,9): # cb = self.cb_factory(x) # self.parent.bind("&lt;KeyPress-%d&gt;" % x, cb) # self.parent.bind("&lt;KeyRelease-%d&gt;" % x, cb) self.parent.bind("&lt;KeyPress-1&gt;", self.cb1) self.parent.bind("&lt;KeyRelease-1&gt;", self.cb1) self.parent.bind("&lt;KeyPress-2&gt;", self.cb2) self.parent.bind("&lt;KeyRelease-2&gt;", self.cb2) self.parent.bind("&lt;KeyPress-3&gt;", self.cb3) self.parent.bind("&lt;KeyRelease-3&gt;", self.cb3) self.parent.bind("&lt;KeyPress-4&gt;", self.cb4) self.parent.bind("&lt;KeyRelease-4&gt;", self.cb4) self.parent.bind("&lt;KeyPress-5&gt;", self.cb5) self.parent.bind("&lt;KeyRelease-5&gt;", self.cb5) self.parent.bind("&lt;KeyPress-6&gt;", self.cb6) self.parent.bind("&lt;KeyRelease-6&gt;", self.cb6) self.parent.bind("&lt;KeyPress-7&gt;", self.cb7) self.parent.bind("&lt;KeyRelease-7&gt;", self.cb7) self.parent.bind("&lt;KeyPress-8&gt;", self.cb8) self.parent.bind("&lt;KeyRelease-8&gt;", self.cb8) def display_bitfield(self): """ Display the PIO lines (1 for on, 0 for off) """ bin_lst = [] for x in xrange(8): bit = 1 &lt;&lt; x if bit &amp; self.bitfield: bin_lst.append("1") else: bin_lst.append("0") bin_lst.reverse() bin_str = " ".join( bin_lst ) self.bf_label.set( bin_str ) def message( self, msg_txt ): "set" self.messages.set( msg_txt ) def cb_factory(self, numberic_key ): """ Return a call back function for a specific keyboard numeric key (0-9) """ def cb( self, event, key=numberic_key ): bit_val = 1&lt;&lt;numberic_key-1 if int(event.type) == 2: self.bitfield |= bit_val self.message("Key %d Down" % key) else: self.bitfield &amp;= (~bit_val &amp; 0xFF) self.message("Key %d Up" % key) print hex(self.bitfield) self.display_bitfield() return cb ########################################################################## if __name__ == "__main__": root = Tk() root.title("PIO Test") theApp = App( root ) root.mainloop() </code></pre> <p>I finally got some sort of method factory working for the callback but I don't find it very satisfactory. </p> <p>So my question is, can you have a class method factory, that will produce class methods the way I tried (see commented out code and App class method cb_factory())?</p> <p>NOTES: Yes, I know that this app only lets you hold down 4 keys at a time, but that is good enough for my purposes.</p>
1
2009-05-26T08:18:17Z
909,579
<p>cb expects 'self' and 'event'. Maybe it only gets event from the bind?</p>
1
2009-05-26T08:25:04Z
[ "python", "methods", "factory" ]
Factory for Callback methods - Python TKinter
909,551
<p>Writing a test app to emulate PIO lines, I have a very simple Python/Tk GUI app. Using the numeric Keys 1 to 8 to simulate PIO pins 1 to 8. Press the key down = PIO High, release the Key = PIO goes low. What I need it for is not the problem. I kind of went down a rabbit hole trying to use a factory to create the key press call back functions. </p> <p>Here is some stripped down code:</p> <pre><code>#!usr/bin/env python """ Python + Tk GUI interface to simulate a 8 Pio lines. """ from Tkinter import * def cb_factory(numberic_key): """ Return a call back function for a specific keyboard numeric key (0-9) """ def cb( self, event, key=numberic_key ): bit_val = 1&lt;&lt;numberic_key-1 if int(event.type) == 2 and not (bit_val &amp; self.bitfield): self.bitfield |= bit_val self.message("Key %d Down" % key) elif int(event.type) == 3 and (bit_val &amp; self.bitfield): self.bitfield &amp;= (~bit_val &amp; 0xFF) self.message("Key %d Up" % key) else: # Key repeat return print hex(self.bitfield) self.display_bitfield() return cb class App( Frame ): """ Main TK App class """ cb1 = cb_factory(1) cb2 = cb_factory(2) cb3 = cb_factory(3) cb4 = cb_factory(4) cb5 = cb_factory(5) cb6 = cb_factory(6) cb7 = cb_factory(7) cb8 = cb_factory(8) def __init__(self, parent): "Init" self.parent = parent self.bitfield = 0x00 Frame.__init__(self, parent) self.messages = StringVar() self.messages.set("Initialised") Label( parent, bd=1, relief=SUNKEN, anchor=W, textvariable=self.messages, text="Testing" ).pack(fill=X) self.bf_label = StringVar() self.bf_label.set("0 0 0 0 0 0 0 0") Label( parent, bd=1, relief=SUNKEN, anchor=W, textvariable=self.bf_label, text="Testing" ).pack(fill=X) # This Doesn't work! Get a traceback saying 'cb' expected 2 arguements # but only got 1? # # for x in xrange(1,9): # cb = self.cb_factory(x) # self.parent.bind("&lt;KeyPress-%d&gt;" % x, cb) # self.parent.bind("&lt;KeyRelease-%d&gt;" % x, cb) self.parent.bind("&lt;KeyPress-1&gt;", self.cb1) self.parent.bind("&lt;KeyRelease-1&gt;", self.cb1) self.parent.bind("&lt;KeyPress-2&gt;", self.cb2) self.parent.bind("&lt;KeyRelease-2&gt;", self.cb2) self.parent.bind("&lt;KeyPress-3&gt;", self.cb3) self.parent.bind("&lt;KeyRelease-3&gt;", self.cb3) self.parent.bind("&lt;KeyPress-4&gt;", self.cb4) self.parent.bind("&lt;KeyRelease-4&gt;", self.cb4) self.parent.bind("&lt;KeyPress-5&gt;", self.cb5) self.parent.bind("&lt;KeyRelease-5&gt;", self.cb5) self.parent.bind("&lt;KeyPress-6&gt;", self.cb6) self.parent.bind("&lt;KeyRelease-6&gt;", self.cb6) self.parent.bind("&lt;KeyPress-7&gt;", self.cb7) self.parent.bind("&lt;KeyRelease-7&gt;", self.cb7) self.parent.bind("&lt;KeyPress-8&gt;", self.cb8) self.parent.bind("&lt;KeyRelease-8&gt;", self.cb8) def display_bitfield(self): """ Display the PIO lines (1 for on, 0 for off) """ bin_lst = [] for x in xrange(8): bit = 1 &lt;&lt; x if bit &amp; self.bitfield: bin_lst.append("1") else: bin_lst.append("0") bin_lst.reverse() bin_str = " ".join( bin_lst ) self.bf_label.set( bin_str ) def message( self, msg_txt ): "set" self.messages.set( msg_txt ) def cb_factory(self, numberic_key ): """ Return a call back function for a specific keyboard numeric key (0-9) """ def cb( self, event, key=numberic_key ): bit_val = 1&lt;&lt;numberic_key-1 if int(event.type) == 2: self.bitfield |= bit_val self.message("Key %d Down" % key) else: self.bitfield &amp;= (~bit_val &amp; 0xFF) self.message("Key %d Up" % key) print hex(self.bitfield) self.display_bitfield() return cb ########################################################################## if __name__ == "__main__": root = Tk() root.title("PIO Test") theApp = App( root ) root.mainloop() </code></pre> <p>I finally got some sort of method factory working for the callback but I don't find it very satisfactory. </p> <p>So my question is, can you have a class method factory, that will produce class methods the way I tried (see commented out code and App class method cb_factory())?</p> <p>NOTES: Yes, I know that this app only lets you hold down 4 keys at a time, but that is good enough for my purposes.</p>
1
2009-05-26T08:18:17Z
910,510
<p>Here is the amended code, taking into account SpliFF's answer. I find this much more aesthetically pleasing but it bugs me that I don't understand how it works. So, for extra credit, can anyone explain how this does work?</p> <pre><code>#!usr/bin/env python """ Python + Tk GUI interface to simulate a 8 Pio lines. """ from Tkinter import * from pio_handler import * class App( Frame ): """ Main TK App class """ def __init__(self, parent): "Init" self.parent = parent self.bitfield = 0x00 Frame.__init__(self, parent) self.messages = StringVar() self.messages.set("Initialised") Label( parent, bd=1, relief=SUNKEN, anchor=W, textvariable=self.messages, text="Testing" ).pack(fill=X) self.bf_label = StringVar() self.bf_label.set("0 0 0 0 0 0 0 0") Label( parent, bd=1, relief=SUNKEN, anchor=W, textvariable=self.bf_label, text="Testing" ).pack(fill=X) # This is the clever bit! # Use a factory to assign a callback function for keys 1 to 8 for x in xrange(1,9): cb = self.cb_factory(x) self.parent.bind("&lt;KeyPress-%d&gt;" % x, cb) self.parent.bind("&lt;KeyRelease-%d&gt;" % x, cb) def display_bitfield(self): """ Display the PIO lines (1 for on, 0 for off) """ bin_lst = [] for x in xrange(8): bit = 1 &lt;&lt; x if bit &amp; self.bitfield: bin_lst.append("1") else: bin_lst.append("0") bin_lst.reverse() bin_str = " ".join( bin_lst ) self.bf_label.set( bin_str ) def message( self, msg_txt ): "set" self.messages.set( msg_txt ) def cb_factory(self, numeric_key ): """ Return a call back function for a specific keyboard numeric key (0-9) """ def cb( event, key=numeric_key ): bit_val = 1&lt;&lt;numeric_key-1 if int(event.type) == 2: self.bitfield |= bit_val self.message("Key %d Down" % key) else: self.bitfield &amp;= (~bit_val &amp; 0xFF) self.message("Key %d Up" % key) print hex(self.bitfield) self.display_bitfield() return cb ########################################################################## if __name__ == "__main__": root = Tk() root.title("PIO Test") theApp = App( root ) root.mainloop() </code></pre>
0
2009-05-26T12:50:31Z
[ "python", "methods", "factory" ]
Factory for Callback methods - Python TKinter
909,551
<p>Writing a test app to emulate PIO lines, I have a very simple Python/Tk GUI app. Using the numeric Keys 1 to 8 to simulate PIO pins 1 to 8. Press the key down = PIO High, release the Key = PIO goes low. What I need it for is not the problem. I kind of went down a rabbit hole trying to use a factory to create the key press call back functions. </p> <p>Here is some stripped down code:</p> <pre><code>#!usr/bin/env python """ Python + Tk GUI interface to simulate a 8 Pio lines. """ from Tkinter import * def cb_factory(numberic_key): """ Return a call back function for a specific keyboard numeric key (0-9) """ def cb( self, event, key=numberic_key ): bit_val = 1&lt;&lt;numberic_key-1 if int(event.type) == 2 and not (bit_val &amp; self.bitfield): self.bitfield |= bit_val self.message("Key %d Down" % key) elif int(event.type) == 3 and (bit_val &amp; self.bitfield): self.bitfield &amp;= (~bit_val &amp; 0xFF) self.message("Key %d Up" % key) else: # Key repeat return print hex(self.bitfield) self.display_bitfield() return cb class App( Frame ): """ Main TK App class """ cb1 = cb_factory(1) cb2 = cb_factory(2) cb3 = cb_factory(3) cb4 = cb_factory(4) cb5 = cb_factory(5) cb6 = cb_factory(6) cb7 = cb_factory(7) cb8 = cb_factory(8) def __init__(self, parent): "Init" self.parent = parent self.bitfield = 0x00 Frame.__init__(self, parent) self.messages = StringVar() self.messages.set("Initialised") Label( parent, bd=1, relief=SUNKEN, anchor=W, textvariable=self.messages, text="Testing" ).pack(fill=X) self.bf_label = StringVar() self.bf_label.set("0 0 0 0 0 0 0 0") Label( parent, bd=1, relief=SUNKEN, anchor=W, textvariable=self.bf_label, text="Testing" ).pack(fill=X) # This Doesn't work! Get a traceback saying 'cb' expected 2 arguements # but only got 1? # # for x in xrange(1,9): # cb = self.cb_factory(x) # self.parent.bind("&lt;KeyPress-%d&gt;" % x, cb) # self.parent.bind("&lt;KeyRelease-%d&gt;" % x, cb) self.parent.bind("&lt;KeyPress-1&gt;", self.cb1) self.parent.bind("&lt;KeyRelease-1&gt;", self.cb1) self.parent.bind("&lt;KeyPress-2&gt;", self.cb2) self.parent.bind("&lt;KeyRelease-2&gt;", self.cb2) self.parent.bind("&lt;KeyPress-3&gt;", self.cb3) self.parent.bind("&lt;KeyRelease-3&gt;", self.cb3) self.parent.bind("&lt;KeyPress-4&gt;", self.cb4) self.parent.bind("&lt;KeyRelease-4&gt;", self.cb4) self.parent.bind("&lt;KeyPress-5&gt;", self.cb5) self.parent.bind("&lt;KeyRelease-5&gt;", self.cb5) self.parent.bind("&lt;KeyPress-6&gt;", self.cb6) self.parent.bind("&lt;KeyRelease-6&gt;", self.cb6) self.parent.bind("&lt;KeyPress-7&gt;", self.cb7) self.parent.bind("&lt;KeyRelease-7&gt;", self.cb7) self.parent.bind("&lt;KeyPress-8&gt;", self.cb8) self.parent.bind("&lt;KeyRelease-8&gt;", self.cb8) def display_bitfield(self): """ Display the PIO lines (1 for on, 0 for off) """ bin_lst = [] for x in xrange(8): bit = 1 &lt;&lt; x if bit &amp; self.bitfield: bin_lst.append("1") else: bin_lst.append("0") bin_lst.reverse() bin_str = " ".join( bin_lst ) self.bf_label.set( bin_str ) def message( self, msg_txt ): "set" self.messages.set( msg_txt ) def cb_factory(self, numberic_key ): """ Return a call back function for a specific keyboard numeric key (0-9) """ def cb( self, event, key=numberic_key ): bit_val = 1&lt;&lt;numberic_key-1 if int(event.type) == 2: self.bitfield |= bit_val self.message("Key %d Down" % key) else: self.bitfield &amp;= (~bit_val &amp; 0xFF) self.message("Key %d Up" % key) print hex(self.bitfield) self.display_bitfield() return cb ########################################################################## if __name__ == "__main__": root = Tk() root.title("PIO Test") theApp = App( root ) root.mainloop() </code></pre> <p>I finally got some sort of method factory working for the callback but I don't find it very satisfactory. </p> <p>So my question is, can you have a class method factory, that will produce class methods the way I tried (see commented out code and App class method cb_factory())?</p> <p>NOTES: Yes, I know that this app only lets you hold down 4 keys at a time, but that is good enough for my purposes.</p>
1
2009-05-26T08:18:17Z
910,861
<p>In answer to your followup question.</p> <p>I'm not sure which part you don't understand but I'm guessing you don't quite have a handle on how event callbacks work? If so it's pretty easy. Tk runs in a loop looking for events (keypresses, mouseclicks, etc..). When you bind a callback/function to a event you're just telling it to call your function and pass an event object as it's argument. You can then query the event object for more details of what actually occurred. You are currently building seperate callback functions and binding each to 18 key events (down and release on keys 1-9). I think you can rewrite this to simply have cb as a method of your class because the event object will almost certainly contain the keycode as well.</p> <pre><code>class: def __init__(self): for x in xrange(8): self.parent.bind("&lt;KeyPress-%d&gt;" % x, self.keyaction) self.parent.bind("&lt;KeyRelease-%d&gt;" % x, self.keyaction) def keyaction(self, event): key = event.keycode # attribute may have another name, I haven't checked tk docs ... do stuff ... </code></pre> <p>Since we're now using <strong>self</strong>.keyaction as the callback it should get self as its first argument. It gets its keycode from the event object. Now neither value needs to be 'built' into the function when the function is created so the need to actually create different callbacks for each key is removed and the code easier to understand.</p>
1
2009-05-26T14:03:10Z
[ "python", "methods", "factory" ]
on my local Windows machine, how do i write a script to download a comic strip every day and email it to myself?
909,618
<p>on my local Windows machine, how do i write a script to download a comic strip every day and email it to myself?</p> <p>such as<br /> <a href="http://comics.com/peanuts/" rel="nofollow">http://comics.com/peanuts/</a></p> <p><strong>Update</strong>: i know how to download the image as a file. the hard part is how to email it from my local Windows machine.</p>
5
2009-05-26T08:36:43Z
909,643
<p>A quick look on google reveals two command-line programs that you should be able to lash together in a batch file or using the scripting language of your choice.</p> <p><a href="http://www.gnu.org/software/wget/" rel="nofollow">http://www.gnu.org/software/wget/</a> - to do the download</p> <p><a href="http://www.beyondlogic.org/solutions/cmdlinemail/cmdlinemail.htm" rel="nofollow">http://www.beyondlogic.org/solutions/cmdlinemail/cmdlinemail.htm</a> - to send the email</p> <p>You can use the Windows Task Scheduler in control panel to make it run daily.</p> <p>If you are using Python there are surely going to be convenient libraries to do the downloading/emailing parts - browse the official Python site.</p>
3
2009-05-26T08:43:31Z
[ "php", "python", "ruby", "scheduled-tasks" ]
on my local Windows machine, how do i write a script to download a comic strip every day and email it to myself?
909,618
<p>on my local Windows machine, how do i write a script to download a comic strip every day and email it to myself?</p> <p>such as<br /> <a href="http://comics.com/peanuts/" rel="nofollow">http://comics.com/peanuts/</a></p> <p><strong>Update</strong>: i know how to download the image as a file. the hard part is how to email it from my local Windows machine.</p>
5
2009-05-26T08:36:43Z
909,827
<p>Here is perhaps the shortest distance to your goal.</p> <p>It's not simple... you will need to work out how to parse out the image, and the peanuts example seems to be an unpredictable URI, so it might be more difficult than it looks to get the image itself. Your best bet will be to <strong>read the HTML</strong> of the remote webpage, <strong>write a regex</strong> to parse out the image url. Then the <strong>mail function</strong> will work fine, send an HTML email by setting the headers in the mail() function to something like:</p> <pre><code>$headers = "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/html;"; $headers .= " charset=iso-8859-1\r\n"; </code></pre> <p>With the image tags in the mail. This will let you receive emails with all your comic strips placed one after another. Your email software will do the HTTP requests to <strong>download the images for you</strong>, so you can avoid having to attach the images directly.</p>
1
2009-05-26T09:36:28Z
[ "php", "python", "ruby", "scheduled-tasks" ]
on my local Windows machine, how do i write a script to download a comic strip every day and email it to myself?
909,618
<p>on my local Windows machine, how do i write a script to download a comic strip every day and email it to myself?</p> <p>such as<br /> <a href="http://comics.com/peanuts/" rel="nofollow">http://comics.com/peanuts/</a></p> <p><strong>Update</strong>: i know how to download the image as a file. the hard part is how to email it from my local Windows machine.</p>
5
2009-05-26T08:36:43Z
910,031
<p>This depends how precise you want to be. Downloading the entire web page wouldn't be too challenging - using wget, as Earwicker mentions above.</p> <p>If you want the actual image file of the comic downloaded, you would need a bit more in your arsenal. In Python - because that's what I know best - I would imagine you'd need to use urllib to access the page, and then a regular expression to identify the correct part of the page. Therefore you will need to know the exact layout of the page and the absolute URL of the image.</p> <p>For XKCD, for example, the following works:</p> <pre><code>#!/usr/bin/env python import re, urllib root_url = 'http://xkcd.com/' img_url = r'http://imgs.xkcd.com/comics/' dl_dir = '/path/to/download/directory/' # Open the page URL and identify comic image URL page = urllib.urlopen(root_url).read() comic = re.match(r'%s[\w]+?\.(png|jpg)' % img_url, page) # Generate the filename fname = re.sub(img_url, '', comic) # Download the image to the specified download directory try: image = urllib.urlretrieve(comic, '%s%s' % (dl_dir, fname)) except ContentTooShortError: print 'Download interrupted.' else: print 'Download successful.' </code></pre> <p>You can then email it however you feel comfortable.</p>
8
2009-05-26T10:36:14Z
[ "php", "python", "ruby", "scheduled-tasks" ]
on my local Windows machine, how do i write a script to download a comic strip every day and email it to myself?
909,618
<p>on my local Windows machine, how do i write a script to download a comic strip every day and email it to myself?</p> <p>such as<br /> <a href="http://comics.com/peanuts/" rel="nofollow">http://comics.com/peanuts/</a></p> <p><strong>Update</strong>: i know how to download the image as a file. the hard part is how to email it from my local Windows machine.</p>
5
2009-05-26T08:36:43Z
910,102
<p>Configure feedburner on the RSS feed, subscribe yourself to the email alerts?</p>
2
2009-05-26T10:56:17Z
[ "php", "python", "ruby", "scheduled-tasks" ]
on my local Windows machine, how do i write a script to download a comic strip every day and email it to myself?
909,618
<p>on my local Windows machine, how do i write a script to download a comic strip every day and email it to myself?</p> <p>such as<br /> <a href="http://comics.com/peanuts/" rel="nofollow">http://comics.com/peanuts/</a></p> <p><strong>Update</strong>: i know how to download the image as a file. the hard part is how to email it from my local Windows machine.</p>
5
2009-05-26T08:36:43Z
911,727
<p>Emailing it is easy. Pick a library in your favorite language and read the documentation. Send it through your regular email account, or create a new free GMail account for it.</p> <ul> <li><a href="http://docs.python.org/library/email" rel="nofollow">http://docs.python.org/library/email</a></li> <li><a href="http://am.rubyonrails.org/" rel="nofollow">http://am.rubyonrails.org/</a></li> <li><a href="http://us.php.net/manual/en/function.mail.php" rel="nofollow">http://us.php.net/manual/en/function.mail.php</a></li> </ul> <p>Sometimes attachments can indeed be tricky, though. If nothing else, give it a good whirl with whatever library you like most, and post another specific question about any problems you encounter.</p>
1
2009-05-26T17:02:32Z
[ "php", "python", "ruby", "scheduled-tasks" ]
on my local Windows machine, how do i write a script to download a comic strip every day and email it to myself?
909,618
<p>on my local Windows machine, how do i write a script to download a comic strip every day and email it to myself?</p> <p>such as<br /> <a href="http://comics.com/peanuts/" rel="nofollow">http://comics.com/peanuts/</a></p> <p><strong>Update</strong>: i know how to download the image as a file. the hard part is how to email it from my local Windows machine.</p>
5
2009-05-26T08:36:43Z
913,993
<p>It's pretty simple if you already know how to download the file. Once its downloaded create a cronjob that emails it to yourself. </p> <p>Using something like phpmailer would be the easiest way to email it</p> <p><a href="http://phpmailer.codeworxtech.com/index.php?pg=examplebmail" rel="nofollow">http://phpmailer.codeworxtech.com/index.php?pg=examplebmail</a></p>
1
2009-05-27T04:50:41Z
[ "php", "python", "ruby", "scheduled-tasks" ]
Windows Authentication with Python and urllib2
909,658
<p>I want to grab some data off a webpage that requires my windows username and password.</p> <p>So far, I've got:</p> <pre><code>opener = build_opener() try: page = opener.open("http://somepagewhichneedsmywindowsusernameandpassword/") print page except URLError: print "Oh noes." </code></pre> <p>Is this supported by urllib2? I've found <a href="http://code.google.com/p/python-ntlm/">Python NTLM</a>, but that requires me to put my username and password in. Is there any way to just grab the authentication information somehow (e.g. like IE does, or Firefox, if I changed the <code>network.automatic-ntlm-auth.trusted-uris</code> settings).</p> <h1>Edit after msander's answer</h1> <p>So I've now got this:</p> <pre><code># Send a simple "message" over a socket - send the number of bytes first, # then the string. Ditto for receive. def _send_msg(s, m): s.send(struct.pack("i", len(m))) s.send(m) def _get_msg(s): size_data = s.recv(struct.calcsize("i")) if not size_data: return None cb = struct.unpack("i", size_data)[0] return s.recv(cb) def sspi_client(): c = httplib.HTTPConnection("myserver") c.connect() # Do the auth dance. ca = sspi.ClientAuth("NTLM", win32api.GetUserName()) data = None while 1: err, out_buf = ca.authorize(data) # error 400 triggered by this line _send_msg(c.sock, out_buf[0].Buffer) if err==0: break data = _get_msg(c.sock) print "Auth dance complete - sending a few encryted messages" # Assume out data is sensitive - encrypt the message. for data in "Hello from the client".split(): blob, key = ca.encrypt(data) _send_msg(c.sock, blob) _send_msg(c.sock, key) c.sock.close() print "Client completed." </code></pre> <p>which is pretty well ripped from <code>socket_server.py</code> (see <a href="http://lists.adullact.net/pipermail/atelier-dev-commits/2005-August/000316.html">here</a>). But I get an error 400 - bad request. Does anyone have any further ideas?</p> <p>Thanks,</p> <p>Dom</p>
10
2009-05-26T08:48:09Z
909,919
<p>There are several forms of authentication that web sites can use.</p> <ol> <li><p>HTTP Authentication. This where the browser pops up a window for you to enter your username and password. There are two mechanisms: basic and digest. There is an "Authorization" Header that comes along with the page that tells a browser (or a program using urllib2) what to do.</p> <p>In this case, you must configure your urlopener to provide the answers that the authorization header needs to see. You'll need to build either an <a href="http://docs.python.org/library/urllib2.html#urllib2.HTTPBasicAuthHandler" rel="nofollow">HTTPBasicAuthHandler</a> or <a href="http://docs.python.org/library/urllib2.html#urllib2.HTTPDigestAuthHandler" rel="nofollow">HTTPDigestAuthHandler</a>. </p> <p>AuthHandlers require a <a href="http://docs.python.org/library/urllib2.html#urllib2.HTTPPasswordMgr" rel="nofollow">PasswordManager</a>. This password manager could have a hard-coded username and password (very common) or it could be clever and work out your Windows password from some Windows API.</p></li> <li><p>Application Authentication. This is where the web application directs you to a page with a form you fill in with a username and password. In this case, your Python program must use urllib2 to do a POST (a <a href="http://docs.python.org/library/urllib2.html#urllib2.urlopen" rel="nofollow">request with data</a>) where the data is the form filled in properly. The reply to the post usually contains a cookie, which is what allows you further access. You don't need to worry much about the cookie, urllib2 handles this automatically.</p></li> </ol> <p>How do you know which you have? You dump the headers on the response. The response from urllib2.openurl includes all the headers (in <code>page.info()</code>) as well as the page content.</p> <p>Read <a href="http://stackoverflow.com/questions/720867/http-authentication-in-python">http://stackoverflow.com/questions/720867/http-authentication-in-python</a></p> <p><a href="http://stackoverflow.com/questions/112768/how-would-one-log-into-a-phpbb3-forum-through-a-python-script-using-urllib-urlli">http://stackoverflow.com/questions/112768/how-would-one-log-into-a-phpbb3-forum-through-a-python-script-using-urllib-urlli</a></p> <p><a href="http://stackoverflow.com/questions/101742/how-do-you-access-an-authenticated-google-app-engine-service-from-a-non-web-pyt">http://stackoverflow.com/questions/101742/how-do-you-access-an-authenticated-google-app-engine-service-from-a-non-web-pyt</a></p>
-1
2009-05-26T10:08:29Z
[ "python", "urllib2" ]
Windows Authentication with Python and urllib2
909,658
<p>I want to grab some data off a webpage that requires my windows username and password.</p> <p>So far, I've got:</p> <pre><code>opener = build_opener() try: page = opener.open("http://somepagewhichneedsmywindowsusernameandpassword/") print page except URLError: print "Oh noes." </code></pre> <p>Is this supported by urllib2? I've found <a href="http://code.google.com/p/python-ntlm/">Python NTLM</a>, but that requires me to put my username and password in. Is there any way to just grab the authentication information somehow (e.g. like IE does, or Firefox, if I changed the <code>network.automatic-ntlm-auth.trusted-uris</code> settings).</p> <h1>Edit after msander's answer</h1> <p>So I've now got this:</p> <pre><code># Send a simple "message" over a socket - send the number of bytes first, # then the string. Ditto for receive. def _send_msg(s, m): s.send(struct.pack("i", len(m))) s.send(m) def _get_msg(s): size_data = s.recv(struct.calcsize("i")) if not size_data: return None cb = struct.unpack("i", size_data)[0] return s.recv(cb) def sspi_client(): c = httplib.HTTPConnection("myserver") c.connect() # Do the auth dance. ca = sspi.ClientAuth("NTLM", win32api.GetUserName()) data = None while 1: err, out_buf = ca.authorize(data) # error 400 triggered by this line _send_msg(c.sock, out_buf[0].Buffer) if err==0: break data = _get_msg(c.sock) print "Auth dance complete - sending a few encryted messages" # Assume out data is sensitive - encrypt the message. for data in "Hello from the client".split(): blob, key = ca.encrypt(data) _send_msg(c.sock, blob) _send_msg(c.sock, key) c.sock.close() print "Client completed." </code></pre> <p>which is pretty well ripped from <code>socket_server.py</code> (see <a href="http://lists.adullact.net/pipermail/atelier-dev-commits/2005-August/000316.html">here</a>). But I get an error 400 - bad request. Does anyone have any further ideas?</p> <p>Thanks,</p> <p>Dom</p>
10
2009-05-26T08:48:09Z
910,023
<p>Assuming you are writing your client code on Windows and need seamless NTLM authentication then you should read Mark Hammond's <a href="http://mail.python.org/pipermail/python-win32/2008-June/007722.html">Hooking in NTLM</a> post from the python-win32 mailing list which essentially answers the same question. This points at the sspi example code included with the Python Win32 extensions (which are included with <a href="http://www.activestate.com/activepython/">ActivePython</a> and otherwise can be <a href="http://starship.python.net/crew/mhammond/win32/Downloads.html">downloaded here</a>).</p>
13
2009-05-26T10:34:05Z
[ "python", "urllib2" ]
pywikipedia logging in?
909,834
<p>For various reasons I can't use login.py to log me in so I was wondering if anyone knew code so that I could log in to Wikipedia with my script without running a separate script? Cheers!</p>
-1
2009-05-26T09:39:54Z
1,023,283
<p>The answer is going to be simple: you can't use pywikipedia without being able to run <code>login.py</code>.</p> <p>That file not only provides a nice User-interface to try your configuration: it contains all the authentication primitives that we use in the framework to log in. Without logging-in, you can't do much, so no.</p> <p>If you want a more helpful answer, you'll have to be more precise: as in, why you can't use login.py, and what operations you do need to do with Pywikipedia.</p>
1
2009-06-21T05:37:05Z
[ "python", "login", "pywikipedia" ]
pywikipedia logging in?
909,834
<p>For various reasons I can't use login.py to log me in so I was wondering if anyone knew code so that I could log in to Wikipedia with my script without running a separate script? Cheers!</p>
-1
2009-05-26T09:39:54Z
20,646,716
<p>One alternative that worked for me, when I wasn't able to interactively use my remote server (and thus not enter my password), was to copy my credentials to the remote server.</p> <p>By default your remote permissions are stored in <code>~/.pywikibot/pywikibot.lwp</code>, and it has worked for me in the past to log in locally, then copy this <code>.lwp</code> file to the remote server, and then I no longer had to enter my password on the remote server. </p> <p>I don't claim this method to be secure at all, but it is a hack.</p>
0
2013-12-17T23:21:39Z
[ "python", "login", "pywikipedia" ]
Reading "raw" Unicode-strings in Python
909,886
<p>I am quite new to Python so my question might be silly, but even though reading through a lot of threads I didn't find an answer to my question.</p> <p>I have a mixed source document which contains html, xml, latex and other textformats and which I try to get into a latex-only format. </p> <p>Therefore, I have used python to recognise the different commands as regular expresssions and replace them with the adequate latex command. Everything has worked out fine so far.</p> <p>Now I am left with some "raw-type" Unicode signs, such as the greek letters. Unfortunaltly is just about to much to do it by hand. Therefore, I am looking for a way to do this the smart way too. Is there a way for Python to recognise / read them? And how do I tell python to recognise / read e.g. Pi written as a Greek letter?</p> <p>A minimal example of the code I use is:</p> <pre><code>fh = open('SOURCE_DOCUMENT','r') stuff = fh.read() fh.close() new_stuff = re.sub('READ','REPLACE',stuff) fh = open('LATEX_DOCUMENT','w') fh.write(new_stuff) fh.close() </code></pre> <p>I am not sure whether it is an important information or not, but I am using Python 2.6 running on windows. </p> <p>I would be really glad, if someone might be able to give me hint, at least where to find the according information or how this might work. Or whether I am completely wrong, and Python can't do this job ...</p> <p>Many thanks in advance.<br /> Cheers,<br /> Britta</p>
1
2009-05-26T09:54:22Z
909,921
<p>You talk of ``raw'' Unicode strings. What does that mean? Unicode itself is not an encoding, but there are different encodings to store Unicode characters (read <a href="http://www.joelonsoftware.com/articles/Unicode.html" rel="nofollow">this post</a> by Joel).</p> <p>The <a href="http://docs.python.org/3.0/library/functions.html#open" rel="nofollow">open</a> function in Python 3.0 takes an optional <code>encoding</code> argument that lets you specify the encoding, e.g. UTF-8 (a very common way to encode Unicode). In Python 2.x, have a look at the <a href="http://docs.python.org/library/codecs.html" rel="nofollow">codecs</a> module, which also provides an <a href="http://docs.python.org/library/codecs.html#codecs.open" rel="nofollow">open</a> function that allows specifying the encoding of the file.</p> <p><strong>Edit:</strong> alternatively, why not just let those poor characters be, and specify the encoding of your LaTeX file at the top:</p> <pre><code>\usepackage[utf8]{inputenc} </code></pre> <p>(I never tried this, but I figure it should work. You <a href="http://termos.vemod.net/how-to-use-utf-8-encoding-with-latex" rel="nofollow">may</a> need to replace <code>utf8</code> by <code>utf8x</code>, though)</p>
3
2009-05-26T10:09:09Z
[ "python", "string", "unicode", "readability" ]
Reading "raw" Unicode-strings in Python
909,886
<p>I am quite new to Python so my question might be silly, but even though reading through a lot of threads I didn't find an answer to my question.</p> <p>I have a mixed source document which contains html, xml, latex and other textformats and which I try to get into a latex-only format. </p> <p>Therefore, I have used python to recognise the different commands as regular expresssions and replace them with the adequate latex command. Everything has worked out fine so far.</p> <p>Now I am left with some "raw-type" Unicode signs, such as the greek letters. Unfortunaltly is just about to much to do it by hand. Therefore, I am looking for a way to do this the smart way too. Is there a way for Python to recognise / read them? And how do I tell python to recognise / read e.g. Pi written as a Greek letter?</p> <p>A minimal example of the code I use is:</p> <pre><code>fh = open('SOURCE_DOCUMENT','r') stuff = fh.read() fh.close() new_stuff = re.sub('READ','REPLACE',stuff) fh = open('LATEX_DOCUMENT','w') fh.write(new_stuff) fh.close() </code></pre> <p>I am not sure whether it is an important information or not, but I am using Python 2.6 running on windows. </p> <p>I would be really glad, if someone might be able to give me hint, at least where to find the according information or how this might work. Or whether I am completely wrong, and Python can't do this job ...</p> <p>Many thanks in advance.<br /> Cheers,<br /> Britta</p>
1
2009-05-26T09:54:22Z
910,046
<p>You need to determine the "encoding" of the input document. Unicode can encode millions of characters but files can only story 8-bit values (0-255). So the Unicode text must be encoded in some way.</p> <p>If the document is XML, it should be in the first line (encoding="..."; "utf-8" is the default if there is no "encoding" field). For HTML, look for "charset".</p> <p>If all else fails, open the document in an editor where you can set the encoding (<a href="http://www.jedit.org/" rel="nofollow">jEdit</a>, for example). Try them until the text looks right. Then use this value as the <code>encoding</code> parameter for <code>codecs.open()</code> in Python.</p>
0
2009-05-26T10:39:30Z
[ "python", "string", "unicode", "readability" ]
Reading "raw" Unicode-strings in Python
909,886
<p>I am quite new to Python so my question might be silly, but even though reading through a lot of threads I didn't find an answer to my question.</p> <p>I have a mixed source document which contains html, xml, latex and other textformats and which I try to get into a latex-only format. </p> <p>Therefore, I have used python to recognise the different commands as regular expresssions and replace them with the adequate latex command. Everything has worked out fine so far.</p> <p>Now I am left with some "raw-type" Unicode signs, such as the greek letters. Unfortunaltly is just about to much to do it by hand. Therefore, I am looking for a way to do this the smart way too. Is there a way for Python to recognise / read them? And how do I tell python to recognise / read e.g. Pi written as a Greek letter?</p> <p>A minimal example of the code I use is:</p> <pre><code>fh = open('SOURCE_DOCUMENT','r') stuff = fh.read() fh.close() new_stuff = re.sub('READ','REPLACE',stuff) fh = open('LATEX_DOCUMENT','w') fh.write(new_stuff) fh.close() </code></pre> <p>I am not sure whether it is an important information or not, but I am using Python 2.6 running on windows. </p> <p>I would be really glad, if someone might be able to give me hint, at least where to find the according information or how this might work. Or whether I am completely wrong, and Python can't do this job ...</p> <p>Many thanks in advance.<br /> Cheers,<br /> Britta</p>
1
2009-05-26T09:54:22Z
910,051
<p>Please, first, read this:</p> <p><a href="http://www.joelonsoftware.com/articles/Unicode.html" rel="nofollow">The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)</a></p> <p>Then, come back and ask questions.</p>
1
2009-05-26T10:42:40Z
[ "python", "string", "unicode", "readability" ]
Changing a get request to a post in python?
909,929
<blockquote> <p>en.wikipedia.org/w/api.php?action=login&amp;lgname=user&amp;lgpassword=password</p> </blockquote> <p>But it doesn't work because it is a get request. What would the the post request version of this?</p> <p>Cheers!</p>
0
2009-05-26T10:11:19Z
909,958
<p>The variables for a POST request are in the HTTP headers, not in the URL. Check <a href="http://docs.python.org/library/urllib.html" rel="nofollow">urllib</a>.</p> <p>edit: Try this (i got it from <a href="http://www.voidspace.org.uk/python/articles/urllib2.shtml" rel="nofollow">here</a>):</p> <pre><code>import urllib import urllib2 url = 'en.wikipedia.org/w/api.php' values = {'action' : 'login', 'lgname' : 'user', 'password' : 'password' } data = urllib.urlencode(values) req = urllib2.Request(url, data) response = urllib2.urlopen(req) the_page = response.read() </code></pre>
3
2009-05-26T10:17:23Z
[ "python", "forms", "post", "get" ]
Changing a get request to a post in python?
909,929
<blockquote> <p>en.wikipedia.org/w/api.php?action=login&amp;lgname=user&amp;lgpassword=password</p> </blockquote> <p>But it doesn't work because it is a get request. What would the the post request version of this?</p> <p>Cheers!</p>
0
2009-05-26T10:11:19Z
909,975
<p>Since your sample is in PHP, use $_REQUEST, this holds the contents of both $_GET and $_POST. </p>
0
2009-05-26T10:23:00Z
[ "python", "forms", "post", "get" ]
Changing a get request to a post in python?
909,929
<blockquote> <p>en.wikipedia.org/w/api.php?action=login&amp;lgname=user&amp;lgpassword=password</p> </blockquote> <p>But it doesn't work because it is a get request. What would the the post request version of this?</p> <p>Cheers!</p>
0
2009-05-26T10:11:19Z
910,024
<pre><code>params = urllib.urlencode({'action' : 'login', 'lgname' : 'user', 'lgpassword' : 'password'}) response = urllib.urlopen("http://en.wikipedia.org/w/api.php", params) </code></pre> <p>info about urllib can be found <a href="http://docs.python.org/library/urllib.html" rel="nofollow">here</a>.</p>
2
2009-05-26T10:34:21Z
[ "python", "forms", "post", "get" ]
Python MemoryError - how can I force object deletion
910,153
<p>I have a program that process several files, and for each file a report is generated. The report generating part is a separate function that takes a filename, then returns. During report generation, intermediate parts are cached in memory, as they may be used for several parts of the report, to avoid recalculating.</p> <p>When I run this program on all files in a directory, it will run for a while, then crash with a MemoryError. If I then rerun it on the same directory, it will skip all files that it successfully created a report for, and continue on. It will process a couple of files before crashing again.</p> <p>Now, why isn't all resources cleared, or marked at least for garbage collection, after the method call that generates the report? There are no instances leaving, and I am not using any global objects, and after each file processing, all open files are closed.</p> <p>Are there ways for me to verify that there is no extra references to an object? Is there a way to force garbage collection in Python?</p> <p>A bit more detail about the implementation and cache. Each report has several elements in it, each element can then rely on different computations, each computation can depend on other computations. If one computation is already done, I don't want to do it again (most of these are expensive).</p> <p>Here is an abbreviated version off the cache:</p> <pre><code>class MathCache: def __init__(self): self.cache = {} def get(data_provider): if not data_provider.id in self.cache: self.cache[data_provider.id] = data_provider.get_value(self) return self.cache[data_provider.id] </code></pre> <p>An instance of it is created, and then passed to each element in the report. This instance is only kept in a local reference in the report creation method.</p> <p>All data_providers inherit from a common class that serves to make a unique id for the instance based on a hash off constructor arguments and class name. I pass on the MathCache as the data_provider itself may rely on other calculations.</p>
0
2009-05-26T11:11:40Z
910,162
<p>You should check out the gc module: <a href="http://docs.python.org/library/gc.html#module-gc" rel="nofollow">http://docs.python.org/library/gc.html#module-gc</a>. </p>
3
2009-05-26T11:13:21Z
[ "python", "memory", "resources", "garbage-collection" ]
Resize fields in Django Admin
910,169
<p>Django tends to fill up horizontal space when adding or editing entries on the admin, but, in some cases, is a real waste of space, when, i.e., editing a date field, 8 characters wide, or a CharField, also 6 or 8 chars wide, and then the edit box goes up to 15 or 20 chars.</p> <p>How can I tell the admin how wide a textbox should be, or the height of a TextField edit box?</p>
77
2009-05-26T11:16:16Z
911,915
<p>You can set arbitrary HTML attributes on a widget using its <a href="http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs">"attrs" property</a>.</p> <p>You can do this in the Django admin using formfield_for_dbfield:</p> <pre><code>class MyModelAdmin(admin.ModelAdmin): def formfield_for_dbfield(self, db_field, **kwargs): field = super(ContentAdmin, self).formfield_for_dbfield(db_field, **kwargs) if db_field.name == 'somefield': field.widget.attrs['class'] = 'someclass ' + field.widget.attrs.get('class', '') return field </code></pre> <p>or with a custom Widget subclass and the <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_overrides">formfield_overrides dictionary</a>:</p> <pre><code>class DifferentlySizedTextarea(forms.Textarea): def __init__(self, *args, **kwargs): attrs = kwargs.setdefault('attrs', {}) attrs.setdefault('cols', 80) attrs.setdefault('rows', 5) super(DifferentlySizedTextarea, self).__init__(*args, **kwargs) class MyModelAdmin(admin.ModelAdmin): formfield_overrides = { models.TextField: {'widget': DifferentlySizedTextarea}} </code></pre>
40
2009-05-26T17:57:49Z
[ "python", "django", "django-models", "django-admin" ]
Resize fields in Django Admin
910,169
<p>Django tends to fill up horizontal space when adding or editing entries on the admin, but, in some cases, is a real waste of space, when, i.e., editing a date field, 8 characters wide, or a CharField, also 6 or 8 chars wide, and then the edit box goes up to 15 or 20 chars.</p> <p>How can I tell the admin how wide a textbox should be, or the height of a TextField edit box?</p>
77
2009-05-26T11:16:16Z
912,661
<p>A quick and dirty option is to simply provide a custom template for the model in question. </p> <p>If you create a template named <code>admin/&lt;app label&gt;/&lt;class name&gt;/change_form.html</code> then the admin will use that template instead of the default. That is, if you've got a model named <code>Person</code> in an app named <code>people</code>, you'd create a template named <code>admin/people/person/change_form.html</code>.</p> <p>All the admin templates have an <code>extrahead</code> block you can override to place stuff in the <code>&lt;head&gt;</code>, and the final piece of the puzzle is the fact that every field has an HTML id of <code>id_&lt;field-name&gt;</code>.</p> <p>So, you could put something like the following in your template:</p> <pre><code>{% extends "admin/change_form.html" %} {% block extrahead %} {{ block.super }} &lt;style type="text/css"&gt; #id_my_field { width: 100px; } &lt;/style&gt; {% endblock %} </code></pre>
19
2009-05-26T20:45:00Z
[ "python", "django", "django-models", "django-admin" ]
Resize fields in Django Admin
910,169
<p>Django tends to fill up horizontal space when adding or editing entries on the admin, but, in some cases, is a real waste of space, when, i.e., editing a date field, 8 characters wide, or a CharField, also 6 or 8 chars wide, and then the edit box goes up to 15 or 20 chars.</p> <p>How can I tell the admin how wide a textbox should be, or the height of a TextField edit box?</p>
77
2009-05-26T11:16:16Z
913,565
<p>If you want to change the attributes on a per-field instance, you can add the "attrs" property directly in to your form entries.</p> <p>for example:</p> <pre><code>class BlogPostForm(forms.ModelForm): title = forms.CharField(label='Title:', max_length=128) body = forms.CharField(label='Post:', max_length=2000, widget=forms.Textarea(attrs={'rows':'5', 'cols': '5'})) class Meta: model = BlogPost fields = ('title', 'body') </code></pre> <p>The "attrs" property basically passes along the HTML markup that will adjust the form field. Each entry is a tuple of the attribute you would like to override and the value you would like to override it with. You can enter as many attributes as you like as long as you separate each tuple with a comma.</p>
9
2009-05-27T01:36:50Z
[ "python", "django", "django-models", "django-admin" ]
Resize fields in Django Admin
910,169
<p>Django tends to fill up horizontal space when adding or editing entries on the admin, but, in some cases, is a real waste of space, when, i.e., editing a date field, 8 characters wide, or a CharField, also 6 or 8 chars wide, and then the edit box goes up to 15 or 20 chars.</p> <p>How can I tell the admin how wide a textbox should be, or the height of a TextField edit box?</p>
77
2009-05-26T11:16:16Z
1,251,864
<p>The best way I found is something like this:</p> <pre><code>class NotificationForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(NotificationForm, self).__init__(*args, **kwargs) self.fields['content'].widget.attrs['cols'] = 80 self.fields['content'].widget.attrs['rows'] = 15 self.fields['title'].widget.attrs['size'] = 50 class Meta: model = Notification </code></pre> <p>Its much better for ModelForm than overriding fields with different widgets, as it preserves <code>name</code> and <code>help_text</code> attributes and also default values of model fields, so you don't have to copy them to your form. </p>
6
2009-08-09T17:58:57Z
[ "python", "django", "django-models", "django-admin" ]
Resize fields in Django Admin
910,169
<p>Django tends to fill up horizontal space when adding or editing entries on the admin, but, in some cases, is a real waste of space, when, i.e., editing a date field, 8 characters wide, or a CharField, also 6 or 8 chars wide, and then the edit box goes up to 15 or 20 chars.</p> <p>How can I tell the admin how wide a textbox should be, or the height of a TextField edit box?</p>
77
2009-05-26T11:16:16Z
1,368,252
<p>It's well described in <a href="http://code.djangoproject.com/wiki/NewformsHOWTO#Q%3AHowdoIchangetheattributesforawidgetonafieldinmymodel.">Django FAQ</a>:</p> <p><strong>Q:</strong> How do I change the attributes for a widget on a field in my model?</p> <p><strong>A:</strong> Override the formfield_for_dbfield in the ModelAdmin/StackedInline/TabularInline class </p> <pre><code>class MyOtherModelInline(admin.StackedInline): model = MyOtherModel extra = 1 def formfield_for_dbfield(self, db_field, **kwargs): # This method will turn all TextFields into giant TextFields if isinstance(db_field, models.TextField): return forms.CharField(widget=forms.Textarea(attrs={'cols': 130, 'rows':30, 'class': 'docx'})) return super(MyOtherModelInline, self).formfield_for_dbfield(db_field, **kwargs) </code></pre>
5
2009-09-02T15:02:06Z
[ "python", "django", "django-models", "django-admin" ]
Resize fields in Django Admin
910,169
<p>Django tends to fill up horizontal space when adding or editing entries on the admin, but, in some cases, is a real waste of space, when, i.e., editing a date field, 8 characters wide, or a CharField, also 6 or 8 chars wide, and then the edit box goes up to 15 or 20 chars.</p> <p>How can I tell the admin how wide a textbox should be, or the height of a TextField edit box?</p>
77
2009-05-26T11:16:16Z
1,744,292
<p>You should use <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/">ModelAdmin.formfield_overrides</a>.</p> <p>It is quite easy - in <code>admin.py</code>, define:</p> <pre><code>class YourModelAdmin(admin.ModelAdmin): formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size':'20'})}, models.TextField: {'widget': Textarea(attrs={'rows':4, 'cols':40})}, } admin.site.register(YourModel, YourModelAdmin) </code></pre> <p>Don't forget that you should import appropriate classes -- in this case:</p> <pre><code>from django.forms import TextInput, Textarea from django.db import models </code></pre>
129
2009-11-16T19:24:46Z
[ "python", "django", "django-models", "django-admin" ]
Resize fields in Django Admin
910,169
<p>Django tends to fill up horizontal space when adding or editing entries on the admin, but, in some cases, is a real waste of space, when, i.e., editing a date field, 8 characters wide, or a CharField, also 6 or 8 chars wide, and then the edit box goes up to 15 or 20 chars.</p> <p>How can I tell the admin how wide a textbox should be, or the height of a TextField edit box?</p>
77
2009-05-26T11:16:16Z
2,137,240
<p>I had a similar problem with TextField. I'm using Django 1.0.2 and wanted to change the default value for 'rows' in the associated textarea. formfield_overrides doesn't exist in this version. Overriding formfield_for_dbfield worked but I had to do it for each of my ModelAdmin subclasses or it would result in a recursion error. Eventually, I found that adding the code below to models.py works:</p> <pre><code>from django.forms import Textarea class MyTextField(models.TextField): #A more reasonably sized textarea def formfield(self, **kwargs): kwargs.update( {"widget": Textarea(attrs={'rows':2, 'cols':80})} ) return super(MyTextField, self).formfield(**kwargs) </code></pre> <p>Then use MyTextField instead of TextField when defining your models. I adapted it from <a href="http://stackoverflow.com/questions/430592/djang-admin-charfield-as-textarea/430652#430652">this answer</a> to a similar question.</p>
7
2010-01-26T02:48:20Z
[ "python", "django", "django-models", "django-admin" ]
Resize fields in Django Admin
910,169
<p>Django tends to fill up horizontal space when adding or editing entries on the admin, but, in some cases, is a real waste of space, when, i.e., editing a date field, 8 characters wide, or a CharField, also 6 or 8 chars wide, and then the edit box goes up to 15 or 20 chars.</p> <p>How can I tell the admin how wide a textbox should be, or the height of a TextField edit box?</p>
77
2009-05-26T11:16:16Z
2,138,384
<p>You can always set your fields sizes in a custom stylesheet and tell Django to use that for your ModelAdmin class:</p> <pre><code>class MyModelAdmin(ModelAdmin): class Media: css = {"all": ("my_stylesheet.css",)} </code></pre>
4
2010-01-26T09:11:02Z
[ "python", "django", "django-models", "django-admin" ]
Resize fields in Django Admin
910,169
<p>Django tends to fill up horizontal space when adding or editing entries on the admin, but, in some cases, is a real waste of space, when, i.e., editing a date field, 8 characters wide, or a CharField, also 6 or 8 chars wide, and then the edit box goes up to 15 or 20 chars.</p> <p>How can I tell the admin how wide a textbox should be, or the height of a TextField edit box?</p>
77
2009-05-26T11:16:16Z
8,552,571
<p>Same answer as msdin but with TextInput instead of TextArea:</p> <pre><code>from django.forms import TextInput class ShortTextField(models.TextField): def formfield(self, **kwargs): kwargs.update( {"widget": TextInput(attrs={'size': 10})} ) return super(ShortTextField, self).formfield(**kwargs) </code></pre>
1
2011-12-18T15:04:13Z
[ "python", "django", "django-models", "django-admin" ]
Resize fields in Django Admin
910,169
<p>Django tends to fill up horizontal space when adding or editing entries on the admin, but, in some cases, is a real waste of space, when, i.e., editing a date field, 8 characters wide, or a CharField, also 6 or 8 chars wide, and then the edit box goes up to 15 or 20 chars.</p> <p>How can I tell the admin how wide a textbox should be, or the height of a TextField edit box?</p>
77
2009-05-26T11:16:16Z
15,650,812
<p>for 1.6, using forms I had to specify the attributes of the textarea inside the charfield:</p> <pre><code>test1 = forms.CharField(max_length=400, widget=forms.Textarea( attrs={'rows':'2', 'cols': '10'}), initial='', help_text=helptexts.helptxt['test']) </code></pre>
0
2013-03-27T02:10:18Z
[ "python", "django", "django-models", "django-admin" ]
Resize fields in Django Admin
910,169
<p>Django tends to fill up horizontal space when adding or editing entries on the admin, but, in some cases, is a real waste of space, when, i.e., editing a date field, 8 characters wide, or a CharField, also 6 or 8 chars wide, and then the edit box goes up to 15 or 20 chars.</p> <p>How can I tell the admin how wide a textbox should be, or the height of a TextField edit box?</p>
77
2009-05-26T11:16:16Z
21,766,384
<p><strong>To change the width for a specific field.</strong></p> <p>Made via <a href="https://docs.djangoproject.com/en/1.5/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_form" rel="nofollow">ModelAdmin.get_form</a>:</p> <pre><code>class YourModelAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): form = super(YourModelAdmin, self).get_form(request, obj, **kwargs) form.base_fields['myfield'].widget.attrs['style'] = 'width: 45em;' return form </code></pre>
13
2014-02-13T21:56:18Z
[ "python", "django", "django-models", "django-admin" ]
Problems with python script on web hosting
910,219
<p>I have written a script for Wikipedia &amp; it works fine on my computer, yet when I upload it to my web host(Dreamhost) it doesn't work &amp; says that the user I am trying to log in as is blocked-this is not true, it works on my computer &amp; I#m not blocked. This is the exact error message I get-</p> <pre><code>A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred. /home/tris1601/thewikipediaforum.com/pywikipedia/wikitest.py 35 site = wikipedia.getSite() 36 newpage = wikipedia.Page(site, u"User:Dottydotdot/test") 37 newpage.put(text + "&lt;br&gt;&lt;br&gt;'''Imported from [http://en.wikiquote.org '''Wikiquote'''] by [[User:DottyQuoteBot|'''DottyQuoteBot''']]", u"Testing") 38 39 wikipedia.stopme() newpage = Page{[[User:Dottydotdot/test]]}, newpage.put = &lt;bound method Page.put of Page{[[User:Dottydotdot/test]]}&gt;, text = u'You have so many things in the background that y... could possibly work?" &lt;p&gt; [[Ward Cunningham]] \n' /home/tris1601/thewikipediaforum.com/pywikipedia/wikipedia.py in put(self=Page{[[User:Dottydotdot/test]]}, newtext=u"You have so many things in the background that y...''] by [[User:DottyQuoteBot|'''DottyQuoteBot''']]", comment=u'Testing', watchArticle=None, minorEdit=True, force=False, sysop=False, botflag=True) 1380 1381 # Check blocks 1382 self.site().checkBlocks(sysop = sysop) 1383 1384 # Determine if we are allowed to edit self = Page{[[User:Dottydotdot/test]]}, self.site = &lt;bound method Page.site of Page{[[User:Dottydotdot/test]]}&gt;, ).checkBlocks undefined, sysop = False /home/tris1601/thewikipediaforum.com/pywikipedia/wikipedia.py in checkBlocks(self=wikipedia:en, sysop=False) 4457 if self._isBlocked[index]: 4458 # User blocked 4459 raise UserBlocked('User is blocked in site %s' % self) 4460 4461 def isBlocked(self, sysop = False): global UserBlocked = &lt;class wikipedia.UserBlocked&gt;, self = wikipedia:en UserBlocked: User is blocked in site wikipedia:en args = ('User is blocked in site wikipedia:en',) </code></pre> <p>Any ideas as to why it isn't working?</p> <p>Thanks, much appreciated!</p>
0
2009-05-26T11:32:49Z
910,254
<p>It could be that your host (Dreamhost) is blocked, and not your user.</p>
1
2009-05-26T11:38:47Z
[ "python", "hosting", "pywikipedia" ]
Problems with python script on web hosting
910,219
<p>I have written a script for Wikipedia &amp; it works fine on my computer, yet when I upload it to my web host(Dreamhost) it doesn't work &amp; says that the user I am trying to log in as is blocked-this is not true, it works on my computer &amp; I#m not blocked. This is the exact error message I get-</p> <pre><code>A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred. /home/tris1601/thewikipediaforum.com/pywikipedia/wikitest.py 35 site = wikipedia.getSite() 36 newpage = wikipedia.Page(site, u"User:Dottydotdot/test") 37 newpage.put(text + "&lt;br&gt;&lt;br&gt;'''Imported from [http://en.wikiquote.org '''Wikiquote'''] by [[User:DottyQuoteBot|'''DottyQuoteBot''']]", u"Testing") 38 39 wikipedia.stopme() newpage = Page{[[User:Dottydotdot/test]]}, newpage.put = &lt;bound method Page.put of Page{[[User:Dottydotdot/test]]}&gt;, text = u'You have so many things in the background that y... could possibly work?" &lt;p&gt; [[Ward Cunningham]] \n' /home/tris1601/thewikipediaforum.com/pywikipedia/wikipedia.py in put(self=Page{[[User:Dottydotdot/test]]}, newtext=u"You have so many things in the background that y...''] by [[User:DottyQuoteBot|'''DottyQuoteBot''']]", comment=u'Testing', watchArticle=None, minorEdit=True, force=False, sysop=False, botflag=True) 1380 1381 # Check blocks 1382 self.site().checkBlocks(sysop = sysop) 1383 1384 # Determine if we are allowed to edit self = Page{[[User:Dottydotdot/test]]}, self.site = &lt;bound method Page.site of Page{[[User:Dottydotdot/test]]}&gt;, ).checkBlocks undefined, sysop = False /home/tris1601/thewikipediaforum.com/pywikipedia/wikipedia.py in checkBlocks(self=wikipedia:en, sysop=False) 4457 if self._isBlocked[index]: 4458 # User blocked 4459 raise UserBlocked('User is blocked in site %s' % self) 4460 4461 def isBlocked(self, sysop = False): global UserBlocked = &lt;class wikipedia.UserBlocked&gt;, self = wikipedia:en UserBlocked: User is blocked in site wikipedia:en args = ('User is blocked in site wikipedia:en',) </code></pre> <p>Any ideas as to why it isn't working?</p> <p>Thanks, much appreciated!</p>
0
2009-05-26T11:32:49Z
910,428
<p>I'd start by adding in some debug. Can you capture the output you're sending to wikipedia and the results it resturns? There's probably some more information lodged in there which you can extract to see why it's failing.</p> <p><strong>[Edit]</strong> r.e. debugging - it's hard to give advice given the small snippet you provided. The fact that you've got over 3.5k lines in a single file suggests there's either some rather innefficient coding in there or that the problem wasn't particularly well broken down... which is likely to make debugging more tricky.</p> <p>Having said that, the .put() mentioned in the debug above is almost certainly sending a request to the server. You could start by printing out those requests or bits of the request. To try and piece together what request is being sent and then try doing just those requests and recording the output using python's print command:</p> <pre><code>print "Sending '%s' to server%(my_put_request) </code></pre> <p>...where my_put_request is the bits of data you're sending.</p> <p><strong>[Edit2]</strong> I just spotted that this it's the pywikipedia bot script you're using. The wikipedia article on the bot <a href="http://meta.wikimedia.org/wiki/Using_the_python_wikipediabot#Permission_on_wiki_projects" rel="nofollow">mentions some points on permissions</a> which would support uggedals suggestion of it being an access problem. It's quite possible that wikipedia recognises dreamhosts IP and that someone else has tried doing something bad in the past which has caused them to be blocked in some way.</p>
0
2009-05-26T12:30:42Z
[ "python", "hosting", "pywikipedia" ]