title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
SimpleParse non-deterministic grammar until runtime
1,537,708
<p>I'm working on a basic networking protocol in Python, which should be able to transfer both ASCII strings (read: EOL-terminated) and binary data. For the latter to be possible, I chose to create the grammar such that it contains the number of bytes to come which are going to be binary.</p> <p>For SimpleParse, the grammar would look like this [1] so far:</p> <pre><code>EOL := [\n] IDENTIFIER := [a-zA-Z0-9_-]+ SIZE_INTEGER := [1-9]*[0-9]+ ASCII_VALUE := [^\n\0]+, EOL BINARY_VALUE := .*+ value := (ASCII_VALUE/BINARY_VALUE) eol_attribute := IDENTIFIER, ':', value binary_attribute := IDENTIFIER, [\t], SIZE_INTEGER, ':', value attributes := (eol_attribute/binary_attribute)+ command := IDENTIFIER, EOL command := IDENTIFIER, '{', attributes, '}' </code></pre> <p>The problem is I don't know how to instruct SimpleParse that the following is going to be a chuck of binary data of SIZE_INTEGER bytes <strong>at runtime</strong>.</p> <p>The cause for this is the definition of the terminal BINARY_VALUE which fulfills my needs as it is now, so it cannot be changed.</p> <p>Thanks</p> <p><strong>Edit</strong></p> <p>I suppose the solution would be telling it to stop when it matches the production binary_attribute and let me populate the AST node manually (via socket.recv()), but <strong>how to do that?</strong></p> <p><strong>Edit 2</strong></p> <p>Base64-encoding or similar is not an option.</p> <p>[1] I have't tested it, so I don't know if it practically works, it's only for you to get an idea</p>
1
2009-10-08T13:11:07Z
1,628,368
<p>If you want your application to be portable and reliable I would suggest you pass only standard ASCII characters over the wire.</p> <p>Different computer architectures have different binary representaions, different word sizes, different character sets. There are three approaches to dealing with this.</p> <p>FIrst you can ignore the issues and hope you only ever have to implement the protocol on a single paltform.</p> <p>Two you can go all computer sciency and come up with a "cardinal form" for each possible data type ala CORBA.</p> <p>You can be practical and use the magic of "sprintf" and "scanf" to translate your data to and from plain ASCII characters when sending data over the network.</p> <p>I would also suggest that your protocol includes a message length at or near the begining of the message. The commonest bug in home made protocols is the receiving partner expecting more data than was sent and subsequntly waiting forever for data that was never sent. </p>
1
2009-10-27T01:55:42Z
[ "python", "parsing", "text-parsing" ]
Python multiprocessing and database access with pyodbc "is not safe"?
1,537,809
<p><strong>The Problem:</strong></p> <p>I am getting the following traceback and don't understand what it means or how to fix it:</p> <pre><code>Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "C:\Python26\lib\multiprocessing\forking.py", line 342, in main self = load(from_parent) File "C:\Python26\lib\pickle.py", line 1370, in load return Unpickler(file).load() File "C:\Python26\lib\pickle.py", line 858, in load dispatch[key](self) File "C:\Python26\lib\pickle.py", line 1083, in load_newobj obj = cls.__new__(cls, *args) TypeError: object.__new__(pyodbc.Cursor) is not safe, use pyodbc.Cursor.__new__() </code></pre> <p><strong>The situation:</strong></p> <p>I've got a SQL Server database full of data to be processed. I'm trying to use the multiprocessing module to parallelize the work and take advantage of the multiple cores on my computer. My general class structure is as follows:</p> <ul> <li>MyManagerClass <ul> <li>This is the main class, where the program starts.</li> <li>It creates two multiprocessing.Queue objects, one <code>work_queue</code> and one <code>write_queue</code></li> <li>It also creates and launches the other processes, then waits for them to finish.</li> <li><em>NOTE: this is <strong>not</strong> an extension of multiprocessing.managers.BaseManager()</em> </li> </ul></li> <li>MyReaderClass <ul> <li>This class reads the data from the SQL Server database.</li> <li>It puts items in the <code>work_queue</code>.</li> </ul></li> <li>MyWorkerClass <ul> <li>This is where the work processing happens.</li> <li>It gets items from the <code>work_queue</code> and puts completed items in the <code>write_queue</code>.</li> </ul></li> <li>MyWriterClass <ul> <li>This class is in charge of writing the processed data back to the SQL Server database.</li> <li>It gets items from the <code>write_queue</code>.</li> </ul></li> </ul> <p>The idea is that there will be one manager, one reader, one writer, and many workers.</p> <p><strong>Other details:</strong></p> <p>I get the traceback twice in stderr, so I'm thinking that it happens once for the reader and once for the writer. My worker processes get created fine, but just sit there until I send a KeyboardInterrupt because they have nothing in the <code>work_queue</code>.</p> <p>Both the reader and writer have their own connection to the database, created on initialization.</p> <p><strong>Solution:</strong></p> <p>Thanks to Mark and Ferdinand Beyer for their answers and questions that led to this solution. They rightfully pointed out that the Cursor object is not "pickle-able", which is the method that multiprocessing uses to pass information between processes.</p> <p>The issue with my code was that <code>MyReaderClass(multiprocessing.Process)</code> and <code>MyWriterClass(multiprocessing.Process)</code> both connected to the database in their <code>__init__()</code> methods. I created both these objects (i.e. called their init method) in <code>MyManagerClass</code>, then called <code>start()</code>.</p> <p>So it would create the connection and cursor objects, then try to send them to the child process via pickle. My solution was to move the instantiation of the connection and cursor objects to the run() method, which isn't called until the child process is fully created.</p>
9
2009-10-08T13:29:43Z
1,537,840
<p>The error is raised within the <code>pickle</code> module, so somewhere your DB-Cursor object gets pickled and unpickled (serialized to storage and unserialized to the Python object again).</p> <p>I guess that <code>pyodbc.Cursor</code> does not support pickling. Why should you try to persist the cursor object anyway?</p> <p>Check if you use <code>pickle</code> somewhere in your work chain or if it is used implicitely.</p>
3
2009-10-08T13:36:22Z
[ "python", "sql-server", "multiprocessing", "pickle", "pyodbc" ]
Python multiprocessing and database access with pyodbc "is not safe"?
1,537,809
<p><strong>The Problem:</strong></p> <p>I am getting the following traceback and don't understand what it means or how to fix it:</p> <pre><code>Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "C:\Python26\lib\multiprocessing\forking.py", line 342, in main self = load(from_parent) File "C:\Python26\lib\pickle.py", line 1370, in load return Unpickler(file).load() File "C:\Python26\lib\pickle.py", line 858, in load dispatch[key](self) File "C:\Python26\lib\pickle.py", line 1083, in load_newobj obj = cls.__new__(cls, *args) TypeError: object.__new__(pyodbc.Cursor) is not safe, use pyodbc.Cursor.__new__() </code></pre> <p><strong>The situation:</strong></p> <p>I've got a SQL Server database full of data to be processed. I'm trying to use the multiprocessing module to parallelize the work and take advantage of the multiple cores on my computer. My general class structure is as follows:</p> <ul> <li>MyManagerClass <ul> <li>This is the main class, where the program starts.</li> <li>It creates two multiprocessing.Queue objects, one <code>work_queue</code> and one <code>write_queue</code></li> <li>It also creates and launches the other processes, then waits for them to finish.</li> <li><em>NOTE: this is <strong>not</strong> an extension of multiprocessing.managers.BaseManager()</em> </li> </ul></li> <li>MyReaderClass <ul> <li>This class reads the data from the SQL Server database.</li> <li>It puts items in the <code>work_queue</code>.</li> </ul></li> <li>MyWorkerClass <ul> <li>This is where the work processing happens.</li> <li>It gets items from the <code>work_queue</code> and puts completed items in the <code>write_queue</code>.</li> </ul></li> <li>MyWriterClass <ul> <li>This class is in charge of writing the processed data back to the SQL Server database.</li> <li>It gets items from the <code>write_queue</code>.</li> </ul></li> </ul> <p>The idea is that there will be one manager, one reader, one writer, and many workers.</p> <p><strong>Other details:</strong></p> <p>I get the traceback twice in stderr, so I'm thinking that it happens once for the reader and once for the writer. My worker processes get created fine, but just sit there until I send a KeyboardInterrupt because they have nothing in the <code>work_queue</code>.</p> <p>Both the reader and writer have their own connection to the database, created on initialization.</p> <p><strong>Solution:</strong></p> <p>Thanks to Mark and Ferdinand Beyer for their answers and questions that led to this solution. They rightfully pointed out that the Cursor object is not "pickle-able", which is the method that multiprocessing uses to pass information between processes.</p> <p>The issue with my code was that <code>MyReaderClass(multiprocessing.Process)</code> and <code>MyWriterClass(multiprocessing.Process)</code> both connected to the database in their <code>__init__()</code> methods. I created both these objects (i.e. called their init method) in <code>MyManagerClass</code>, then called <code>start()</code>.</p> <p>So it would create the connection and cursor objects, then try to send them to the child process via pickle. My solution was to move the instantiation of the connection and cursor objects to the run() method, which isn't called until the child process is fully created.</p>
9
2009-10-08T13:29:43Z
1,538,008
<p>Multiprocessing relies on pickling to communicate objects between processes. The pyodbc connection and cursor objects can not be pickled.</p> <pre><code>&gt;&gt;&gt; cPickle.dumps(aCursor) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib64/python2.5/copy_reg.py", line 69, in _reduce_ex raise TypeError, "can't pickle %s objects" % base.__name__ TypeError: can't pickle Cursor objects &gt;&gt;&gt; cPickle.dumps(dbHandle) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib64/python2.5/copy_reg.py", line 69, in _reduce_ex raise TypeError, "can't pickle %s objects" % base.__name__ TypeError: can't pickle Connection objects </code></pre> <p>"It puts items in the work_queue", what items? Is it possible the cursor object is getting passed as well?</p>
6
2009-10-08T14:02:46Z
[ "python", "sql-server", "multiprocessing", "pickle", "pyodbc" ]
Python multiprocessing and database access with pyodbc "is not safe"?
1,537,809
<p><strong>The Problem:</strong></p> <p>I am getting the following traceback and don't understand what it means or how to fix it:</p> <pre><code>Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "C:\Python26\lib\multiprocessing\forking.py", line 342, in main self = load(from_parent) File "C:\Python26\lib\pickle.py", line 1370, in load return Unpickler(file).load() File "C:\Python26\lib\pickle.py", line 858, in load dispatch[key](self) File "C:\Python26\lib\pickle.py", line 1083, in load_newobj obj = cls.__new__(cls, *args) TypeError: object.__new__(pyodbc.Cursor) is not safe, use pyodbc.Cursor.__new__() </code></pre> <p><strong>The situation:</strong></p> <p>I've got a SQL Server database full of data to be processed. I'm trying to use the multiprocessing module to parallelize the work and take advantage of the multiple cores on my computer. My general class structure is as follows:</p> <ul> <li>MyManagerClass <ul> <li>This is the main class, where the program starts.</li> <li>It creates two multiprocessing.Queue objects, one <code>work_queue</code> and one <code>write_queue</code></li> <li>It also creates and launches the other processes, then waits for them to finish.</li> <li><em>NOTE: this is <strong>not</strong> an extension of multiprocessing.managers.BaseManager()</em> </li> </ul></li> <li>MyReaderClass <ul> <li>This class reads the data from the SQL Server database.</li> <li>It puts items in the <code>work_queue</code>.</li> </ul></li> <li>MyWorkerClass <ul> <li>This is where the work processing happens.</li> <li>It gets items from the <code>work_queue</code> and puts completed items in the <code>write_queue</code>.</li> </ul></li> <li>MyWriterClass <ul> <li>This class is in charge of writing the processed data back to the SQL Server database.</li> <li>It gets items from the <code>write_queue</code>.</li> </ul></li> </ul> <p>The idea is that there will be one manager, one reader, one writer, and many workers.</p> <p><strong>Other details:</strong></p> <p>I get the traceback twice in stderr, so I'm thinking that it happens once for the reader and once for the writer. My worker processes get created fine, but just sit there until I send a KeyboardInterrupt because they have nothing in the <code>work_queue</code>.</p> <p>Both the reader and writer have their own connection to the database, created on initialization.</p> <p><strong>Solution:</strong></p> <p>Thanks to Mark and Ferdinand Beyer for their answers and questions that led to this solution. They rightfully pointed out that the Cursor object is not "pickle-able", which is the method that multiprocessing uses to pass information between processes.</p> <p>The issue with my code was that <code>MyReaderClass(multiprocessing.Process)</code> and <code>MyWriterClass(multiprocessing.Process)</code> both connected to the database in their <code>__init__()</code> methods. I created both these objects (i.e. called their init method) in <code>MyManagerClass</code>, then called <code>start()</code>.</p> <p>So it would create the connection and cursor objects, then try to send them to the child process via pickle. My solution was to move the instantiation of the connection and cursor objects to the run() method, which isn't called until the child process is fully created.</p>
9
2009-10-08T13:29:43Z
26,644,234
<p><a href="http://pyodbc.googlecode.com/git-history/c3f6b46d8a4f73722439b4755ef5df42adff81d9/web/docs.html#pyodbc" rel="nofollow">pyodbc</a> has Python DB-API <a href="http://legacy.python.org/dev/peps/pep-0249/#threadsafety" rel="nofollow">threadsafety level 1</a>. This means threads cannot share connections, and it's not threadsafe at all.</p> <p>I don't think underlying thread-safe ODBC drivers make a difference. It's in the Python code as noted by the Pickling error.</p>
1
2014-10-30T02:50:08Z
[ "python", "sql-server", "multiprocessing", "pickle", "pyodbc" ]
Read bytes from string as floats
1,537,862
<p>I've got a python webserver where small binary files are POST:ed. The posted data is represented as strings. I want to examine the contents of these strings. But to do that, I need to convert each 4 bytes to floats (little endian). How do you do that?</p>
1
2009-10-08T13:39:32Z
1,537,884
<p>You use the <a href="http://docs.python.org/library/struct.html" rel="nofollow">struct</a> module:</p> <pre><code>&gt;&gt;&gt; import struct &gt;&gt;&gt; struct.unpack_from("f", "\43\a3\12\32") (8.6198787687447256e-33,) </code></pre>
7
2009-10-08T13:43:19Z
[ "python", "string", "byte" ]
Read bytes from string as floats
1,537,862
<p>I've got a python webserver where small binary files are POST:ed. The posted data is represented as strings. I want to examine the contents of these strings. But to do that, I need to convert each 4 bytes to floats (little endian). How do you do that?</p>
1
2009-10-08T13:39:32Z
1,537,927
<p>The <a href="http://construct.wikispaces.com/" rel="nofollow">construct</a> module might also be a handy way to do this. It should be easy to adapt <a href="http://construct.wikispaces.com/tut-basics" rel="nofollow">this example</a> to your needs:</p> <pre><code># [U]nsigned, [L]ittle endian, 16 bit wide integer (parsing) &gt;&gt;&gt; ULInt16("foo").parse("\x01\x02") 513 </code></pre>
1
2009-10-08T13:50:47Z
[ "python", "string", "byte" ]
Read bytes from string as floats
1,537,862
<p>I've got a python webserver where small binary files are POST:ed. The posted data is represented as strings. I want to examine the contents of these strings. But to do that, I need to convert each 4 bytes to floats (little endian). How do you do that?</p>
1
2009-10-08T13:39:32Z
1,538,312
<p>While <code>struct</code> is best for unpacking collection of "scalar" binary values, when you what you have is a sequence of 4-byte binary floats in a string one after the other, the <a href="http://docs.python.org/library/array.html" rel="nofollow">array</a> module is ideal. Specifically, it's as simple as:</p> <pre><code>import array thefloats = array.array('f', thestring) </code></pre> <p>If only part of <code>thestring</code> contains the sequence of 4-byte binary floats, you can build the array from that part by using the appropriate slice of the string instead of the entire string. The <code>array</code> instance offers most of the functionality of <code>list</code> (plus handy methods to convert to/from strings of bytes and swap between little-endian and big-endian forms if needed), but it's less flexible (only floats can be in the array) and enormously more compact (can take up 3-4 times less memory than a list with the same items).</p>
5
2009-10-08T14:49:02Z
[ "python", "string", "byte" ]
How to redirect and then display errors with Google App Engine
1,538,287
<p>I'm working on a Google App Engine project that collects stories submitted by users.</p> <p>This is how I handle submission errors in the post method of my Request Handler:</p> <pre><code># get the title and content using self.request.get() errors = [] if not title: errors.append("Please enter a title.") if not content: errors.append("Please enter a story.") if not errors: # create the story, save it to the database # redirect to the story's page else: # pass the title and/or content to a template # pass the error message(s) to a template # the same template that displays the submission form is used here </code></pre> <p><b>The problem:</b> since my form sends posts to <b>example.com/createstory.do</b> -- if there are errors I end up redisplaying the form page at that address. </p> <p><b>What I want to happen:</b> redirect the user back the page where they submitted the form: <b>example.com/Share</b>, while at the same time displaying the error messages and redisplaying the submitted form data.</p> <p>What's the easiest way to do this?</p> <p>I know I could just have <b>/Share</b> handle both get and post requests, but I'm looking for a solution that I can use even when doing that wouldn't be an option. </p>
1
2009-10-08T14:44:43Z
1,538,438
<p>You could redirect to /Share including the errors in a GET variable in the URL, if you're absolutely sure you need to use separate URLs. Of course, this makes your URL ugly since it now has all of the error information in it.</p> <p>Another option would be to redirect back to Share and have the errors stored in cookies or in a session variable.</p> <p>Combining either of these with client-side form validation in Javascript before submitting in the first place so the ugly solution isn't hit in most cases might be the best option.</p>
1
2009-10-08T15:08:08Z
[ "python", "google-app-engine" ]
How to redirect and then display errors with Google App Engine
1,538,287
<p>I'm working on a Google App Engine project that collects stories submitted by users.</p> <p>This is how I handle submission errors in the post method of my Request Handler:</p> <pre><code># get the title and content using self.request.get() errors = [] if not title: errors.append("Please enter a title.") if not content: errors.append("Please enter a story.") if not errors: # create the story, save it to the database # redirect to the story's page else: # pass the title and/or content to a template # pass the error message(s) to a template # the same template that displays the submission form is used here </code></pre> <p><b>The problem:</b> since my form sends posts to <b>example.com/createstory.do</b> -- if there are errors I end up redisplaying the form page at that address. </p> <p><b>What I want to happen:</b> redirect the user back the page where they submitted the form: <b>example.com/Share</b>, while at the same time displaying the error messages and redisplaying the submitted form data.</p> <p>What's the easiest way to do this?</p> <p>I know I could just have <b>/Share</b> handle both get and post requests, but I'm looking for a solution that I can use even when doing that wouldn't be an option. </p>
1
2009-10-08T14:44:43Z
1,540,080
<p>There's no 'clean' way of doing this, because you cannot redirect POST requests (and have the redirected request also make a POST). The standard - and cleanest - approach is to have the same URL display the form when fetched with GET, and accept the data when fetched with POST.</p>
1
2009-10-08T20:00:59Z
[ "python", "google-app-engine" ]
QGraphicsView with automatic items placing
1,538,308
<p>I would like to write an asset browser using QGraphicsView. It's a little different from examples using QGraphicsView and QGraphicsItems, because I want only one scrollbar and I want items to move automatically, when the viewport size changes. For example, when viewport width is large enough to display 4 asssets, they should be displayed like this:</p> <pre><code>aaaa aaaa aa </code></pre> <p>but when viewport is shrinked and can only contain 3 in a row, it should display them like this:</p> <pre><code>aaa aaa aaa a </code></pre> <p>I wouldn't like to have to move those asset's by myself and let the graphics view manage them all. Is it somehow possible?</p> <p>I have written once such a thing, but using QWidget and paintEvent, drawing all assets myself and keeping track of how many assets can be displayed in a row. Can it be done simpler with QGraphicsView?</p>
2
2009-10-08T14:48:48Z
1,538,432
<p>QGraphicsView supports layouts. What you have to do is implement your own layout manager, inheriting from QGraphicsLayout.</p> <p>For the layout you require, take a look at the Flow Layout example of Qt. Converting that example will give you a QGraphicsFlowLayout. Add your QGraphicsItems to this layout and set your QGraphicsView's layout to that layout, and that would do the trick.</p>
5
2009-10-08T15:06:32Z
[ "python", "qt", "pyqt", "qgraphicsview" ]
QGraphicsView with automatic items placing
1,538,308
<p>I would like to write an asset browser using QGraphicsView. It's a little different from examples using QGraphicsView and QGraphicsItems, because I want only one scrollbar and I want items to move automatically, when the viewport size changes. For example, when viewport width is large enough to display 4 asssets, they should be displayed like this:</p> <pre><code>aaaa aaaa aa </code></pre> <p>but when viewport is shrinked and can only contain 3 in a row, it should display them like this:</p> <pre><code>aaa aaa aaa a </code></pre> <p>I wouldn't like to have to move those asset's by myself and let the graphics view manage them all. Is it somehow possible?</p> <p>I have written once such a thing, but using QWidget and paintEvent, drawing all assets myself and keeping track of how many assets can be displayed in a row. Can it be done simpler with QGraphicsView?</p>
2
2009-10-08T14:48:48Z
1,538,455
<p>I would use a custom layout to do this. Try to create your custom Layout class that inherits from QGraphicsLayout and manage the way it is placing items.</p>
0
2009-10-08T15:10:41Z
[ "python", "qt", "pyqt", "qgraphicsview" ]
QGraphicsView with automatic items placing
1,538,308
<p>I would like to write an asset browser using QGraphicsView. It's a little different from examples using QGraphicsView and QGraphicsItems, because I want only one scrollbar and I want items to move automatically, when the viewport size changes. For example, when viewport width is large enough to display 4 asssets, they should be displayed like this:</p> <pre><code>aaaa aaaa aa </code></pre> <p>but when viewport is shrinked and can only contain 3 in a row, it should display them like this:</p> <pre><code>aaa aaa aaa a </code></pre> <p>I wouldn't like to have to move those asset's by myself and let the graphics view manage them all. Is it somehow possible?</p> <p>I have written once such a thing, but using QWidget and paintEvent, drawing all assets myself and keeping track of how many assets can be displayed in a row. Can it be done simpler with QGraphicsView?</p>
2
2009-10-08T14:48:48Z
1,538,918
<p>It sounds to me you want a list, not a graphics view. A list can be set to display things wrapping around like you desire. See the <a href="http://doc.trolltech.com/4.5/itemviews-puzzle.html" rel="nofollow">puzzle example</a>, paying attention to the list of puzzle pieces on the left. It looks pretty simple to set up for the case presented.</p> <p>Of course, if you really want it in a graphics view, I suppose you could add a list to the view and use it there.</p>
1
2009-10-08T16:23:17Z
[ "python", "qt", "pyqt", "qgraphicsview" ]
How can I get the name of an object in Python?
1,538,342
<p>Is there any way to get the name of an object in Python? For instance:</p> <pre><code>my_list = [x, y, z] # x, y, z have been previously defined for bla in my_list: print "handling object ", name(bla) # &lt;--- what would go instead of `name`? # do something to bla </code></pre> <p><strong>Edit:</strong> Some context:</p> <p>What I'm actually doing is creating a list of functions that I can specify by the command line.</p> <p>I have:</p> <pre><code>def fun1: pass def fun2 pass def fun3: pass fun_dict = {'fun1': fun1, 'fun2': fun2, 'fun3': fun3} </code></pre> <p>I get the name of the function from the commandline and I want to call the relevant function:</p> <pre><code>func_name = parse_commandline() fun_dict[func_name]() </code></pre> <p>And the reason I want to have the name of the function is because I want to create <code>fun_dict</code> without writing the names of the functions twice, since that seems like a good way to create bugs. What I want to do is:</p> <pre><code>fun_list = [fun1, fun2, fun3] # and I'll add more as the need arises fun_dict = {} [fun_dict[name(t) = t for t in fun_list] # &lt;-- this is where I need the name function </code></pre> <p>This way I only need to write the function names once.</p>
11
2009-10-08T14:54:21Z
1,538,380
<p>Objects do not necessarily have names in python, so you can't get the name. It's not unusual for objects to have a <code>__name__</code> attribute in those cases that they do have a name, but this is not a part of standard python, and most built in types do not have one.</p> <p>When you create a variable, like the x, y, z above then those names just act as "pointers" or "references" to the objects. The objects itself do not know what names you are using for it, and you can not easily (if at all) get the names of all references to an object.</p> <p>Update: However, functions do have a <code>__name__</code> (unless they are lambdas) so, in this case you can do:</p> <pre><code>dict([(t.__name__, t) for t in fun_list]) </code></pre>
17
2009-10-08T14:58:40Z
[ "python", "introspection" ]
How can I get the name of an object in Python?
1,538,342
<p>Is there any way to get the name of an object in Python? For instance:</p> <pre><code>my_list = [x, y, z] # x, y, z have been previously defined for bla in my_list: print "handling object ", name(bla) # &lt;--- what would go instead of `name`? # do something to bla </code></pre> <p><strong>Edit:</strong> Some context:</p> <p>What I'm actually doing is creating a list of functions that I can specify by the command line.</p> <p>I have:</p> <pre><code>def fun1: pass def fun2 pass def fun3: pass fun_dict = {'fun1': fun1, 'fun2': fun2, 'fun3': fun3} </code></pre> <p>I get the name of the function from the commandline and I want to call the relevant function:</p> <pre><code>func_name = parse_commandline() fun_dict[func_name]() </code></pre> <p>And the reason I want to have the name of the function is because I want to create <code>fun_dict</code> without writing the names of the functions twice, since that seems like a good way to create bugs. What I want to do is:</p> <pre><code>fun_list = [fun1, fun2, fun3] # and I'll add more as the need arises fun_dict = {} [fun_dict[name(t) = t for t in fun_list] # &lt;-- this is where I need the name function </code></pre> <p>This way I only need to write the function names once.</p>
11
2009-10-08T14:54:21Z
1,538,399
<p>That's not really possible, as there could be multiple variables that have the same value, or a value might have no variable, or a value might have the same value as a variable only by chance.</p> <p>If you really want to do that, you can use</p> <pre><code>def variable_for_value(value): for n,v in globals().items(): if v == value: return n return None </code></pre> <p>However, it would be better if you would iterate over names in the first place:</p> <pre><code>my_list = ["x", "y", "z"] # x, y, z have been previously defined for name in my_list: print "handling variable ", name bla = globals()[name] # do something to bla </code></pre> <p>&nbsp;</p>
5
2009-10-08T15:01:40Z
[ "python", "introspection" ]
How can I get the name of an object in Python?
1,538,342
<p>Is there any way to get the name of an object in Python? For instance:</p> <pre><code>my_list = [x, y, z] # x, y, z have been previously defined for bla in my_list: print "handling object ", name(bla) # &lt;--- what would go instead of `name`? # do something to bla </code></pre> <p><strong>Edit:</strong> Some context:</p> <p>What I'm actually doing is creating a list of functions that I can specify by the command line.</p> <p>I have:</p> <pre><code>def fun1: pass def fun2 pass def fun3: pass fun_dict = {'fun1': fun1, 'fun2': fun2, 'fun3': fun3} </code></pre> <p>I get the name of the function from the commandline and I want to call the relevant function:</p> <pre><code>func_name = parse_commandline() fun_dict[func_name]() </code></pre> <p>And the reason I want to have the name of the function is because I want to create <code>fun_dict</code> without writing the names of the functions twice, since that seems like a good way to create bugs. What I want to do is:</p> <pre><code>fun_list = [fun1, fun2, fun3] # and I'll add more as the need arises fun_dict = {} [fun_dict[name(t) = t for t in fun_list] # &lt;-- this is where I need the name function </code></pre> <p>This way I only need to write the function names once.</p>
11
2009-10-08T14:54:21Z
1,538,466
<p>Variable names can be found in the globals() and locals() dicts. But they won't give you what you're looking for above. "bla" will contain the value of each item of my_list, not the variable.</p>
0
2009-10-08T15:12:23Z
[ "python", "introspection" ]
How can I get the name of an object in Python?
1,538,342
<p>Is there any way to get the name of an object in Python? For instance:</p> <pre><code>my_list = [x, y, z] # x, y, z have been previously defined for bla in my_list: print "handling object ", name(bla) # &lt;--- what would go instead of `name`? # do something to bla </code></pre> <p><strong>Edit:</strong> Some context:</p> <p>What I'm actually doing is creating a list of functions that I can specify by the command line.</p> <p>I have:</p> <pre><code>def fun1: pass def fun2 pass def fun3: pass fun_dict = {'fun1': fun1, 'fun2': fun2, 'fun3': fun3} </code></pre> <p>I get the name of the function from the commandline and I want to call the relevant function:</p> <pre><code>func_name = parse_commandline() fun_dict[func_name]() </code></pre> <p>And the reason I want to have the name of the function is because I want to create <code>fun_dict</code> without writing the names of the functions twice, since that seems like a good way to create bugs. What I want to do is:</p> <pre><code>fun_list = [fun1, fun2, fun3] # and I'll add more as the need arises fun_dict = {} [fun_dict[name(t) = t for t in fun_list] # &lt;-- this is where I need the name function </code></pre> <p>This way I only need to write the function names once.</p>
11
2009-10-08T14:54:21Z
1,538,772
<p>Note that while, as noted, objects in general do not and cannot know what variables are bound to them, functions defined with <code>def</code> do have names in the <code>__name__</code> attribute (the name used in <code>def</code>). Also if the functions are defined in the same module (as in your example) then <code>globals()</code> will contain a superset of the dictionary you want. </p> <pre><code>def fun1: pass def fun2: pass def fun3: pass fun_dict = {} for f in [fun1, fun2, fun3]: fun_dict[f.__name__] = f </code></pre>
1
2009-10-08T16:03:22Z
[ "python", "introspection" ]
How can I get the name of an object in Python?
1,538,342
<p>Is there any way to get the name of an object in Python? For instance:</p> <pre><code>my_list = [x, y, z] # x, y, z have been previously defined for bla in my_list: print "handling object ", name(bla) # &lt;--- what would go instead of `name`? # do something to bla </code></pre> <p><strong>Edit:</strong> Some context:</p> <p>What I'm actually doing is creating a list of functions that I can specify by the command line.</p> <p>I have:</p> <pre><code>def fun1: pass def fun2 pass def fun3: pass fun_dict = {'fun1': fun1, 'fun2': fun2, 'fun3': fun3} </code></pre> <p>I get the name of the function from the commandline and I want to call the relevant function:</p> <pre><code>func_name = parse_commandline() fun_dict[func_name]() </code></pre> <p>And the reason I want to have the name of the function is because I want to create <code>fun_dict</code> without writing the names of the functions twice, since that seems like a good way to create bugs. What I want to do is:</p> <pre><code>fun_list = [fun1, fun2, fun3] # and I'll add more as the need arises fun_dict = {} [fun_dict[name(t) = t for t in fun_list] # &lt;-- this is where I need the name function </code></pre> <p>This way I only need to write the function names once.</p>
11
2009-10-08T14:54:21Z
1,539,112
<p>Generally when you are wanting to do something like this, you create a class to hold all of these functions and name them with some clear prefix <code>cmd_</code> or the like. You then take the string from the command, and try to get that attribute from the class with the <code>cmd_</code> prefixed to it. Now you only need to add a new function/method to the class, and it's available to your callers. And you can use the doc strings for automatically creating the help text.</p> <p>As described in other answers, you may be able to do the same approach with <code>globals()</code> and regular functions in your module to more closely match what you asked for.</p> <p>Something like this:</p> <pre><code>class Tasks: def cmd_doit(self): # do it here func_name = parse_commandline() try: func = getattr('cmd_' + func_name, Tasks()) except AttributeError: # bad command: exit or whatever func() </code></pre>
0
2009-10-08T16:53:33Z
[ "python", "introspection" ]
How can I get the name of an object in Python?
1,538,342
<p>Is there any way to get the name of an object in Python? For instance:</p> <pre><code>my_list = [x, y, z] # x, y, z have been previously defined for bla in my_list: print "handling object ", name(bla) # &lt;--- what would go instead of `name`? # do something to bla </code></pre> <p><strong>Edit:</strong> Some context:</p> <p>What I'm actually doing is creating a list of functions that I can specify by the command line.</p> <p>I have:</p> <pre><code>def fun1: pass def fun2 pass def fun3: pass fun_dict = {'fun1': fun1, 'fun2': fun2, 'fun3': fun3} </code></pre> <p>I get the name of the function from the commandline and I want to call the relevant function:</p> <pre><code>func_name = parse_commandline() fun_dict[func_name]() </code></pre> <p>And the reason I want to have the name of the function is because I want to create <code>fun_dict</code> without writing the names of the functions twice, since that seems like a good way to create bugs. What I want to do is:</p> <pre><code>fun_list = [fun1, fun2, fun3] # and I'll add more as the need arises fun_dict = {} [fun_dict[name(t) = t for t in fun_list] # &lt;-- this is where I need the name function </code></pre> <p>This way I only need to write the function names once.</p>
11
2009-10-08T14:54:21Z
1,539,123
<p>Here's another way to think about it. Suppose there were a <code>name()</code> function that returned the name of its argument. Given the following code:</p> <pre><code>def f(a): return a b = "x" c = b d = f(c) e = [f(b), f(c), f(d)] </code></pre> <p>What should <code>name(e[2])</code> return, and why?</p>
1
2009-10-08T16:54:37Z
[ "python", "introspection" ]
How can I get the name of an object in Python?
1,538,342
<p>Is there any way to get the name of an object in Python? For instance:</p> <pre><code>my_list = [x, y, z] # x, y, z have been previously defined for bla in my_list: print "handling object ", name(bla) # &lt;--- what would go instead of `name`? # do something to bla </code></pre> <p><strong>Edit:</strong> Some context:</p> <p>What I'm actually doing is creating a list of functions that I can specify by the command line.</p> <p>I have:</p> <pre><code>def fun1: pass def fun2 pass def fun3: pass fun_dict = {'fun1': fun1, 'fun2': fun2, 'fun3': fun3} </code></pre> <p>I get the name of the function from the commandline and I want to call the relevant function:</p> <pre><code>func_name = parse_commandline() fun_dict[func_name]() </code></pre> <p>And the reason I want to have the name of the function is because I want to create <code>fun_dict</code> without writing the names of the functions twice, since that seems like a good way to create bugs. What I want to do is:</p> <pre><code>fun_list = [fun1, fun2, fun3] # and I'll add more as the need arises fun_dict = {} [fun_dict[name(t) = t for t in fun_list] # &lt;-- this is where I need the name function </code></pre> <p>This way I only need to write the function names once.</p>
11
2009-10-08T14:54:21Z
1,539,174
<blockquote> <p>And the reason I want to have the name of the function is because I want to create <code>fun_dict</code> without writing the names of the functions twice, since that seems like a good way to create bugs.</p> </blockquote> <p>For this purpose you have a wonderful <a href="http://docs.python.org/library/functions.html#getattr" rel="nofollow"><code>getattr</code></a> function, that allows you to get an object by known name. So you could do for example:</p> <p><code>funcs.py:</code></p> <pre><code>def func1(): pass def func2(): pass </code></pre> <p><code>main.py:</code></p> <pre><code>import funcs option = command_line_option() getattr(funcs, option)() </code></pre>
1
2009-10-08T17:02:37Z
[ "python", "introspection" ]
How can I get the name of an object in Python?
1,538,342
<p>Is there any way to get the name of an object in Python? For instance:</p> <pre><code>my_list = [x, y, z] # x, y, z have been previously defined for bla in my_list: print "handling object ", name(bla) # &lt;--- what would go instead of `name`? # do something to bla </code></pre> <p><strong>Edit:</strong> Some context:</p> <p>What I'm actually doing is creating a list of functions that I can specify by the command line.</p> <p>I have:</p> <pre><code>def fun1: pass def fun2 pass def fun3: pass fun_dict = {'fun1': fun1, 'fun2': fun2, 'fun3': fun3} </code></pre> <p>I get the name of the function from the commandline and I want to call the relevant function:</p> <pre><code>func_name = parse_commandline() fun_dict[func_name]() </code></pre> <p>And the reason I want to have the name of the function is because I want to create <code>fun_dict</code> without writing the names of the functions twice, since that seems like a good way to create bugs. What I want to do is:</p> <pre><code>fun_list = [fun1, fun2, fun3] # and I'll add more as the need arises fun_dict = {} [fun_dict[name(t) = t for t in fun_list] # &lt;-- this is where I need the name function </code></pre> <p>This way I only need to write the function names once.</p>
11
2009-10-08T14:54:21Z
1,539,517
<p>Use a reverse dict.</p> <pre><code>fun_dict = {'fun1': fun1, 'fun2': fun2, 'fun3': fun3} r_dict = dict(zip(fun_dict.values(), fun_dict.keys())) </code></pre> <p>The reverse dict will map each function reference to the exact name you gave it in fun_dict, which may or may not be the name you used when you defined the function. And, this technique generalizes to other objects, including integers.</p> <p>For extra fun and insanity, you can store the forward and reverse values in the same dict. I wouldn't do that if you were mapping strings to strings, but if you are doing something like function references and strings, it's not too crazy.</p>
1
2009-10-08T18:03:44Z
[ "python", "introspection" ]
How can I get the name of an object in Python?
1,538,342
<p>Is there any way to get the name of an object in Python? For instance:</p> <pre><code>my_list = [x, y, z] # x, y, z have been previously defined for bla in my_list: print "handling object ", name(bla) # &lt;--- what would go instead of `name`? # do something to bla </code></pre> <p><strong>Edit:</strong> Some context:</p> <p>What I'm actually doing is creating a list of functions that I can specify by the command line.</p> <p>I have:</p> <pre><code>def fun1: pass def fun2 pass def fun3: pass fun_dict = {'fun1': fun1, 'fun2': fun2, 'fun3': fun3} </code></pre> <p>I get the name of the function from the commandline and I want to call the relevant function:</p> <pre><code>func_name = parse_commandline() fun_dict[func_name]() </code></pre> <p>And the reason I want to have the name of the function is because I want to create <code>fun_dict</code> without writing the names of the functions twice, since that seems like a good way to create bugs. What I want to do is:</p> <pre><code>fun_list = [fun1, fun2, fun3] # and I'll add more as the need arises fun_dict = {} [fun_dict[name(t) = t for t in fun_list] # &lt;-- this is where I need the name function </code></pre> <p>This way I only need to write the function names once.</p>
11
2009-10-08T14:54:21Z
16,139,159
<p>This one-liner works, for all types of objects, as long as they are in <code>globals()</code> dict, which they should be:</p> <pre><code>def name_of_global_obj(xx): return [objname for objname,oid in globals().items() if id(oid)==id(xx)][0] </code></pre> <p>or, equivalently:</p> <pre><code> def name_of_global_obj(xx): for objname,oid in globals().items(): if oid is xx: return objname </code></pre>
1
2013-04-22T03:53:40Z
[ "python", "introspection" ]
How can I get the name of an object in Python?
1,538,342
<p>Is there any way to get the name of an object in Python? For instance:</p> <pre><code>my_list = [x, y, z] # x, y, z have been previously defined for bla in my_list: print "handling object ", name(bla) # &lt;--- what would go instead of `name`? # do something to bla </code></pre> <p><strong>Edit:</strong> Some context:</p> <p>What I'm actually doing is creating a list of functions that I can specify by the command line.</p> <p>I have:</p> <pre><code>def fun1: pass def fun2 pass def fun3: pass fun_dict = {'fun1': fun1, 'fun2': fun2, 'fun3': fun3} </code></pre> <p>I get the name of the function from the commandline and I want to call the relevant function:</p> <pre><code>func_name = parse_commandline() fun_dict[func_name]() </code></pre> <p>And the reason I want to have the name of the function is because I want to create <code>fun_dict</code> without writing the names of the functions twice, since that seems like a good way to create bugs. What I want to do is:</p> <pre><code>fun_list = [fun1, fun2, fun3] # and I'll add more as the need arises fun_dict = {} [fun_dict[name(t) = t for t in fun_list] # &lt;-- this is where I need the name function </code></pre> <p>This way I only need to write the function names once.</p>
11
2009-10-08T14:54:21Z
21,339,843
<p>If you are looking to get the names of functions or lambdas or other function-like objects that are defined in the interpreter, you can use <code>dill.source.getname</code> from <a href="https://github.com/uqfoundation/dill" rel="nofollow"><code>dill</code></a>. It pretty much looks for the <code>__name__</code> method, but in certain cases it knows other magic for how to find the name... or <strong>a name</strong> for the object. I don't want to get into an argument about finding <strong>the one true name</strong> for a python object, whatever that means.</p> <pre><code>&gt;&gt;&gt; from dill.source import getname &gt;&gt;&gt; &gt;&gt;&gt; def add(x,y): ... return x+y ... &gt;&gt;&gt; squared = lambda x:x**2 &gt;&gt;&gt; &gt;&gt;&gt; print getname(add) 'add' &gt;&gt;&gt; print getname(squared) 'squared' &gt;&gt;&gt; &gt;&gt;&gt; class Foo(object): ... def bar(self, x): ... return x*x+x ... &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; &gt;&gt;&gt; print getname(f.bar) 'bar' &gt;&gt;&gt; &gt;&gt;&gt; woohoo = squared &gt;&gt;&gt; plus = add &gt;&gt;&gt; getname(woohoo) 'squared' &gt;&gt;&gt; getname(plus) 'add' </code></pre>
2
2014-01-24T18:30:51Z
[ "python", "introspection" ]
How can I get the name of an object in Python?
1,538,342
<p>Is there any way to get the name of an object in Python? For instance:</p> <pre><code>my_list = [x, y, z] # x, y, z have been previously defined for bla in my_list: print "handling object ", name(bla) # &lt;--- what would go instead of `name`? # do something to bla </code></pre> <p><strong>Edit:</strong> Some context:</p> <p>What I'm actually doing is creating a list of functions that I can specify by the command line.</p> <p>I have:</p> <pre><code>def fun1: pass def fun2 pass def fun3: pass fun_dict = {'fun1': fun1, 'fun2': fun2, 'fun3': fun3} </code></pre> <p>I get the name of the function from the commandline and I want to call the relevant function:</p> <pre><code>func_name = parse_commandline() fun_dict[func_name]() </code></pre> <p>And the reason I want to have the name of the function is because I want to create <code>fun_dict</code> without writing the names of the functions twice, since that seems like a good way to create bugs. What I want to do is:</p> <pre><code>fun_list = [fun1, fun2, fun3] # and I'll add more as the need arises fun_dict = {} [fun_dict[name(t) = t for t in fun_list] # &lt;-- this is where I need the name function </code></pre> <p>This way I only need to write the function names once.</p>
11
2009-10-08T14:54:21Z
23,258,737
<p>I ran into this page while wondering the same question.</p> <p>As others have noted, it's simple enough to just grab the <code>__name__</code> attribute from a function in order to determine the name of the function. It's marginally trickier with objects that don't have a sane way to determine <code>__name__</code>, i.e. base/primitive objects like basestring instances, ints, longs, etc.</p> <p>Long story short, you could probably use the inspect module to make an educated guess about which one it is, but you would have to probably know what frame you're working in/traverse down the stack to find the right one. But I'd hate to imagine how much fun this would be trying to deal with eval/exec'ed code.</p> <pre><code>% python2 whats_my_name_again.py needle =&gt; ''b'' ['a', 'b'] [] needle =&gt; '&lt;function foo at 0x289d08ec&gt;' ['c'] ['foo'] needle =&gt; '&lt;function bar at 0x289d0bfc&gt;' ['f', 'bar'] [] needle =&gt; '&lt;__main__.a_class instance at 0x289d3aac&gt;' ['e', 'd'] [] needle =&gt; '&lt;function bar at 0x289d0bfc&gt;' ['f', 'bar'] [] % </code></pre> <p>whats_my_name_again.py:</p> <pre><code>#!/usr/bin/env python import inspect class a_class: def __init__(self): pass def foo(): def bar(): pass a = 'b' b = 'b' c = foo d = a_class() e = d f = bar #print('globals', inspect.stack()[0][0].f_globals) #print('locals', inspect.stack()[0][0].f_locals) assert(inspect.stack()[0][0].f_globals == globals()) assert(inspect.stack()[0][0].f_locals == locals()) in_a_haystack = lambda: value == needle and key != 'needle' for needle in (a, foo, bar, d, f, ): print("needle =&gt; '%r'" % (needle, )) print([key for key, value in locals().iteritems() if in_a_haystack()]) print([key for key, value in globals().iteritems() if in_a_haystack()]) foo() </code></pre>
0
2014-04-24T02:29:50Z
[ "python", "introspection" ]
How can I get the name of an object in Python?
1,538,342
<p>Is there any way to get the name of an object in Python? For instance:</p> <pre><code>my_list = [x, y, z] # x, y, z have been previously defined for bla in my_list: print "handling object ", name(bla) # &lt;--- what would go instead of `name`? # do something to bla </code></pre> <p><strong>Edit:</strong> Some context:</p> <p>What I'm actually doing is creating a list of functions that I can specify by the command line.</p> <p>I have:</p> <pre><code>def fun1: pass def fun2 pass def fun3: pass fun_dict = {'fun1': fun1, 'fun2': fun2, 'fun3': fun3} </code></pre> <p>I get the name of the function from the commandline and I want to call the relevant function:</p> <pre><code>func_name = parse_commandline() fun_dict[func_name]() </code></pre> <p>And the reason I want to have the name of the function is because I want to create <code>fun_dict</code> without writing the names of the functions twice, since that seems like a good way to create bugs. What I want to do is:</p> <pre><code>fun_list = [fun1, fun2, fun3] # and I'll add more as the need arises fun_dict = {} [fun_dict[name(t) = t for t in fun_list] # &lt;-- this is where I need the name function </code></pre> <p>This way I only need to write the function names once.</p>
11
2009-10-08T14:54:21Z
30,019,630
<p>As others have mentioned, this is a really tricky question. Solutions to this are not "one size fits all", not even remotely. The difficulty (or ease) is really going to depend on your situation.</p> <p>I have come to this problem on several occasions, but most recently while creating a debugging function. I wanted the function to take some unknown objects as arguments and print their declared names and contents. Getting the contents is easy of course, but the declared name is another story.</p> <p>What follows is some of what I have come up with.</p> <h2>Return function name</h2> <p>Determining the name of a function is really easy as it has the <em>__name__</em> attribute containing the function's declared name.</p> <pre><code>name_of_function = lambda x : x.__name__ def name_of_function(arg): try: return arg.__name__ except AttributeError: pass` </code></pre> <p>Just as an example, if you create the function <code>def test_function(): pass</code>, then <code>copy_function = test_function</code>, then <code>name_of_function(copy_function)</code>, it will return <em>test_function</em>.</p> <h2>Return first matching object name</h2> <ol> <li><p>Check whether the object has a <em>__name__</em> attribute and return it if so (declared functions only). Note that you may remove this test as the name will still be in <code>globals()</code>.</p></li> <li><p>Compare the value of arg with the values of items in <code>globals()</code> and return the name of the first match. Note that I am filtering out names starting with '_'.</p></li> </ol> <p>The result will consist of the name of the first matching object otherwise None.</p> <pre><code>def name_of_object(arg): # check __name__ attribute (functions) try: return arg.__name__ except AttributeError: pass for name, value in globals().items(): if value is arg and not name.startswith('_'): return name </code></pre> <h2>Return all matching object names</h2> <ul> <li>Compare the value of arg with the values of items in <code>globals()</code> and store names in a list. Note that I am filtering out names starting with '_'.</li> </ul> <p>The result will consist of a list (for multiple matches), a string (for a single match), otherwise None. Of course you should adjust this behavior as needed.</p> <pre><code>def names_of_object(arg): results = [n for n, v in globals().items() if v is arg and not n.startswith('_')] return results[0] if len(results) is 1 else results if results else None </code></pre>
1
2015-05-03T21:30:03Z
[ "python", "introspection" ]
How can I get the name of an object in Python?
1,538,342
<p>Is there any way to get the name of an object in Python? For instance:</p> <pre><code>my_list = [x, y, z] # x, y, z have been previously defined for bla in my_list: print "handling object ", name(bla) # &lt;--- what would go instead of `name`? # do something to bla </code></pre> <p><strong>Edit:</strong> Some context:</p> <p>What I'm actually doing is creating a list of functions that I can specify by the command line.</p> <p>I have:</p> <pre><code>def fun1: pass def fun2 pass def fun3: pass fun_dict = {'fun1': fun1, 'fun2': fun2, 'fun3': fun3} </code></pre> <p>I get the name of the function from the commandline and I want to call the relevant function:</p> <pre><code>func_name = parse_commandline() fun_dict[func_name]() </code></pre> <p>And the reason I want to have the name of the function is because I want to create <code>fun_dict</code> without writing the names of the functions twice, since that seems like a good way to create bugs. What I want to do is:</p> <pre><code>fun_list = [fun1, fun2, fun3] # and I'll add more as the need arises fun_dict = {} [fun_dict[name(t) = t for t in fun_list] # &lt;-- this is where I need the name function </code></pre> <p>This way I only need to write the function names once.</p>
11
2009-10-08T14:54:21Z
30,019,808
<p>You define a <code>class</code> and add the Unicode private function insert the <code>class</code> like</p> <pre><code>class example: def __init__(self, name): self.name = name def __unicode__(self): return self.name </code></pre> <p>Of course you have to add extra variable <code>self.name</code> which is the name of the object.</p>
0
2015-05-03T21:48:39Z
[ "python", "introspection" ]
How can I get the name of an object in Python?
1,538,342
<p>Is there any way to get the name of an object in Python? For instance:</p> <pre><code>my_list = [x, y, z] # x, y, z have been previously defined for bla in my_list: print "handling object ", name(bla) # &lt;--- what would go instead of `name`? # do something to bla </code></pre> <p><strong>Edit:</strong> Some context:</p> <p>What I'm actually doing is creating a list of functions that I can specify by the command line.</p> <p>I have:</p> <pre><code>def fun1: pass def fun2 pass def fun3: pass fun_dict = {'fun1': fun1, 'fun2': fun2, 'fun3': fun3} </code></pre> <p>I get the name of the function from the commandline and I want to call the relevant function:</p> <pre><code>func_name = parse_commandline() fun_dict[func_name]() </code></pre> <p>And the reason I want to have the name of the function is because I want to create <code>fun_dict</code> without writing the names of the functions twice, since that seems like a good way to create bugs. What I want to do is:</p> <pre><code>fun_list = [fun1, fun2, fun3] # and I'll add more as the need arises fun_dict = {} [fun_dict[name(t) = t for t in fun_list] # &lt;-- this is where I need the name function </code></pre> <p>This way I only need to write the function names once.</p>
11
2009-10-08T14:54:21Z
39,240,374
<p>Here is my answer, I am also using globals().items()</p> <pre><code> def get_name_of_obj(obj, except_word = ""): for name, item in globals().items(): if item == obj and name != except_word: return name </code></pre> <p>I added except_word because I want to filter off some word used in for loop. If you didn't add it, the keyword in for loop may confuse this function, sometimes the keyword like "each_item" in the following case may show in the function's result, depends on what you have done to your loop.</p> <p>eg.</p> <pre><code> for each_item in [objA, objB, objC]: get_name_of_obj(obj, "each_item") </code></pre> <p>eg.</p> <pre><code> &gt;&gt;&gt; objA = [1, 2, 3] &gt;&gt;&gt; objB = ('a', {'b':'thi is B'}, 'c') &gt;&gt;&gt; for each_item in [objA, objB]: ... get_name_of_obj(each_item) ... 'objA' 'objB' &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; for each_item in [objA, objB]: ... get_name_of_obj(each_item) ... 'objA' 'objB' &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; objC = [{'a1':'a2'}] &gt;&gt;&gt; &gt;&gt;&gt; for item in [objA, objB, objC]: ... get_name_of_obj(item) ... 'objA' 'item' &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; --------- this is no good 'item' &gt;&gt;&gt; for item in [objA, objB]: ... get_name_of_obj(item) ... 'objA' 'item' &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;--------this is no good &gt;&gt;&gt; &gt;&gt;&gt; for item in [objA, objB, objC]: ... get_name_of_obj(item, "item") ... 'objA' 'objB' &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;--------- now it's ok 'objC' &gt;&gt;&gt; </code></pre> <p>Hope this can help.</p>
1
2016-08-31T03:42:47Z
[ "python", "introspection" ]
How to sort all possible words out of a string?
1,538,589
<p>I'm wondering how to proceed with this task, take this string for example "thingsandstuff".</p> <p>How could I generate all possible strings out of this string as to look them up individually against an english dictionary?</p> <p>The goal is to find valid english words in a string that does not contain space.</p> <p>Thanks</p>
1
2009-10-08T15:36:25Z
1,538,637
<p>The brute force approach, i.e. checking every substring, is computationally unfeasible even for strings of middling lengths (a string of length <code>N</code> has <code>O(N**2)</code> substrings). Unless there is a pretty tight bound on the length of strings you care about, that doesn't scale well.</p> <p>To make things more feasible, more knowledge is required -- are you interested in <em>overlapping</em> words (eg 'things' and 'sand' in your example) and/or words which would leave unaccounted for characters (eg 'thing' and 'and' in your example, leaving the intermediate 's' stranded), or you do you want a strict partition of the string into juxtaposed (not overlapping) words with no residue?</p> <p>The latter would be the simplest problem, because the degrees of freedom drop sharply -- essentially to trying to determine a sequence of "breaking points", each between two adjacent characters, that would split the string into words. If that's the case, do you need every possible valid split (i.e. do you need <strong>both</strong> "thing sand" <em>and</em> "things and"), or will any single valid split do, or are there criteria that your split must optimize?</p> <p>If you clarify all of these issues it may be possible to give you more help!</p>
2
2009-10-08T15:44:48Z
[ "python" ]
How to sort all possible words out of a string?
1,538,589
<p>I'm wondering how to proceed with this task, take this string for example "thingsandstuff".</p> <p>How could I generate all possible strings out of this string as to look them up individually against an english dictionary?</p> <p>The goal is to find valid english words in a string that does not contain space.</p> <p>Thanks</p>
1
2009-10-08T15:36:25Z
1,538,666
<p>Another possibility is going the other way around, instead of generating substrings from a string, grab all your candidate words and match them against your string. </p> <p>You can store as a result (start,end) pairs of indexes of the words in the original string.</p> <p>This could be easily done in regex, or, if not performant enough, with str.find(), or if even not performant enough with more complex dictionary index schemes or smarts about what can and can't match (see <a href="http://stackoverflow.com/questions/1538589/how-to-sort-all-possible-words-out-of-a-string/1538799#1538799">Gregg's answer</a> for ideas)</p> <p>Here you have a sample of what I mean</p> <pre><code>candidate = "thingsandstuffmydarlingpretty" words = file('/usr/share/dict/words').read() #This generator calls find twice, it should be rewritten as a normal loop generate_matches = ((candidate.find(word),word) for word in words.split('\n') if candidate.find(word) != -1 and word != '') for match in generate_matches: print "Found %s at (%d,%d)" % (match[1],match[0],match[0] + len(match[1])) </code></pre>
5
2009-10-08T15:49:25Z
[ "python" ]
How to sort all possible words out of a string?
1,538,589
<p>I'm wondering how to proceed with this task, take this string for example "thingsandstuff".</p> <p>How could I generate all possible strings out of this string as to look them up individually against an english dictionary?</p> <p>The goal is to find valid english words in a string that does not contain space.</p> <p>Thanks</p>
1
2009-10-08T15:36:25Z
1,538,687
<p>Well here is my idea </p> <ul> <li>Find all possible strings containing 1 character from the original</li> <li>Find all possible strings containing 2 characters from the original</li> <li>... Same thing up to the length of the original string</li> </ul> <p>Then add all up and go match with your dictionary</p>
0
2009-10-08T15:51:53Z
[ "python" ]
How to sort all possible words out of a string?
1,538,589
<p>I'm wondering how to proceed with this task, take this string for example "thingsandstuff".</p> <p>How could I generate all possible strings out of this string as to look them up individually against an english dictionary?</p> <p>The goal is to find valid english words in a string that does not contain space.</p> <p>Thanks</p>
1
2009-10-08T15:36:25Z
1,538,799
<p>People talk about this as though the Order of the problem is the number of possible substrings. This is incorrect. The correct order of this problem is:</p> <p>O( min ( number-of-words-in-dict, number-of-substring-combinations) * comparison_cost)</p> <p>So, another approach to the problem, to build on Vinko, is to index the heck out of the <em>dictionary</em> (e.g., for each work in the dict, determine the letters in that word, the length of the word, etc). This can speed things up dramatically. As an example, we know that target "queen" can't match "zebra" (no z's!) ( or any word containing z,r,b,a...), and the like. Also, store each word in the dict as a sorted string ('zebra' -> 'aberz') and do "string in string" (longest common substring) matching. 'eenuq' vs 'abarz' (no match). </p> <p>(Note: I am assuming that the order of the letters in the original word don't matter -- it's a 'bag of letters', if they do, then adjust accordingly) </p> <p>If you have lots of words to compare at once, the comparison cost can be lowered further using something like <a href="http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt%5Falgorithm">KMP</a>. </p> <p>(Also, I dove right in, and made some assumptions that Alex didn't, so if they're wrong, then shut my mouth!)</p>
5
2009-10-08T16:06:34Z
[ "python" ]
How to sort all possible words out of a string?
1,538,589
<p>I'm wondering how to proceed with this task, take this string for example "thingsandstuff".</p> <p>How could I generate all possible strings out of this string as to look them up individually against an english dictionary?</p> <p>The goal is to find valid english words in a string that does not contain space.</p> <p>Thanks</p>
1
2009-10-08T15:36:25Z
1,538,805
<p>What if you break it up into syllables and then use those to construct words to compare to your dictionary. It's still a brute force method, but it would surely speed things up a bit.</p>
0
2009-10-08T16:07:27Z
[ "python" ]
How to sort all possible words out of a string?
1,538,589
<p>I'm wondering how to proceed with this task, take this string for example "thingsandstuff".</p> <p>How could I generate all possible strings out of this string as to look them up individually against an english dictionary?</p> <p>The goal is to find valid english words in a string that does not contain space.</p> <p>Thanks</p>
1
2009-10-08T15:36:25Z
1,538,809
<p>I looked at a powerset implementation. Too many possibilities. </p> <p>Try encoding your string and all candidates from your dictionary and see if the candidate from the dictionary <em>could</em> be made from the candidate string. That is, do the letters in the dictionary word appear no more frequently than in your candidate string?</p> <pre><code>from __future__ import with_statement import collections def word_dict(word): d = collections.defaultdict(int) for c in word: d[c] += 1 return d def compare_word_dict(dict_cand, cand): return all(dict_cand[k] &lt;= cand[k] for k in dict_cand) def try_word(candidate): s = word_dict(candidate) dictionary_file = r"h:\words\WORDs(3).txt" i = 0 with open(dictionary_file) as f: for line in f: line = line.strip() dc = word_dict(line) if compare_word_dict(dc,s): print line i += 1 return i print try_word("thingsandstuff") </code></pre> <p>I get 670 words with my dictionary. Seems a bit small. Takes about 3 seconds on 200k words in the dictionary.</p> <p>This works for <a href="http://docs.python.org/library/collections.html" rel="nofollow">python 2.5 and above because of the addition of collections.defaultdict</a>. In python 3.1, <a href="http://docs.python.org/dev/py3k/library/collections.html" rel="nofollow">collections.Counter</a> was added that works like collections.defaultdict(int).</p>
0
2009-10-08T16:08:06Z
[ "python" ]
How to sort all possible words out of a string?
1,538,589
<p>I'm wondering how to proceed with this task, take this string for example "thingsandstuff".</p> <p>How could I generate all possible strings out of this string as to look them up individually against an english dictionary?</p> <p>The goal is to find valid english words in a string that does not contain space.</p> <p>Thanks</p>
1
2009-10-08T15:36:25Z
1,538,836
<p>norving wrote a great article on how to write a spell checker in python.</p> <p><a href="http://norvig.com/spell-correct.html" rel="nofollow">http://norvig.com/spell-correct.html</a></p> <p>it will give you an good idea on how to detect words. (i.e. just go testing each group of chars until you get a valid word... beware that to be deterministic you would need to do the reverse. Test all the string, and then go removing chars at the end. that way you get composite words as they are intended... or not intended, who knows. spaces have a reason :)</p> <p>after that, it's basic CS 101.</p>
1
2009-10-08T16:12:19Z
[ "python" ]
How to sort all possible words out of a string?
1,538,589
<p>I'm wondering how to proceed with this task, take this string for example "thingsandstuff".</p> <p>How could I generate all possible strings out of this string as to look them up individually against an english dictionary?</p> <p>The goal is to find valid english words in a string that does not contain space.</p> <p>Thanks</p>
1
2009-10-08T15:36:25Z
1,539,056
<p>Take a look to <a href="http://translate.google.es/translate?u=http%3A%2F%2Ffortran.blogspot.com%2F2008%2F07%2Fel-melenas-de-cifras-y-letras-no-tena.html&amp;sl=es&amp;tl=en&amp;hl=es&amp;ie=UTF-8" rel="nofollow">this post</a>, it addresses the same problem, both in Python and OCaml, with a solution based in normalizing the strings first instead of doing brute-force search.</p> <p>By the way, the automatic translation removes the indenting, so to get the working Python code you should look at the <a href="http://fortran.blogspot.com/2008/07/el-melenas-de-cifras-y-letras-no-tena.html" rel="nofollow">untranslated Spanish version</a> (that in fact is much proper than the crappy English generated by Google translator)...</p> <p>Edit:</p> <p>Re-reading your question, I understand now that you could want only those words that are unscrambled, right? If so, you don't need to do all the stuff described in the post, just:</p> <pre><code>maxwordlength = max(map(len, english_words)) for i in range(len(word)): for j in range(i+1, min(maxwordlength+i, len(word))): if word[i:j] in english_words: print word[i:j] </code></pre> <p>The complexity should be O(N) now, given that the size of the largest word in English is finite.</p>
0
2009-10-08T16:44:30Z
[ "python" ]
How to sort all possible words out of a string?
1,538,589
<p>I'm wondering how to proceed with this task, take this string for example "thingsandstuff".</p> <p>How could I generate all possible strings out of this string as to look them up individually against an english dictionary?</p> <p>The goal is to find valid english words in a string that does not contain space.</p> <p>Thanks</p>
1
2009-10-08T15:36:25Z
1,539,119
<p>Code:</p> <pre><code>def all_substrings(val): return [val[start:end] for start in range(len(val)) for end in range(start + 1, len(val))] val = "thingsandstuff" for result in all_substrings(val): print result </code></pre> <p>Output:</p> <pre><code>t th thi thin thing </code></pre> <p>[ ... ]</p> <pre><code>tu tuf u uf f </code></pre>
0
2009-10-08T16:54:10Z
[ "python" ]
How to sort all possible words out of a string?
1,538,589
<p>I'm wondering how to proceed with this task, take this string for example "thingsandstuff".</p> <p>How could I generate all possible strings out of this string as to look them up individually against an english dictionary?</p> <p>The goal is to find valid english words in a string that does not contain space.</p> <p>Thanks</p>
1
2009-10-08T15:36:25Z
1,539,332
<p>This will find whether or not a candidate can be formed out of the letters in a given word; it's assumed that <code>word</code> (but not <code>candidate</code>) is sorted prior to the call.</p> <pre><code>&gt;&gt;&gt; def match(candidate, word): def next_char(w): for ch in sorted(w): yield ch g = next_char(word) for cl in sorted(candidate): try: wl = g.next() except StopIteration: return False if wl &gt; cl: return False while wl &lt; cl: try: wl = g.next() except StopIteration: return False if wl &gt; cl: return False return True &gt;&gt;&gt; word = sorted("supernatural") &gt;&gt;&gt; dictionary = ["super", "natural", "perturb", "rant", "arrant"] &gt;&gt;&gt; for candidate in dictionary: print candidate, match(candidate, word) super True natural True perturb False rant True arrant True </code></pre> <p>When I load the BSD words file (235,000+ words) and run this using <code>plenipotentiary</code> as my word, I get about 2500 hits in under a second and a half. </p> <p>If you're going to run many searches, it's a good idea to remove the sort from <code>next_char</code>, build a dictionary keyed on the sorted version of each word -</p> <pre><code>d = dict([(sorted(word), word) for word in dictionary]) </code></pre> <p>and produce results via logic like this:</p> <pre><code>result = [d[k] for k in d.keys() if match(k, word)] </code></pre> <p>so that you have to perform 250,000+ sorts over and over again.</p>
1
2009-10-08T17:32:27Z
[ "python" ]
How to sort all possible words out of a string?
1,538,589
<p>I'm wondering how to proceed with this task, take this string for example "thingsandstuff".</p> <p>How could I generate all possible strings out of this string as to look them up individually against an english dictionary?</p> <p>The goal is to find valid english words in a string that does not contain space.</p> <p>Thanks</p>
1
2009-10-08T15:36:25Z
1,539,336
<p>If you know the full dictionary well in advance, and it doesn't change between searches, you might try the following...</p> <p>Index the dictionary. Each word (e.g. "hello") becomes a (key, data) tuple such as ("ehllo", "hello"). In the key, the letters are sorted alphabetically.</p> <p>Good index data structures would include a <a href="http://en.wikipedia.org/wiki/Trie" rel="nofollow">trie</a> (aka digital tree) or a <a href="http://en.wikipedia.org/wiki/Ternary%5Fsearch%5Ftree" rel="nofollow">ternary tree</a>. A conventional binary tree could be made to work. A hash table wouldn't work. I'm going to assume a trie or a ternary tree. Note - the data structure must act as a multimap (you probably need a linked list of matched data items at each key-matched leaf).</p> <p>Before evaluating for a particular string, sort the letters in the string. Then do a key search in the data structure. <em>BUT</em> a simple key search will only find words that use <em>all</em> letters from the original string.</p> <p>Basically, a trie search matches one letter at a time, choosing a child node based on the next letter of the input. However, at each step, we have an extra option - skip a letter of the sorted input string and remain at the same node (ie, don't use that letter in the output). The obvious thing to do is a depth-first backtracking search. Note that both our keys and our input have the letters sorted, so we can probably optimise the search a bit.</p> <p>A ternary tree version follows similar principles to a trie, but instead of multiple children per node, you basically have next-letter binary tree logic built into the structure. The search can be easily adapted - the options for each next-letter search being match the next input letter or discard it.</p> <p>When you get runs of the same letter in the sorted input string, the 'skip a letter' option in the search should be 'skip to the next different letter'. Otherwise, you end up doing duplicate searches (during backtracking) - e.g. there are 3 different ways to use two out of three duplicate letters - you could ignore the first, the second, or the third duplicate - and you only need to check one case.</p> <p>Optimisations might have extra details in the data structure nodes in order to help prune the search tree. E.g. keeping the maximum length of word tails in the subtree allows you to check whether your remaining part of your search string contains enough letters to bother continuing the search.</p> <p>Time complexity isn't immediately obvious due to the backtracking.</p>
0
2009-10-08T17:32:49Z
[ "python" ]
HTTP Download very Big File
1,538,617
<p>I'm working at a web application in Python/Twisted.</p> <p>I want the user to be able to download a very big file (> 100 Mb). I don't want to load all the file in memory (of the server), of course.</p> <p>server side I have this idea:</p> <pre><code>... request.setHeader('Content-Type', 'text/plain') fp = open(fileName, 'rb') try: r = None while r != '': r = fp.read(1024) request.write(r) finally: fp.close() request.finish() </code></pre> <p>I expected this to work, but I have problems: I'm testing with FF... It seems the browser make me wait until the file is completed downloaded, and then I have the open/save dialog box.</p> <p>I expected the dialog box immediately, and then the progress bar in action...</p> <p>Maybe I have to add something in the Http header... Something like the size of the file?</p>
12
2009-10-08T15:43:00Z
1,538,647
<p>Yes, the Content-Length header will give you the progress bar you desire!</p>
3
2009-10-08T15:45:34Z
[ "python", "http", "download", "twisted" ]
HTTP Download very Big File
1,538,617
<p>I'm working at a web application in Python/Twisted.</p> <p>I want the user to be able to download a very big file (> 100 Mb). I don't want to load all the file in memory (of the server), of course.</p> <p>server side I have this idea:</p> <pre><code>... request.setHeader('Content-Type', 'text/plain') fp = open(fileName, 'rb') try: r = None while r != '': r = fp.read(1024) request.write(r) finally: fp.close() request.finish() </code></pre> <p>I expected this to work, but I have problems: I'm testing with FF... It seems the browser make me wait until the file is completed downloaded, and then I have the open/save dialog box.</p> <p>I expected the dialog box immediately, and then the progress bar in action...</p> <p>Maybe I have to add something in the Http header... Something like the size of the file?</p>
12
2009-10-08T15:43:00Z
1,545,148
<p>If this really is <code>text/plain</code> content, you should seriously consider sending it with <code>Content-Encoding: gzip</code> whenever a client indicates they can handle it. You ought to see huge bandwidth savings. Additionally, if this is a static file, what you really want to do is use <code>sendfile(2)</code>. As for browsers not doing what you expect in terms of downloading things, you might want to look at the <code>Content-Disposition</code> header. So anyhow, the logic goes like this:</p> <p>If the client indicates they can handle <code>gzip</code> encoding via the <code>Accept-Encoding</code> header (e.g. <code>Accept-Encoding: compress;q=0.5, gzip;q=1.0</code> or <code>Accept-Encoding: gzip;q=1.0, identity; q=0.5, *;q=0</code> or similar) then compress the file, cache the compressed result somewhere, write the correct headers for the response (<code>Content-Encoding: gzip</code>, <code>Content-Length: n</code>, <code>Content-Type: text/plain</code>, etc), and then use <code>sendfile(2)</code> (however that may or may not have been made available in your environment) to copy the content from the open file descriptor into your response stream.</p> <p>If they don't accept <code>gzip</code>, do the same thing, but without gzipping first.</p> <p>Alternatively, if you have Apache, Lighttpd, or similar acting as a transparent proxy in front of your server, you could use the <code>X-Sendfile</code> header, which is exceedingly fast:</p> <pre><code>response.setHeader('Content-Type', 'text/plain') response.setHeader( 'Content-Disposition', 'attachment; filename="' + os.path.basename(fileName) + '"' ) response.setHeader('X-Sendfile', fileName) response.setHeader('Content-Length', os.stat(fileName).st_size) </code></pre>
3
2009-10-09T17:43:54Z
[ "python", "http", "download", "twisted" ]
HTTP Download very Big File
1,538,617
<p>I'm working at a web application in Python/Twisted.</p> <p>I want the user to be able to download a very big file (> 100 Mb). I don't want to load all the file in memory (of the server), of course.</p> <p>server side I have this idea:</p> <pre><code>... request.setHeader('Content-Type', 'text/plain') fp = open(fileName, 'rb') try: r = None while r != '': r = fp.read(1024) request.write(r) finally: fp.close() request.finish() </code></pre> <p>I expected this to work, but I have problems: I'm testing with FF... It seems the browser make me wait until the file is completed downloaded, and then I have the open/save dialog box.</p> <p>I expected the dialog box immediately, and then the progress bar in action...</p> <p>Maybe I have to add something in the Http header... Something like the size of the file?</p>
12
2009-10-08T15:43:00Z
1,657,324
<p>Two big problems with the sample code you posted are that it is non-cooperative and it loads the entire file into memory before sending it.</p> <pre><code>while r != '': r = fp.read(1024) request.write(r) </code></pre> <p>Remember that Twisted uses cooperative multitasking to achieve any sort of concurrency. So the first problem with this snippet is that it is a while loop over the contents of an entire file (which you say is large). This means the entire file will be read into memory and written to the response before <em>anything</em> else can happen in the process. In this case, it happens that "<em>anything</em>" also includes pushing the bytes from the in-memory buffer onto the network, so your code will also hold the entire file in memory at once and only start to get rid of it when this loop completes.</p> <p>So, as a general rule, you shouldn't write code for use in a Twisted-based application that uses a loop like this to do a big job. Instead, you need to do each small piece of the big job in a way that will cooperate with the event loop. For sending a file over the network, the best way to approach this is with <em>producers</em> and <em>consumers</em>. These are two related APIs for moving large amounts of data around using buffer-empty events to do it efficiently and without wasting unreasonable amounts of memory.</p> <p>You can find some documentation of these APIs here:</p> <p><a href="http://twistedmatrix.com/projects/core/documentation/howto/producers.html">http://twistedmatrix.com/projects/core/documentation/howto/producers.html</a></p> <p>Fortunately, for this very common case, there is also a producer written already that you can use, rather than implementing your own:</p> <p><a href="http://twistedmatrix.com/documents/current/api/twisted.protocols.basic.FileSender.html">http://twistedmatrix.com/documents/current/api/twisted.protocols.basic.FileSender.html</a></p> <p>You probably want to use it sort of like this:</p> <pre><code>from twisted.protocols.basic import FileSender from twisted.python.log import err from twisted.web.server import NOT_DONE_YET class Something(Resource): ... def render_GET(self, request): request.setHeader('Content-Type', 'text/plain') fp = open(fileName, 'rb') d = FileSender().beginFileTransfer(fp, request) def cbFinished(ignored): fp.close() request.finish() d.addErrback(err).addCallback(cbFinished) return NOT_DONE_YET </code></pre> <p>You can read more about <code>NOT_DONE_YET</code> and other related ideas the "Twisted Web in 60 Seconds" series on my blog, <a href="http://jcalderone.livejournal.com/50562.html">http://jcalderone.livejournal.com/50562.html</a> (see the "asynchronous responses" entries in particular).</p>
31
2009-11-01T14:37:00Z
[ "python", "http", "download", "twisted" ]
HTTP Download very Big File
1,538,617
<p>I'm working at a web application in Python/Twisted.</p> <p>I want the user to be able to download a very big file (> 100 Mb). I don't want to load all the file in memory (of the server), of course.</p> <p>server side I have this idea:</p> <pre><code>... request.setHeader('Content-Type', 'text/plain') fp = open(fileName, 'rb') try: r = None while r != '': r = fp.read(1024) request.write(r) finally: fp.close() request.finish() </code></pre> <p>I expected this to work, but I have problems: I'm testing with FF... It seems the browser make me wait until the file is completed downloaded, and then I have the open/save dialog box.</p> <p>I expected the dialog box immediately, and then the progress bar in action...</p> <p>Maybe I have to add something in the Http header... Something like the size of the file?</p>
12
2009-10-08T15:43:00Z
8,377,700
<p>Here is an example of downloading files in chunks using urllib2, which you could use from inside of a twisted function call</p> <pre><code>import os import urllib2 import math def downloadChunks(url): """Helper to download large files the only arg is a url this file will go to a temp directory the file will also be downloaded in chunks and print out how much remains """ baseFile = os.path.basename(url) #move the file to a more uniq path os.umask(0002) temp_path = "/tmp/" try: file = os.path.join(temp_path,baseFile) req = urllib2.urlopen(url) total_size = int(req.info().getheader('Content-Length').strip()) downloaded = 0 CHUNK = 256 * 10240 with open(file, 'wb') as fp: while True: chunk = req.read(CHUNK) downloaded += len(chunk) print math.floor( (downloaded / total_size) * 100 ) if not chunk: break fp.write(chunk) except urllib2.HTTPError, e: print "HTTP Error:",e.code , url return False except urllib2.URLError, e: print "URL Error:",e.reason , url return False return file </code></pre>
0
2011-12-04T18:49:32Z
[ "python", "http", "download", "twisted" ]
Why are python strings and tuples are made immutable?
1,538,663
<p>I am not sure why strings and tuples were made to be immutable; what are the advantages and disadvantage of making them immutable?</p>
37
2009-10-08T15:48:57Z
1,538,685
<blockquote> <p>One is performance: knowing that a string is immutable makes it easy to lay it out at construction time — fixed and unchanging storage requirements. This is also one of the reasons for the distinction between tuples and lists. This also allows the implementation to safely reuse string objects. For example, the CPython implemenation uses pre-allocated objects for single-character strings, and usually returns the original string for string operations that doesn’t change the content.</p> <p>The other is that strings in Python are considered as "elemental" as numbers. No amount of activity will change the value 8 to anything else, and in Python, no amount of activity will change the string “eight” to anything else.</p> </blockquote> <p><a href="http://effbot.org/pyfaq/why-are-python-strings-immutable.htm">http://effbot.org/pyfaq/why-are-python-strings-immutable.htm</a></p>
25
2009-10-08T15:51:29Z
[ "python", "string", "immutability", "tuples" ]
Why are python strings and tuples are made immutable?
1,538,663
<p>I am not sure why strings and tuples were made to be immutable; what are the advantages and disadvantage of making them immutable?</p>
37
2009-10-08T15:48:57Z
1,538,686
<p>pros: Performance </p> <p>cons: you can't change mutables.</p>
2
2009-10-08T15:51:34Z
[ "python", "string", "immutability", "tuples" ]
Why are python strings and tuples are made immutable?
1,538,663
<p>I am not sure why strings and tuples were made to be immutable; what are the advantages and disadvantage of making them immutable?</p>
37
2009-10-08T15:48:57Z
1,538,689
<p>One big advantage of making them immutable is that they can be used as keys in a dictionary. I'm sure the internal data structures used by dictionaries would get quite messed up if the keys were allowed to change.</p>
10
2009-10-08T15:52:09Z
[ "python", "string", "immutability", "tuples" ]
Why are python strings and tuples are made immutable?
1,538,663
<p>I am not sure why strings and tuples were made to be immutable; what are the advantages and disadvantage of making them immutable?</p>
37
2009-10-08T15:48:57Z
1,632,939
<p>Imagine a language called FakeMutablePython, where you can alter strings using list assignment and such (such as <code>mystr[0] = 'a'</code>)</p> <pre><code>a = "abc" </code></pre> <p>That creates an entry in memory in memory address 0x1, containing "abc", and the identifier <code>a</code> pointing to it.</p> <p>Now, say you do..</p> <pre><code>b = a </code></pre> <p>This creates the identifier <code>b</code> and also points it to the same memory address of 0x1</p> <p>Now, if the string were mutable, and you change <code>b</code>:</p> <pre><code>b[0] = 'z' </code></pre> <p>This alters the first byte of the string stored at 0x1 to <code>z</code>.. Since the identifier <code>a</code> is pointing to here to, thus that string would altered also, so..</p> <pre><code>print a print b </code></pre> <p>..would both output <code>zbc</code></p> <p>This could make for some really weird, unexpected behaviour. Dictionary keys would be a good example of this:</p> <pre><code>mykey = 'abc' mydict = { mykey: 123, 'zbc': 321 } anotherstring = mykey anotherstring[0] = 'z' </code></pre> <p>Now in FakeMutablePython, things become rather odd - you initially have two keys in the dictionary, "abc" and "zbc".. Then you alter the "abc" string (via the identifier <code>anotherstring</code>) to "zbc", so the dict has two keys, "zbc" and "zbc"...</p> <p>One solution to this weirdness would be, whenever you assign a string to an identifier (or use it as a dict key), it copies the string at 0x1 to 0x2.</p> <p>This prevents the above, but what if you have a string that requires 200MB of memory?</p> <pre><code>a = "really, really long string [...]" b = a </code></pre> <p>Suddenly your script takes up 400MB of memory? This isn't very good.</p> <p>What about if we point it to the same memory address, until we modify it? <a href="http://en.wikipedia.org/wiki/Copy-on-write">Copy on write</a>. The problem is, this can be quite complicated to do..</p> <p>This is where immutability comes in.. Instead of requiring the <code>.replace()</code> method to copy the string from memory into a new address, then modify it and return.. We just make all strings immutable, and thus the function must create a new string to return. This explains the following code:</p> <pre><code>a = "abc" b = a.replace("a", "z") </code></pre> <p>And is proven by:</p> <pre><code>&gt;&gt;&gt; a = 'abc' &gt;&gt;&gt; b = a &gt;&gt;&gt; id(a) == id(b) True &gt;&gt;&gt; b = b.replace("a", "z") &gt;&gt;&gt; id(a) == id(b) False </code></pre> <p>(the <a href="http://docs.python.org/library/functions.html#id"><code>id()</code></a> function returns the memory address of the object)</p>
61
2009-10-27T18:56:17Z
[ "python", "string", "immutability", "tuples" ]
Why are python strings and tuples are made immutable?
1,538,663
<p>I am not sure why strings and tuples were made to be immutable; what are the advantages and disadvantage of making them immutable?</p>
37
2009-10-08T15:48:57Z
3,165,540
<p>Immutable types are conceptually much simpler than mutable ones. For example, you don't have to mess with copy constructors or const-correctness like in C++. The more types are immutable, the easier the language gets. Thus the easiest languages are the pure functional ones without any global state (because lambda calculus is much easier than Turing machines, and equally powerful), although a lot of people don't seem to appreciate this.</p>
3
2010-07-02T12:16:34Z
[ "python", "string", "immutability", "tuples" ]
Why are python strings and tuples are made immutable?
1,538,663
<p>I am not sure why strings and tuples were made to be immutable; what are the advantages and disadvantage of making them immutable?</p>
37
2009-10-08T15:48:57Z
10,837,060
<p>Perl has mutable strings and seems to function just fine. The above seems like a lot of hand waving and rationalization for an arbitrary design decision.</p> <p>My answer to the question of why Python has immutable strings, because Python creator Guido van Rossum wanted it that way and he now has legions of fans that will defend that arbitrary decision to their dying breath.</p> <p>You could pose a similar question of why Perl doesn't have immutable strings and a whole passel of people would write how awful the very concept of immutable strings are and why it's The Very Bestest Idea Ever (TM) that Perl doesn't have them.</p>
3
2012-05-31T15:54:11Z
[ "python", "string", "immutability", "tuples" ]
can't import gdal in python?
1,538,725
<p>I have <code>gdal</code> installed and running on Ubuntu Jaunty but I can't run <code>gdal2tiles</code> because I get the error:</p> <pre><code>Traceback (most recent call last): File "/usr/local/bin/gdal2tiles.py", line 42, in &lt;module&gt; import gdal ImportError: No module named gdal </code></pre> <p>When I open python and type <code>import gdal</code> I get the same error.</p> <p>I've <code>set LD_LIBRARY_PATH</code> (without spaces!) to <code>/usr/local/lib</code> but it doesn't seem to have made any difference.</p> <p>Looks like Python can't find <code>gdal</code>. Can anyone help?</p> <p>Thanks!</p>
9
2009-10-08T15:56:25Z
1,538,763
<p>Ith seems to be a "<strong><em>Python Path</em></strong>" issue. &nbsp;Python libraries are looked-up within a defined path. Try</p> <pre><code>import sys sys.path </code></pre> <p>If the directory where the gdal.py and related files is not in this list, then Python cannot find it. That's for the "diagnostics" part. To fix the situation, you have several options... They all hinge on knowing the rules which Python uses to build this path.</p> <ul> <li>The PYTHONPATH environement variable can be altered to include the desired path</li> <li>Python can be started from the directory where the desired library resides.</li> <li>sys.path can be dynamically altered, with sys.path.append("/SomePath/To/MyStuff")</li> </ul> <p>The only place where I've seen the rules pertaining to the building of sys.path formerly described, within the "official" Python documentation, is in the <a href="http://docs.python.org/tutorial/modules.html">tutorial</a>, at section 6.1.2<br> <strong>Excerpt:</strong><br></p> <pre> modules are searched in the list of directories given by the variable sys.path which is initialized from the directory containing the input script (or the current directory), PYTHONPATH and the installation- dependent default. This allows Python programs that know what they’re doing to modify or replace the module search path. Note that because the directory containing the script being run is on the search path, it is important that the script not have the same name as a standard module, or Python will attempt to load the script as a module when that module is imported. This will generally be an error. See section Standard Modules for more information. </pre>
14
2009-10-08T16:02:01Z
[ "python", "gdal" ]
can't import gdal in python?
1,538,725
<p>I have <code>gdal</code> installed and running on Ubuntu Jaunty but I can't run <code>gdal2tiles</code> because I get the error:</p> <pre><code>Traceback (most recent call last): File "/usr/local/bin/gdal2tiles.py", line 42, in &lt;module&gt; import gdal ImportError: No module named gdal </code></pre> <p>When I open python and type <code>import gdal</code> I get the same error.</p> <p>I've <code>set LD_LIBRARY_PATH</code> (without spaces!) to <code>/usr/local/lib</code> but it doesn't seem to have made any difference.</p> <p>Looks like Python can't find <code>gdal</code>. Can anyone help?</p> <p>Thanks!</p>
9
2009-10-08T15:56:25Z
1,538,803
<p>Here is a link that teaches how to install and use Python + GDAL, OGR and other tools.</p> <p>I hope its useful.</p> <p><a href="http://www.gis.usu.edu/~chrisg/python/2009/">http://www.gis.usu.edu/~chrisg/python/2009/</a></p>
6
2009-10-08T16:07:17Z
[ "python", "gdal" ]
can't import gdal in python?
1,538,725
<p>I have <code>gdal</code> installed and running on Ubuntu Jaunty but I can't run <code>gdal2tiles</code> because I get the error:</p> <pre><code>Traceback (most recent call last): File "/usr/local/bin/gdal2tiles.py", line 42, in &lt;module&gt; import gdal ImportError: No module named gdal </code></pre> <p>When I open python and type <code>import gdal</code> I get the same error.</p> <p>I've <code>set LD_LIBRARY_PATH</code> (without spaces!) to <code>/usr/local/lib</code> but it doesn't seem to have made any difference.</p> <p>Looks like Python can't find <code>gdal</code>. Can anyone help?</p> <p>Thanks!</p>
9
2009-10-08T15:56:25Z
2,118,630
<p>You may also want to check GDAL Wiki dedicated to the bindings to Python - <a href="http://trac.osgeo.org/gdal/wiki/GdalOgrInPython" rel="nofollow">GdalOgrInPython</a> where the installation and usage on Linux and Windows platforms is discussed.</p>
1
2010-01-22T16:15:48Z
[ "python", "gdal" ]
Is the single underscore "_" a built-in variable in Python?
1,538,832
<p>I don't understand what this single underscore means. Is it a magic variable? I can't see it in locals() and globals().</p> <pre><code>&gt;&gt;&gt; 'abc' 'abc' &gt;&gt;&gt; len(_) 3 &gt;&gt;&gt; </code></pre>
26
2009-10-08T16:11:33Z
1,538,868
<p>In the standard Python REPL, <code>_</code> represents the last returned value -- at the point where you called <code>len(_)</code>, <code>_</code> was the value <code>'abc'</code>.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; 10 10 &gt;&gt;&gt; _ 10 &gt;&gt;&gt; _ + 5 15 &gt;&gt;&gt; _ + 5 20 </code></pre> <p>Note that there is no such functionality within Python <em>scripts</em>. In a script, <code>_</code> has no special meaning and will not be automatically set to the value produced by the previous statement.</p> <p>Also, beware of reassigning <code>_</code> in the REPL if you want to use it like above!</p> <pre><code>&gt;&gt;&gt; _ = "underscore" &gt;&gt;&gt; 10 10 &gt;&gt;&gt; _ + 5 Traceback (most recent call last): File "&lt;pyshell#6&gt;", line 1, in &lt;module&gt; _ + 5 TypeError: cannot concatenate 'str' and 'int' objects </code></pre> <p>To undo the assignment (and remove the <code>_</code> from globals), you'll have to:</p> <pre><code>&gt;&gt;&gt; del _ </code></pre> <p>then the functionality will be back to normal (the <code>__builtin__._</code> will be visible again).</p>
39
2009-10-08T16:16:42Z
[ "python" ]
Is the single underscore "_" a built-in variable in Python?
1,538,832
<p>I don't understand what this single underscore means. Is it a magic variable? I can't see it in locals() and globals().</p> <pre><code>&gt;&gt;&gt; 'abc' 'abc' &gt;&gt;&gt; len(_) 3 &gt;&gt;&gt; </code></pre>
26
2009-10-08T16:11:33Z
1,538,917
<p>Why you can't see it? It is in <code>__builtins__</code></p> <pre><code>&gt;&gt;&gt; __builtins__._ is _ True </code></pre> <p>So it's neither global nor local. <sup>1</sup></p> <p>And where does this assignment happen? <code>sys.displayhook</code>:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; help(sys.displayhook) Help on built-in function displayhook in module sys: displayhook(...) displayhook(object) -&gt; None Print an object to sys.stdout and also save it in __builtin__. </code></pre> <p><sup>1</sup> 2012 Edit : I'd call it <em>"superglobal"</em> since <code>__builtin__</code>'s members are available everywhere, in any module.</p>
15
2009-10-08T16:23:16Z
[ "python" ]
Is the single underscore "_" a built-in variable in Python?
1,538,832
<p>I don't understand what this single underscore means. Is it a magic variable? I can't see it in locals() and globals().</p> <pre><code>&gt;&gt;&gt; 'abc' 'abc' &gt;&gt;&gt; len(_) 3 &gt;&gt;&gt; </code></pre>
26
2009-10-08T16:11:33Z
1,538,942
<p>Usually, we are using _ in Python to bind a ugettext function.</p>
2
2009-10-08T16:26:45Z
[ "python" ]
Caesar's Cipher using python, could use a little help
1,538,935
<p>I'm trying to make a "Caesar's Cipher" while using python..this is what I have so far. Could anyone tell me how this is looking? Am I going in the right direction? What am I missing? When I run the program to say for example (josh is cool) I don't get the cipher on the same line. It looks like this when I do <code>main(3)</code></p> <pre><code>m r v k l v f r r o </code></pre> <p>But it puts each letter on a new line. How could I do it so that it is on one line?</p> <pre><code>def main(k): if k&lt;0 or k&gt;231: print "complaint" raise SystemExit Input = raw_input("Please enter Plaintext to Cipher") for x in range(len(Input)): letter=Input[x] if letter.islower(): x=ord(letter) x=x+k if x&gt;122: x=x-122+97 print chr(x), if letter.isupper(): x=ord(letter) x=x+k if x&gt;90: x=x-90+65 print chr(x), </code></pre>
2
2009-10-08T16:25:51Z
1,539,046
<p>Put a comma after each print statement; it will still put a space between the characters, but they'll all be on the same line. If you need to print them without the spaces, build them all into a single string and print that at the end.</p>
1
2009-10-08T16:43:45Z
[ "python" ]
Caesar's Cipher using python, could use a little help
1,538,935
<p>I'm trying to make a "Caesar's Cipher" while using python..this is what I have so far. Could anyone tell me how this is looking? Am I going in the right direction? What am I missing? When I run the program to say for example (josh is cool) I don't get the cipher on the same line. It looks like this when I do <code>main(3)</code></p> <pre><code>m r v k l v f r r o </code></pre> <p>But it puts each letter on a new line. How could I do it so that it is on one line?</p> <pre><code>def main(k): if k&lt;0 or k&gt;231: print "complaint" raise SystemExit Input = raw_input("Please enter Plaintext to Cipher") for x in range(len(Input)): letter=Input[x] if letter.islower(): x=ord(letter) x=x+k if x&gt;122: x=x-122+97 print chr(x), if letter.isupper(): x=ord(letter) x=x+k if x&gt;90: x=x-90+65 print chr(x), </code></pre>
2
2009-10-08T16:25:51Z
1,539,075
<p>Barring the syntax errors, your code seems to work.</p> <p>However, I took the liberty of removing all duplicates, and cleaning it up:</p> <pre><code>first = raw_input("Please enter Plaintext to Cipher: ") k = int(raw_input("Please enter the shift: ")) result = '' for second in first: x=ord(second) x=x+k if x&gt;90 and x&lt;122: x=x-26 elif x&gt;122: x=x-26 result += chr(x) print first print result </code></pre> <p>Also "first" and "second" are really bad names for those variables. "Input" and "letter" is probably better.</p>
0
2009-10-08T16:47:38Z
[ "python" ]
Caesar's Cipher using python, could use a little help
1,538,935
<p>I'm trying to make a "Caesar's Cipher" while using python..this is what I have so far. Could anyone tell me how this is looking? Am I going in the right direction? What am I missing? When I run the program to say for example (josh is cool) I don't get the cipher on the same line. It looks like this when I do <code>main(3)</code></p> <pre><code>m r v k l v f r r o </code></pre> <p>But it puts each letter on a new line. How could I do it so that it is on one line?</p> <pre><code>def main(k): if k&lt;0 or k&gt;231: print "complaint" raise SystemExit Input = raw_input("Please enter Plaintext to Cipher") for x in range(len(Input)): letter=Input[x] if letter.islower(): x=ord(letter) x=x+k if x&gt;122: x=x-122+97 print chr(x), if letter.isupper(): x=ord(letter) x=x+k if x&gt;90: x=x-90+65 print chr(x), </code></pre>
2
2009-10-08T16:25:51Z
1,539,324
<p>This code should work pretty well. It also handles arbitrary offsets, including negative.</p> <pre><code>phrase = raw_input("Please enter plaintext to Cipher: ") shift = int(raw_input("Please enter shift: ")) result = '' for char in phrase: x = ord(char) if char.isalpha(): x = x + shift offset = 65 if char.islower(): offset = 97 while x &lt; offset: x += 26 while x &gt; offset+25: x -= 26 result += chr(x) print result </code></pre> <p>The other way to do it, with a slightly different cipher, is simply rotate through all characters, upper and lower, or even all ascii > 0x20.</p> <pre><code>phrase = raw_input("Please enter plaintext to Cipher: ") shift = int(raw_input("Please enter shift: ")) result = '' for char in phrase: x = ord(char) x = x + shift while x &lt; 32: x += 96 while x &gt; 127: x -= 96 result += chr(x) print result </code></pre>
2
2009-10-08T17:31:45Z
[ "python" ]
Caesar's Cipher using python, could use a little help
1,538,935
<p>I'm trying to make a "Caesar's Cipher" while using python..this is what I have so far. Could anyone tell me how this is looking? Am I going in the right direction? What am I missing? When I run the program to say for example (josh is cool) I don't get the cipher on the same line. It looks like this when I do <code>main(3)</code></p> <pre><code>m r v k l v f r r o </code></pre> <p>But it puts each letter on a new line. How could I do it so that it is on one line?</p> <pre><code>def main(k): if k&lt;0 or k&gt;231: print "complaint" raise SystemExit Input = raw_input("Please enter Plaintext to Cipher") for x in range(len(Input)): letter=Input[x] if letter.islower(): x=ord(letter) x=x+k if x&gt;122: x=x-122+97 print chr(x), if letter.isupper(): x=ord(letter) x=x+k if x&gt;90: x=x-90+65 print chr(x), </code></pre>
2
2009-10-08T16:25:51Z
1,539,611
<p>Here is a different method to show how we can handle this in a very clean way. We define an input alphabet and an output alphabet, then a translation table and use <code>unicode.translate()</code> to do the actual encryption.</p> <pre><code>import string # Blatantly steal Lennart's UI design first = unicode(raw_input("Please enter Plaintext to Cipher: "), "UTF-8") k = int(raw_input("Please enter the shift: ")) in_alphabet = unicode(string.ascii_lowercase) out_alphabet = in_alphabet[k:] + in_alphabet[:k] translation_table = dict((ord(ic), oc) for ic, oc in zip(in_alphabet, out_alphabet)) print first.translate(translation_table) </code></pre> <p>It can be extended to uppercase letters as needed.</p>
1
2009-10-08T18:22:52Z
[ "python" ]
Caesar's Cipher using python, could use a little help
1,538,935
<p>I'm trying to make a "Caesar's Cipher" while using python..this is what I have so far. Could anyone tell me how this is looking? Am I going in the right direction? What am I missing? When I run the program to say for example (josh is cool) I don't get the cipher on the same line. It looks like this when I do <code>main(3)</code></p> <pre><code>m r v k l v f r r o </code></pre> <p>But it puts each letter on a new line. How could I do it so that it is on one line?</p> <pre><code>def main(k): if k&lt;0 or k&gt;231: print "complaint" raise SystemExit Input = raw_input("Please enter Plaintext to Cipher") for x in range(len(Input)): letter=Input[x] if letter.islower(): x=ord(letter) x=x+k if x&gt;122: x=x-122+97 print chr(x), if letter.isupper(): x=ord(letter) x=x+k if x&gt;90: x=x-90+65 print chr(x), </code></pre>
2
2009-10-08T16:25:51Z
4,987,512
<p>I like kaizer.se's answer, but I think I can simplify it using the <a href="http://docs.python.org/library/string.html#string.maketrans" rel="nofollow">string.maketrans</a> function:</p> <pre><code>import string first = raw_input("Please enter Plaintext to Cipher: ") k = int(raw_input("Please enter the shift: ")) shifted_lowercase = ascii_lowercase[k:] + ascii_lowercase[:k] translation_table = maketrans(ascii_lowercase, shifted_lowercase) print first.translate(translation_table) </code></pre>
6
2011-02-13T23:02:53Z
[ "python" ]
Caesar's Cipher using python, could use a little help
1,538,935
<p>I'm trying to make a "Caesar's Cipher" while using python..this is what I have so far. Could anyone tell me how this is looking? Am I going in the right direction? What am I missing? When I run the program to say for example (josh is cool) I don't get the cipher on the same line. It looks like this when I do <code>main(3)</code></p> <pre><code>m r v k l v f r r o </code></pre> <p>But it puts each letter on a new line. How could I do it so that it is on one line?</p> <pre><code>def main(k): if k&lt;0 or k&gt;231: print "complaint" raise SystemExit Input = raw_input("Please enter Plaintext to Cipher") for x in range(len(Input)): letter=Input[x] if letter.islower(): x=ord(letter) x=x+k if x&gt;122: x=x-122+97 print chr(x), if letter.isupper(): x=ord(letter) x=x+k if x&gt;90: x=x-90+65 print chr(x), </code></pre>
2
2009-10-08T16:25:51Z
17,640,644
<p>I very simple, 3-shift solution without Umlauts and alike would be:</p> <pre><code>def caesar(inputstring): shifted=string.lowercase[3:]+string.lowercase[:3] return "".join(shifted[string.lowercase.index(letter)] for letter in inputstring) </code></pre> <p>and reverse:</p> <pre><code>def brutus(inputstring): shifted=string.lowercase[-3:]+string.lowercase[:-3] return "".join(shifted[string.lowercase.index(letter)] for letter in inputstring) </code></pre> <p>using it:</p> <pre><code>caesar("xerxes") </code></pre>
0
2013-07-14T15:12:01Z
[ "python" ]
Caesar's Cipher using python, could use a little help
1,538,935
<p>I'm trying to make a "Caesar's Cipher" while using python..this is what I have so far. Could anyone tell me how this is looking? Am I going in the right direction? What am I missing? When I run the program to say for example (josh is cool) I don't get the cipher on the same line. It looks like this when I do <code>main(3)</code></p> <pre><code>m r v k l v f r r o </code></pre> <p>But it puts each letter on a new line. How could I do it so that it is on one line?</p> <pre><code>def main(k): if k&lt;0 or k&gt;231: print "complaint" raise SystemExit Input = raw_input("Please enter Plaintext to Cipher") for x in range(len(Input)): letter=Input[x] if letter.islower(): x=ord(letter) x=x+k if x&gt;122: x=x-122+97 print chr(x), if letter.isupper(): x=ord(letter) x=x+k if x&gt;90: x=x-90+65 print chr(x), </code></pre>
2
2009-10-08T16:25:51Z
20,006,751
<p>For Python 3.3, try using the ord(), chr() and .isalpha functions:</p> <pre><code>m = input("What is your message?: ") s = int(input("What is the shift?: ")) for i in m: if i.isalpha(): if (ord(i)+s)&gt;90: print(chr(ord(i)+s-26),end=""), elif chr(ord(i)+s-26)&lt;65: print("The shift is invalid") else: print(chr(ord(i)+s),end=""), else: pass </code></pre>
0
2013-11-15T17:12:16Z
[ "python" ]
Caesar's Cipher using python, could use a little help
1,538,935
<p>I'm trying to make a "Caesar's Cipher" while using python..this is what I have so far. Could anyone tell me how this is looking? Am I going in the right direction? What am I missing? When I run the program to say for example (josh is cool) I don't get the cipher on the same line. It looks like this when I do <code>main(3)</code></p> <pre><code>m r v k l v f r r o </code></pre> <p>But it puts each letter on a new line. How could I do it so that it is on one line?</p> <pre><code>def main(k): if k&lt;0 or k&gt;231: print "complaint" raise SystemExit Input = raw_input("Please enter Plaintext to Cipher") for x in range(len(Input)): letter=Input[x] if letter.islower(): x=ord(letter) x=x+k if x&gt;122: x=x-122+97 print chr(x), if letter.isupper(): x=ord(letter) x=x+k if x&gt;90: x=x-90+65 print chr(x), </code></pre>
2
2009-10-08T16:25:51Z
25,827,384
<p>Here is a oneliner.</p> <pre><code>&gt;&gt;&gt; brutus=lambda message,cipher,direction:''.join([chr((ord(letter)+(cipher*direction))%256) for letter in message]) &gt;&gt;&gt; encrypted= brutus('Message to be encrypted',14,1) #direction=1 for encryption &gt;&gt;&gt; encrypted '[s\x81\x81ous.\x82}.ps.s|q\x80\x87~\x82sr' &gt;&gt;&gt; brutus(encrypted,14,-1) # direction=-1 for decryption 'Message to be encrypted' &gt;&gt;&gt; </code></pre>
0
2014-09-13T20:28:34Z
[ "python" ]
Perform an action and redirecting to the same URL doesn't refresh the page
1,538,994
<p>We are working on a new web site using Apache, Python and Django.</p> <p>In the development phase, no problem but once binding to Apache, using Firefox 3.5.3, we got a strange problem.</p> <p>We stand on :</p> <p><a href="http://website.fr/search/" rel="nofollow">http://website.fr/search/</a></p> <p>When we want to change the ordering of the research, we are sending the user to :</p> <p><a href="http://website.fr/search/order/price/" rel="nofollow">http://website.fr/search/order/price/</a></p> <p>This page change a session variable and redirect, with code 302, to :</p> <p><a href="http://website.fr/search/" rel="nofollow">http://website.fr/search/</a></p> <p>The problem is that Apache send a 302 Apache code and that Firefox doesn't refresh the page. We got the same problem when we are redirecting the user to the same page he was before.</p> <p>How should we do to force the refresh of the page ?</p>
2
2009-10-08T16:35:31Z
1,539,326
<p>How about redirecting to</p> <pre><code>http://website.fr/search/?ignoredvar=&lt;random int&gt; </code></pre> <p>Please provide the full http conversation If you need a better solution. The conversation can be traced using firebug or live http headers.</p> <p>Btw. The above solution is the only one I know for similar bug in a flash on IE.</p>
0
2009-10-08T17:32:04Z
[ "python", "django", "http", "httpwebrequest", "http-status-code-302" ]
Perform an action and redirecting to the same URL doesn't refresh the page
1,538,994
<p>We are working on a new web site using Apache, Python and Django.</p> <p>In the development phase, no problem but once binding to Apache, using Firefox 3.5.3, we got a strange problem.</p> <p>We stand on :</p> <p><a href="http://website.fr/search/" rel="nofollow">http://website.fr/search/</a></p> <p>When we want to change the ordering of the research, we are sending the user to :</p> <p><a href="http://website.fr/search/order/price/" rel="nofollow">http://website.fr/search/order/price/</a></p> <p>This page change a session variable and redirect, with code 302, to :</p> <p><a href="http://website.fr/search/" rel="nofollow">http://website.fr/search/</a></p> <p>The problem is that Apache send a 302 Apache code and that Firefox doesn't refresh the page. We got the same problem when we are redirecting the user to the same page he was before.</p> <p>How should we do to force the refresh of the page ?</p>
2
2009-10-08T16:35:31Z
1,558,399
<p>I'd say you're doing it wrong. The same URL should be the same page. Everything with HTTP and web browsers assume this, and when you don't follow this convention you're going to get yourself into trouble. Just add the search parameters and sort orders as query parameters to the URL.</p>
1
2009-10-13T05:52:43Z
[ "python", "django", "http", "httpwebrequest", "http-status-code-302" ]
Perform an action and redirecting to the same URL doesn't refresh the page
1,538,994
<p>We are working on a new web site using Apache, Python and Django.</p> <p>In the development phase, no problem but once binding to Apache, using Firefox 3.5.3, we got a strange problem.</p> <p>We stand on :</p> <p><a href="http://website.fr/search/" rel="nofollow">http://website.fr/search/</a></p> <p>When we want to change the ordering of the research, we are sending the user to :</p> <p><a href="http://website.fr/search/order/price/" rel="nofollow">http://website.fr/search/order/price/</a></p> <p>This page change a session variable and redirect, with code 302, to :</p> <p><a href="http://website.fr/search/" rel="nofollow">http://website.fr/search/</a></p> <p>The problem is that Apache send a 302 Apache code and that Firefox doesn't refresh the page. We got the same problem when we are redirecting the user to the same page he was before.</p> <p>How should we do to force the refresh of the page ?</p>
2
2009-10-08T16:35:31Z
1,560,646
<p>What happens is, the browser asks for the new URL and via 302 gets redirected back to the previous one, which is in the cache and thus not refreshed. Adding a random integer, like Piotr is suggesting will solve the problem. For randomness you can use simple timestamp.</p> <p>Implication of performing forward as you are doing makes your app unRESTful and prohibits user bookmarking the results - i wonder if it is really what you would like to do.</p> <p>It might be worth a try to try and use 303 or 307 status code instead of 302, maybe that behaves differently.</p> <p>See also: <a href="http://en.wikipedia.org/wiki/HTTP%5F302" rel="nofollow">http://en.wikipedia.org/wiki/HTTP%5F302</a></p> <p><a href="http://en.wikipedia.org/wiki/Representational%5FState%5FTransfer" rel="nofollow">http://en.wikipedia.org/wiki/Representational%5FState%5FTransfer</a></p>
3
2009-10-13T14:38:54Z
[ "python", "django", "http", "httpwebrequest", "http-status-code-302" ]
Using Python's xml.dom.minidom
1,539,023
<p>I'm trying to use Python's xml.dom.minidom, and I'm getting the following error:</p> <pre><code>&gt;&gt;&gt; from xml.dom import minidom &gt;&gt;&gt; xdocument = minidom.Document() &gt;&gt;&gt; xrss = minidom.Element("rss") &gt;&gt;&gt; xdocument.appendChild(xrss) &lt;DOM Element: rss at 0xc1d0f8&gt; &gt;&gt;&gt; xchannel = minidom.Element("channel") &gt;&gt;&gt; xrss.appendChild(xchannel) Traceback (most recent call last): File "C:\Program Files\Wing IDE 3.2\src\debug\tserver\_sandbox.py", line 1, in ? # Used internally for debug sandbox under external interpreter File "c:\Python24\Lib\xml\dom\minidom.py", line 123, in appendChild _clear_id_cache(self) File "c:\Python24\Lib\xml\dom\minidom.py", line 1468, in _clear_id_cache node.ownerDocument._id_cache.clear() AttributeError: 'NoneType' object has no attribute '_id_cache' &gt;&gt;&gt; </code></pre> <p>Anyone has any idea why?</p>
2
2009-10-08T16:39:20Z
1,539,085
<p>Use <code>xdocument.createElement('name')</code> to create new elements. This is the standard way to do that in DOM.</p>
3
2009-10-08T16:48:33Z
[ "python", "xml" ]
Using Python's xml.dom.minidom
1,539,023
<p>I'm trying to use Python's xml.dom.minidom, and I'm getting the following error:</p> <pre><code>&gt;&gt;&gt; from xml.dom import minidom &gt;&gt;&gt; xdocument = minidom.Document() &gt;&gt;&gt; xrss = minidom.Element("rss") &gt;&gt;&gt; xdocument.appendChild(xrss) &lt;DOM Element: rss at 0xc1d0f8&gt; &gt;&gt;&gt; xchannel = minidom.Element("channel") &gt;&gt;&gt; xrss.appendChild(xchannel) Traceback (most recent call last): File "C:\Program Files\Wing IDE 3.2\src\debug\tserver\_sandbox.py", line 1, in ? # Used internally for debug sandbox under external interpreter File "c:\Python24\Lib\xml\dom\minidom.py", line 123, in appendChild _clear_id_cache(self) File "c:\Python24\Lib\xml\dom\minidom.py", line 1468, in _clear_id_cache node.ownerDocument._id_cache.clear() AttributeError: 'NoneType' object has no attribute '_id_cache' &gt;&gt;&gt; </code></pre> <p>Anyone has any idea why?</p>
2
2009-10-08T16:39:20Z
1,539,122
<p>Replace <code>xdocument.appendChild(xrss)</code> with <code>xrss = xdocument.appendChild(xrss)</code>. From the <a href="http://docs.python.org/library/xml.dom.html#xml.dom.Node.appendChild" rel="nofollow">docs</a>:</p> <blockquote> <p>Node.appendChild(newChild) Add a new child node to this node at the end of the list of children, returning newChild. If the node was already in in the tree, it is removed first.</p> </blockquote> <p>So you need to assign <code>xrss</code> to the returned element from <code>appendChild</code>.</p>
0
2009-10-08T16:54:33Z
[ "python", "xml" ]
Weird behaviour with two Trac instances under Apache + mod_wsgi
1,539,203
<p>I am trying to configure two Trac instances in order to access them via browser each one with a different url:</p> <pre><code>http://trac.domain.com/trac1 http://trac.domain.com/trac2 </code></pre> <p>First time I access them Apache response is fine, I get the first Trac with /trac1, then the second one in /trac2. But when I access /trac1 again, it keeps giving me the contents of the second Trac (/trac2). If I touch the .wsgi config file for the first one (say it trac1.wsgi), then request again /trac1 with browser, I get the expected contents again.</p> <p>The opposite case works equal: access /trac2, then /trac1, then /trac2 keeps giving the contents of /trac1 until I touch trac2.wsgi...</p> <p>So it seems Python, mod_wsgi and/or Apache are caching results or something. I am not sysadmin and can't get further on this issue.</p> <p>The .wsgi files and http.conf for Apache:</p> <p><b>trac1.wsgi</b>:</p> <pre><code>import os os.environ['TRAC_ENV'] = '/home/myuser/trac/trac1' os.environ['PYTHON_EGG_CACHE'] = '/tmp/' import trac.web.main application = trac.web.main.dispatch_request </code></pre> <p><b>trac2.wsgi</b>:</p> <pre><code>import os os.environ['TRAC_ENV'] = '/home/myuser/trac/trac2' os.environ['PYTHON_EGG_CACHE'] = '/tmp/' import trac.web.main application = trac.web.main.dispatch_request </code></pre> <p><b>http.conf</b>:</p> <pre><code>&lt;VirtualHost trac.domain.com:8080&gt; WSGIScriptAlias /trac1 /home/myuser/public_html/trac1/apache/trac1.wsgi WSGIScriptAlias /trac2 /home/myuser/public_html/trac2/apache/trac2.wsgi &lt;Directory /home/myuser/public_html/trac1/apache&gt; WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all &lt;/Directory&gt; &lt;Location "/trac1"&gt; AuthType Basic AuthName "Trac1 Trac Auth" AuthUserFile /home/myuser/public_html/trac1/apache/trac1.htpasswd Require valid-user &lt;/Location&gt; &lt;Directory /home/myuser/public_html/trac2/apache&gt; WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all &lt;/Directory&gt; &lt;Location "/trac2"&gt; AuthType Basic AuthName "Trac2 Trac Auth" AuthUserFile /home/myuser/public_html/trac2/apache/trac2.htpasswd Require valid-user &lt;/Location&gt; &lt;/VirtualHost&gt; </code></pre> <p>If anybody suggests an alternative configuration or whatever, it will be welcome as well. thanks!</p> <p>Hector</p>
2
2009-10-08T17:09:19Z
1,539,232
<p>Move your egg cache to separate dirs</p> <p>trac1.wsgi:</p> <pre><code>import os os.environ['TRAC_ENV'] = '/home/myuser/trac/trac1' os.environ['PYTHON_EGG_CACHE'] = '/tmp/trac1' import trac.web.main application = trac.web.main.dispatch_request </code></pre> <p>trac2.wsgi:</p> <pre><code>import os os.environ['TRAC_ENV'] = '/home/myuser/trac/trac2' os.environ['PYTHON_EGG_CACHE'] = '/tmp/trac2' import trac.web.main application = trac.web.main.dispatch_request </code></pre>
0
2009-10-08T17:15:21Z
[ "python", "apache", "trac", "mod-wsgi" ]
Weird behaviour with two Trac instances under Apache + mod_wsgi
1,539,203
<p>I am trying to configure two Trac instances in order to access them via browser each one with a different url:</p> <pre><code>http://trac.domain.com/trac1 http://trac.domain.com/trac2 </code></pre> <p>First time I access them Apache response is fine, I get the first Trac with /trac1, then the second one in /trac2. But when I access /trac1 again, it keeps giving me the contents of the second Trac (/trac2). If I touch the .wsgi config file for the first one (say it trac1.wsgi), then request again /trac1 with browser, I get the expected contents again.</p> <p>The opposite case works equal: access /trac2, then /trac1, then /trac2 keeps giving the contents of /trac1 until I touch trac2.wsgi...</p> <p>So it seems Python, mod_wsgi and/or Apache are caching results or something. I am not sysadmin and can't get further on this issue.</p> <p>The .wsgi files and http.conf for Apache:</p> <p><b>trac1.wsgi</b>:</p> <pre><code>import os os.environ['TRAC_ENV'] = '/home/myuser/trac/trac1' os.environ['PYTHON_EGG_CACHE'] = '/tmp/' import trac.web.main application = trac.web.main.dispatch_request </code></pre> <p><b>trac2.wsgi</b>:</p> <pre><code>import os os.environ['TRAC_ENV'] = '/home/myuser/trac/trac2' os.environ['PYTHON_EGG_CACHE'] = '/tmp/' import trac.web.main application = trac.web.main.dispatch_request </code></pre> <p><b>http.conf</b>:</p> <pre><code>&lt;VirtualHost trac.domain.com:8080&gt; WSGIScriptAlias /trac1 /home/myuser/public_html/trac1/apache/trac1.wsgi WSGIScriptAlias /trac2 /home/myuser/public_html/trac2/apache/trac2.wsgi &lt;Directory /home/myuser/public_html/trac1/apache&gt; WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all &lt;/Directory&gt; &lt;Location "/trac1"&gt; AuthType Basic AuthName "Trac1 Trac Auth" AuthUserFile /home/myuser/public_html/trac1/apache/trac1.htpasswd Require valid-user &lt;/Location&gt; &lt;Directory /home/myuser/public_html/trac2/apache&gt; WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all &lt;/Directory&gt; &lt;Location "/trac2"&gt; AuthType Basic AuthName "Trac2 Trac Auth" AuthUserFile /home/myuser/public_html/trac2/apache/trac2.htpasswd Require valid-user &lt;/Location&gt; &lt;/VirtualHost&gt; </code></pre> <p>If anybody suggests an alternative configuration or whatever, it will be welcome as well. thanks!</p> <p>Hector</p>
2
2009-10-08T17:09:19Z
1,539,691
<p>I found the solution myself, it was on the Trac documentation ("important note" section), and I did not event take look, fool of me :P</p> <p><a href="http://trac.edgewall.org/wiki/TracModWSGI" rel="nofollow">http://trac.edgewall.org/wiki/TracModWSGI</a></p>
2
2009-10-08T18:40:17Z
[ "python", "apache", "trac", "mod-wsgi" ]
Python client library for WebDAV
1,539,378
<p>I'd like to implement a piece of functionality in my application that uploads and manipulates files on a WebDAV server. I'm looking for a mature Python library that would give an interface similar to the <code>os.*</code> modules for working with the remote files. Googling has turned up a smattering of options for WebDAV in Python, but I'd like to know which are in wider use these days. </p>
22
2009-10-08T17:38:32Z
1,541,478
<p>I don't know of any specifically but, depending on your platform, it may be simpler to mount and access the WebDAV-served files through the file system. There's <a href="http://en.wikipedia.org/wiki/Davfs2" rel="nofollow">davfs2</a> out there and some OS's, like Mac OS X, have WebDAV file system support built in.</p>
2
2009-10-09T02:00:54Z
[ "python", "client", "webdav" ]
Python client library for WebDAV
1,539,378
<p>I'd like to implement a piece of functionality in my application that uploads and manipulates files on a WebDAV server. I'm looking for a mature Python library that would give an interface similar to the <code>os.*</code> modules for working with the remote files. Googling has turned up a smattering of options for WebDAV in Python, but I'd like to know which are in wider use these days. </p>
22
2009-10-08T17:38:32Z
1,541,509
<p>I have no experience with any of these libraries, but the Python Package Index ("PyPi") <a href="http://pypi.python.org/pypi?%3Aaction=search&amp;term=webdav&amp;submit=search" rel="nofollow">lists quite a few webdav modules</a>.</p>
0
2009-10-09T02:16:07Z
[ "python", "client", "webdav" ]
Python client library for WebDAV
1,539,378
<p>I'd like to implement a piece of functionality in my application that uploads and manipulates files on a WebDAV server. I'm looking for a mature Python library that would give an interface similar to the <code>os.*</code> modules for working with the remote files. Googling has turned up a smattering of options for WebDAV in Python, but I'd like to know which are in wider use these days. </p>
22
2009-10-08T17:38:32Z
1,545,266
<p>Apparently you're looking for a WebDAV client library.</p> <p>Not sure how the gazillion hits came up, it seems the following 2 looks relevant:</p> <ul> <li>PyDAV: <a href="http://users.sfo.com/~jdavis/Software/PyDAV/readme.html#client" rel="nofollow">http://users.sfo.com/~jdavis/Software/PyDAV/readme.html#client</a></li> <li>Zope - and look for client.py</li> </ul>
1
2009-10-09T18:06:36Z
[ "python", "client", "webdav" ]
Python client library for WebDAV
1,539,378
<p>I'd like to implement a piece of functionality in my application that uploads and manipulates files on a WebDAV server. I'm looking for a mature Python library that would give an interface similar to the <code>os.*</code> modules for working with the remote files. Googling has turned up a smattering of options for WebDAV in Python, but I'd like to know which are in wider use these days. </p>
22
2009-10-08T17:38:32Z
6,898,536
<p>I just had a similar need and ended up testing a few Python WebDAV clients for my needs (uploading and downloading files from a WebDAV server). Here's a summary of my experience:</p> <p>1) The one that worked for me is <a href="https://launchpad.net/python-webdav-lib">python-webdav-lib</a>.</p> <p>Not much documentation, but a quick look at the code (in particular the example) was enough to figure out how to make it work for me.</p> <p>2) PyDAV 0.21 (the latest release I found) doesn't work with Python 2.6 because it uses strings as exceptions. I didn't try to fix this, expecting further incompatibilities later on.</p> <p>3) <a href="http://chandlerproject.org/Projects/Davclient">davclient 0.2.0</a>. I looked at it but didn's explore any further because the documentation didn't mention the level of API I was looking for (file upload and download).</p> <p>4) <a href="http://sourceforge.net/projects/pythonwebdavlib/">Python_WebDAV_Library-0.3.0</a>. Doesn't seem to have any upload functionality.</p>
9
2011-08-01T12:39:09Z
[ "python", "client", "webdav" ]
Python client library for WebDAV
1,539,378
<p>I'd like to implement a piece of functionality in my application that uploads and manipulates files on a WebDAV server. I'm looking for a mature Python library that would give an interface similar to the <code>os.*</code> modules for working with the remote files. Googling has turned up a smattering of options for WebDAV in Python, but I'd like to know which are in wider use these days. </p>
22
2009-10-08T17:38:32Z
12,193,865
<p>It's sad that for this question ("What Python webdav library to use?"), which for sure interests more than one person, unrelated answer was accepted ("don't use Python webdav library"). Well, common problem on Stackexchange.</p> <p>For people who will be looking for real answers, and given the requirements in the original question (simple API similar to "os" module), I may suggest <a href="https://github.com/amnong/easywebdav">easywebdav</a>, which has very easy API and even nice and simple implementation, offering upload/download and few file/dir management methods. Due to simple implementation, it so far doesn't support directory listing, but bug for that was <a href="https://github.com/amnong/easywebdav/issues/3">filed</a>, and the author intends to add it.</p>
38
2012-08-30T09:32:22Z
[ "python", "client", "webdav" ]
Python client library for WebDAV
1,539,378
<p>I'd like to implement a piece of functionality in my application that uploads and manipulates files on a WebDAV server. I'm looking for a mature Python library that would give an interface similar to the <code>os.*</code> modules for working with the remote files. Googling has turned up a smattering of options for WebDAV in Python, but I'd like to know which are in wider use these days. </p>
22
2009-10-08T17:38:32Z
23,611,950
<pre><code>import easywebdav webdav = easywebdav.connect( host='dav.dumptruck.goldenfrog.com', username='_snip_', port=443, protocol="https", password='_snip_') _file = "test.py" print webdav.cd("/dav/") # print webdav._get_url("") # print webdav.ls() # print webdav.exists("/dav/test.py") # print webdav.exists("ECS.zip") # print webdav.download(_file, "./"+_file) print webdav.upload("./test.py", "test.py") </code></pre>
2
2014-05-12T14:37:48Z
[ "python", "client", "webdav" ]
Python client library for WebDAV
1,539,378
<p>I'd like to implement a piece of functionality in my application that uploads and manipulates files on a WebDAV server. I'm looking for a mature Python library that would give an interface similar to the <code>os.*</code> modules for working with the remote files. Googling has turned up a smattering of options for WebDAV in Python, but I'd like to know which are in wider use these days. </p>
22
2009-10-08T17:38:32Z
26,562,880
<p>Install:</p> <pre><code>$ sudo apt-get install libxml2-dev libxslt-dev python-dev $ sudo apt-get install libcurl4-openssl-dev python-pycurl $ sudo easy_install webdavclient </code></pre> <p>Examples:</p> <pre><code>import webdav.client as wc options = { 'webdav_hostname': "https://webdav.server.ru", 'webdav_login': "login", 'webdav_password': "password" } client = wc.Client(options) client.check("dir1/file1") client.info("dir1/file1") files = client.list() free_size = client.free() client.mkdir("dir1/dir2") client.clean("dir1/dir2") client.copy(remote_path_from="dir1/file1", remote_path_to="dir2/file1") client.move(remote_path_from="dir1/file1", remote_path_to="dir2/file1") client.download_sync(remote_path="dir1/file1", local_path="~/Downloads/file1") client.upload_sync(remote_path="dir1/file1", local_path="~/Documents/file1") client.download_async(remote_path="dir1/file1", local_path="~/Downloads/file1", callback=callback) client.upload_async(remote_path="dir1/file1", local_path="~/Documents/file1", callback=callback) link = client.publish("dir1/file1") client.unpublish("dir1/file1") </code></pre> <p>Links:</p> <ul> <li>Source code <a href="https://github.com/designerror/webdavclient" rel="nofollow">here</a></li> <li>Packet <a href="https://pypi.python.org/pypi/webdavclient/0.3.0" rel="nofollow">here</a></li> </ul>
0
2014-10-25T13:26:19Z
[ "python", "client", "webdav" ]
Django Reuseable Apps
1,539,485
<p>I came across many resources about the difference between Django projects and reusable apps, most prominently the <a href="http://www.youtube.com/watch?v=A-S0tqpPga4" rel="nofollow">DjangoCon talk</a>, and <a href="http://pinaxproject.com/" rel="nofollow">Pinax Project</a>.</p> <p>However, being a newbie, writing my own projects and reusable software seems to a bit challenging. I don't quite understand how where models go (and how apps can be flexible and permissive), where the templates go, and how the different apps mesh together.</p> <p>Are there any tutorials on creating a project with reusable apps? Good practices page? Most preferably, a sample project with its own apps (rather than depend on external apps)?</p> <p>I am aiming to understand the architecture of a project and interaction between apps rather than just building reusable apps. Most tutorials I came across online are about building a reusable app, or building a simple monothelic blog app that only has external dependencies on builtin or django.contrib modules.</p>
2
2009-10-08T17:59:07Z
1,539,732
<p>James Bennett's <a href="http://rads.stackoverflow.com/amzn/click/1430219386" rel="nofollow">Practical Django Projects</a> does a pretty good job of covering those topics in general and even includes a chapter specifically on "Writing Reusable Django Applications" that goes through an example of splitting one of the example projects in the book out into its own app.</p>
4
2009-10-08T18:48:24Z
[ "python", "django", "django-apps" ]
Django Reuseable Apps
1,539,485
<p>I came across many resources about the difference between Django projects and reusable apps, most prominently the <a href="http://www.youtube.com/watch?v=A-S0tqpPga4" rel="nofollow">DjangoCon talk</a>, and <a href="http://pinaxproject.com/" rel="nofollow">Pinax Project</a>.</p> <p>However, being a newbie, writing my own projects and reusable software seems to a bit challenging. I don't quite understand how where models go (and how apps can be flexible and permissive), where the templates go, and how the different apps mesh together.</p> <p>Are there any tutorials on creating a project with reusable apps? Good practices page? Most preferably, a sample project with its own apps (rather than depend on external apps)?</p> <p>I am aiming to understand the architecture of a project and interaction between apps rather than just building reusable apps. Most tutorials I came across online are about building a reusable app, or building a simple monothelic blog app that only has external dependencies on builtin or django.contrib modules.</p>
2
2009-10-08T17:59:07Z
1,540,299
<p>You can watch video (DjangoCon 2008: Reusable Apps) - <a href="http://www.youtube.com/watch?v=A-S0tqpPga4" rel="nofollow">http://www.youtube.com/watch?v=A-S0tqpPga4</a> and get the idea, how to use it.</p> <p>There are a lot of reusapbe apps at Google, djangosnippets, git, etc. Most popular:</p> <ul> <li>django-contact-form - feedback form;</li> <li>django-debug-toolbar - watch sql queries and etc;</li> <li>django-registration + django-profiles - skip regs routines;</li> <li>django-mptt - use tree structure;</li> <li>django-pagination - usefull per-page viewer;</li> <li>django-stdimage or sorl-thumbnail - image routines;</li> <li>south - schema migrations;</li> </ul> <p>Read samples docs and save your dev-time. Good luck!</p>
3
2009-10-08T20:39:26Z
[ "python", "django", "django-apps" ]
Django Reuseable Apps
1,539,485
<p>I came across many resources about the difference between Django projects and reusable apps, most prominently the <a href="http://www.youtube.com/watch?v=A-S0tqpPga4" rel="nofollow">DjangoCon talk</a>, and <a href="http://pinaxproject.com/" rel="nofollow">Pinax Project</a>.</p> <p>However, being a newbie, writing my own projects and reusable software seems to a bit challenging. I don't quite understand how where models go (and how apps can be flexible and permissive), where the templates go, and how the different apps mesh together.</p> <p>Are there any tutorials on creating a project with reusable apps? Good practices page? Most preferably, a sample project with its own apps (rather than depend on external apps)?</p> <p>I am aiming to understand the architecture of a project and interaction between apps rather than just building reusable apps. Most tutorials I came across online are about building a reusable app, or building a simple monothelic blog app that only has external dependencies on builtin or django.contrib modules.</p>
2
2009-10-08T17:59:07Z
1,544,591
<p>If you want to see "sample projects with reusable apps interacting with each other," there's no better place to go than downloading <a href="http://pinaxproject.com" rel="nofollow">Pinax</a>, cloning one of their sample projects (just follow the docs) and reading through the code carefully.</p>
3
2009-10-09T15:43:45Z
[ "python", "django", "django-apps" ]
Changing document's attributes in Python's xml.dom.minidom
1,539,555
<p>I created a <code>xml.dom.minidom.Document</code>.</p> <p>How do I give it attributes so that when I do <code>.toprettyxml()</code> it will show like this:</p> <p><code>&lt;?xml version="1.0" encoding="iso-8859-2"?&gt;</code></p>
0
2009-10-08T18:09:28Z
1,539,569
<p><code>.toprettyxml()</code> has an encoding keyword argument:</p> <pre><code>Document.toprettyxml(self, indent='\t', newl='\n', encoding=None) </code></pre>
1
2009-10-08T18:14:04Z
[ "python", "xml" ]
Determine which Button was pressed in Tkinter?
1,539,787
<p>I'm making a simple little utility while learning Python. It dynamically generates a list of buttons:</p> <pre><code>for method in methods: button = Button(self.methodFrame, text=method, command=self.populateMethod) button.pack({'fill': 'x', 'expand': 1, 'padx': 5, 'pady': 3}) </code></pre> <p>That part works fine. However, I need to know which of the buttons was pressed inside <code>self.populateMethod</code>. Any advice on how I might be able to tell?</p>
6
2009-10-08T18:59:23Z
1,539,868
<p>It seems that the command method is not passed any event object.</p> <p>I can think of two workarounds:</p> <ul> <li><p>associate a unique callback to each button</p></li> <li><p>call <code>button.bind('&lt;Button-1&gt;', self.populateMethod)</code> instead of passing self.populateMethod as <code>command</code>. self.populateMethod must then accept a second argument which will be an event object.</p> <p>Assuming that this second argument is called <code>event</code>, <code>event.widget</code> is a reference to the button that was clicked.</p></li> </ul>
1
2009-10-08T19:15:08Z
[ "python", "button", "tkinter" ]
Determine which Button was pressed in Tkinter?
1,539,787
<p>I'm making a simple little utility while learning Python. It dynamically generates a list of buttons:</p> <pre><code>for method in methods: button = Button(self.methodFrame, text=method, command=self.populateMethod) button.pack({'fill': 'x', 'expand': 1, 'padx': 5, 'pady': 3}) </code></pre> <p>That part works fine. However, I need to know which of the buttons was pressed inside <code>self.populateMethod</code>. Any advice on how I might be able to tell?</p>
6
2009-10-08T18:59:23Z
1,543,336
<p>You can use lambda to pass arguments to a command:</p> <pre><code>def populateMethod(self, method): print "method:", method for method in ["one","two","three"]: button = Button(self.methodFrame, text=method, command=lambda m=method: self.populateMethod(m)) button.pack({'fill': 'x', 'expand': 1, 'padx': 5, 'pady': 3}) </code></pre>
11
2009-10-09T11:51:46Z
[ "python", "button", "tkinter" ]
Python HTTP server with XML-RPC
1,540,011
<p>I have a server that has to respond to HTTP and XML-RPC requests. Right now I have an instance of SimpleXMLRPCServer, and an instance of BaseHTTPServer.HTTPServer with a custom request handler, running on different ports. I'd like to run both services on a single port. </p> <p>I think it should be possible to modify the CGIXMLRPCRequestHandler class to also serve custom HTTP requests on some paths, or alternately, to use multiple request handlers based on what path is requested. I'm not really sure what the cleanest way to do this would be, though.</p>
0
2009-10-08T19:45:52Z
1,540,053
<p>Is there a reason not to run a real webserver out front with url rewrites to the two ports you are usign now? It's going to make life much easier in the long run</p>
0
2009-10-08T19:55:17Z
[ "python", "http", "xml-rpc" ]
Python HTTP server with XML-RPC
1,540,011
<p>I have a server that has to respond to HTTP and XML-RPC requests. Right now I have an instance of SimpleXMLRPCServer, and an instance of BaseHTTPServer.HTTPServer with a custom request handler, running on different ports. I'd like to run both services on a single port. </p> <p>I think it should be possible to modify the CGIXMLRPCRequestHandler class to also serve custom HTTP requests on some paths, or alternately, to use multiple request handlers based on what path is requested. I'm not really sure what the cleanest way to do this would be, though.</p>
0
2009-10-08T19:45:52Z
1,543,370
<p>Use <code>SimpleXMLRPCDispatcher</code> class directly from your own request handler.</p>
0
2009-10-09T11:59:43Z
[ "python", "http", "xml-rpc" ]
Python HTTP server with XML-RPC
1,540,011
<p>I have a server that has to respond to HTTP and XML-RPC requests. Right now I have an instance of SimpleXMLRPCServer, and an instance of BaseHTTPServer.HTTPServer with a custom request handler, running on different ports. I'd like to run both services on a single port. </p> <p>I think it should be possible to modify the CGIXMLRPCRequestHandler class to also serve custom HTTP requests on some paths, or alternately, to use multiple request handlers based on what path is requested. I'm not really sure what the cleanest way to do this would be, though.</p>
0
2009-10-08T19:45:52Z
21,441,674
<p>Simplest way would be (tested for Python 3.3 but should work for 2.x with modified imports):</p> <pre><code>from http.server import SimpleHTTPRequestHandler from xmlrpc.server import SimpleXMLRPCRequestHandler,SimpleXMLRPCServer class MixRequestHandler(SimpleHTTPRequestHandler,SimpleXMLRPCRequestHandler): pass srv=SimpleXMLRPCServer(("localhost",8080),MixRequestHandler) #normal stuff for SimpleXMLRPCServer </code></pre>
0
2014-01-29T20:15:01Z
[ "python", "http", "xml-rpc" ]
Replace values in list using Python
1,540,049
<p>I have a list where I want to replace values with None where condition() returns True.</p> <pre><code>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </code></pre> <p>For example, if condition checks bool(item%2) should return:</p> <pre><code>[None, 1, None, 3, None, 5, None, 7, None, 9, None] </code></pre> <p>What is the most efficient way to do this?</p>
59
2009-10-08T19:54:18Z
1,540,060
<pre><code>&gt;&gt;&gt; L = range (11) &gt;&gt;&gt; [ x if x%2 == 1 else None for x in L ] [None, 1, None, 3, None, 5, None, 7, None, 9, None] </code></pre>
2
2009-10-08T19:57:34Z
[ "python", "list", "performance", "replace" ]
Replace values in list using Python
1,540,049
<p>I have a list where I want to replace values with None where condition() returns True.</p> <pre><code>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </code></pre> <p>For example, if condition checks bool(item%2) should return:</p> <pre><code>[None, 1, None, 3, None, 5, None, 7, None, 9, None] </code></pre> <p>What is the most efficient way to do this?</p>
59
2009-10-08T19:54:18Z
1,540,069
<p>The most efficient:</p> <pre><code>items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for index, item in enumerate(items): if not (item % 2): items[index] = None </code></pre> <p>The easiest to read:</p> <pre><code>new_items = [x if x % 2 else None for x in items] </code></pre>
90
2009-10-08T19:58:50Z
[ "python", "list", "performance", "replace" ]
Replace values in list using Python
1,540,049
<p>I have a list where I want to replace values with None where condition() returns True.</p> <pre><code>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </code></pre> <p>For example, if condition checks bool(item%2) should return:</p> <pre><code>[None, 1, None, 3, None, 5, None, 7, None, 9, None] </code></pre> <p>What is the most efficient way to do this?</p>
59
2009-10-08T19:54:18Z
1,540,071
<pre><code>ls = [x if (condition) else None for x in ls] </code></pre>
44
2009-10-08T19:58:57Z
[ "python", "list", "performance", "replace" ]
Replace values in list using Python
1,540,049
<p>I have a list where I want to replace values with None where condition() returns True.</p> <pre><code>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </code></pre> <p>For example, if condition checks bool(item%2) should return:</p> <pre><code>[None, 1, None, 3, None, 5, None, 7, None, 9, None] </code></pre> <p>What is the most efficient way to do this?</p>
59
2009-10-08T19:54:18Z
1,541,791
<p>Riffing on a side question asked by the OP in a comment, i.e.:</p> <blockquote> <p>what if I had a generator that yields the values from range(11) instead of a list. Would it be possible to replace values in the generator?</p> </blockquote> <p>Sure, it's trivially easy...:</p> <pre><code>def replaceiniter(it, predicate, replacement=None): for item in it: if predicate(item): yield replacement else: yield item </code></pre> <p>Just pass any iterable (including the result of calling a generator) as the first arg, the predicate to decide if a value must be replaced as the second arg, and let 'er rip.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; list(replaceiniter(xrange(11), lambda x: x%2)) [0, None, 2, None, 4, None, 6, None, 8, None, 10] </code></pre>
10
2009-10-09T04:29:08Z
[ "python", "list", "performance", "replace" ]
Replace values in list using Python
1,540,049
<p>I have a list where I want to replace values with None where condition() returns True.</p> <pre><code>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </code></pre> <p>For example, if condition checks bool(item%2) should return:</p> <pre><code>[None, 1, None, 3, None, 5, None, 7, None, 9, None] </code></pre> <p>What is the most efficient way to do this?</p>
59
2009-10-08T19:54:18Z
1,543,104
<p>Here's another way:</p> <pre><code>&gt;&gt;&gt; L = range (11) &gt;&gt;&gt; map(lambda x: x if x%2 else None, L) [None, 1, None, 3, None, 5, None, 7, None, 9, None] </code></pre>
5
2009-10-09T10:54:17Z
[ "python", "list", "performance", "replace" ]
How to print the function name as a string in Python from inside that function
1,540,177
<pre><code>def applejuice(q): print THE FUNCTION NAME! </code></pre> <p>It should result in "applejuice" as a string.</p>
6
2009-10-08T20:21:45Z
1,540,189
<p>You need to explain what your problem is. Because the answer to your question is:</p> <pre><code>print "applejuice" </code></pre>
3
2009-10-08T20:23:38Z
[ "python" ]
How to print the function name as a string in Python from inside that function
1,540,177
<pre><code>def applejuice(q): print THE FUNCTION NAME! </code></pre> <p>It should result in "applejuice" as a string.</p>
6
2009-10-08T20:21:45Z
1,540,211
<pre><code>def applejuice(**args): print "Running the function 'applejuice'" pass </code></pre> <p>or use:</p> <pre><code>myfunc.__name__ &gt;&gt;&gt; print applejuice.__name__ 'applejuice' </code></pre> <p>Also, see <a href="http://stackoverflow.com/questions/251464/how-to-get-the-function-name-as-string-in-python">how-to-get-the-function-name-as-string-in-python</a></p>
7
2009-10-08T20:27:10Z
[ "python" ]
How to print the function name as a string in Python from inside that function
1,540,177
<pre><code>def applejuice(q): print THE FUNCTION NAME! </code></pre> <p>It should result in "applejuice" as a string.</p>
6
2009-10-08T20:21:45Z
1,540,215
<pre><code>import traceback def applejuice(q): stack = traceback.extract_stack() (filename, line, procname, text) = stack[-1] print procname </code></pre> <p>I assume this is used for debugging, so you might want to look into the other procedures offered by the <a href="http://docs.python.org/library/traceback.html"><code>traceback</code> module</a>. They'll let you print the entire call stack, exception traces, etc.</p>
7
2009-10-08T20:28:04Z
[ "python" ]
How to print the function name as a string in Python from inside that function
1,540,177
<pre><code>def applejuice(q): print THE FUNCTION NAME! </code></pre> <p>It should result in "applejuice" as a string.</p>
6
2009-10-08T20:21:45Z
1,540,245
<p>Another way</p> <pre><code>import inspect def applejuice(q): print inspect.getframeinfo(inspect.currentframe())[2] </code></pre>
3
2009-10-08T20:31:39Z
[ "python" ]
How to print the function name as a string in Python from inside that function
1,540,177
<pre><code>def applejuice(q): print THE FUNCTION NAME! </code></pre> <p>It should result in "applejuice" as a string.</p>
6
2009-10-08T20:21:45Z
1,540,257
<p>This also works:</p> <pre><code>import sys def applejuice(q): func_name = sys._getframe().f_code.co_name print func_name </code></pre>
13
2009-10-08T20:33:18Z
[ "python" ]
How to print the function name as a string in Python from inside that function
1,540,177
<pre><code>def applejuice(q): print THE FUNCTION NAME! </code></pre> <p>It should result in "applejuice" as a string.</p>
6
2009-10-08T20:21:45Z
17,332,402
<pre><code>def foo(): # a func can just make a call to itself and fetch the name funcName = foo.__name__ # print it print 'Internal: {0}'.format(funcName) # return it return funcName # you can fetch the name externally fooName = foo.__name__ print 'The name of {0} as fetched: {0}'.format(fooName) # print what name foo returned in this example whatIsTheName = foo() print 'The name foo returned is: {0}'.format(whatIsTheName) </code></pre>
0
2013-06-26T23:59:17Z
[ "python" ]
How to print the function name as a string in Python from inside that function
1,540,177
<pre><code>def applejuice(q): print THE FUNCTION NAME! </code></pre> <p>It should result in "applejuice" as a string.</p>
6
2009-10-08T20:21:45Z
29,151,834
<p>This site gave me a decent explanation of how sys._getframe.f_code.co_name works that returns the function name. </p> <p><a href="http://code.activestate.com/recipes/66062-determining-current-function-name/" rel="nofollow">http://code.activestate.com/recipes/66062-determining-current-function-name/</a></p>
1
2015-03-19T17:59:40Z
[ "python" ]
Why isn't getopt working if sys.argv is passed fully?
1,540,365
<p>If I'm using this with <code>getopt</code>:</p> <pre><code>import getopt import sys opts,args = getopt.getopt(sys.argv,"a:bc") print opts print args </code></pre> <p><code>opts</code> will be empty. No tuples will be created. If however, I'll use <code>sys.argv[1:]</code>, everything works as expected. I don't understand why that is. Anyone care to explain?</p>
4
2009-10-08T20:48:48Z
1,540,392
<p>It's by design. Recall that sys.argv[0] is the running program name, and getopt doesn't want it.</p> <p>From the docs:</p> <blockquote> <p>Parses command line options and parameter list. args is the argument list to be parsed, without the leading reference to the running program. Typically, this means sys.argv[1:]. options is the string of option letters that the script wants to recognize, with options that require an argument followed by a colon (':'; i.e., the same format that Unix getopt() uses).</p> </blockquote> <p><a href="http://docs.python.org/library/getopt.html">http://docs.python.org/library/getopt.html</a></p>
6
2009-10-08T20:51:45Z
[ "python", "getopt" ]
Why isn't getopt working if sys.argv is passed fully?
1,540,365
<p>If I'm using this with <code>getopt</code>:</p> <pre><code>import getopt import sys opts,args = getopt.getopt(sys.argv,"a:bc") print opts print args </code></pre> <p><code>opts</code> will be empty. No tuples will be created. If however, I'll use <code>sys.argv[1:]</code>, everything works as expected. I don't understand why that is. Anyone care to explain?</p>
4
2009-10-08T20:48:48Z
1,540,399
<p>The first element of <code>sys.argv</code> (<code>sys.argv[0]</code>) is the name of the script currently being executed. Because this script name is (likely) not a valid argument (and probably doesn't begin with a <code>-</code> or <code>--</code> anyway), <code>getopt</code> does not recognize it as an argument. Due to the nature of how <code>getopt</code> works, when it sees something that is not a command-line flag (something that does not begin with <code>-</code> or <code>--</code>), it stops processing command-line options (and puts the rest of the arguments into <code>args</code>), because it assumes the rest of the arguments are items that will be handled by the program (such as filenames or other "required" arguments).</p>
11
2009-10-08T20:53:25Z
[ "python", "getopt" ]
Recurrence sequence in Java / Python / Mathematica
1,540,519
<p><strong>How can you write the following statement in the given languages?</strong></p> <pre><code>a(0) = 1 a_(n+1) = 1 - 1 / ( a_n + 3) </code></pre> <p>I need to find the smallest value of <code>n</code> when <code>a_n -&gt; 0.732050...</code>.</p> <p><strong>My attempt in Mathematica</strong></p> <pre><code>a[(x+1)_] = 1 - 1/(a[x_] + 3) </code></pre> <p>The problem is apparently in this <code>a[(x+1)_]</code>. However, I do not know how to do it iteratively in Mathematica.</p>
3
2009-10-08T21:12:03Z
1,540,601
<p>Java</p> <pre><code>double A = 1; int n = 0; while (true) { System.out.println(n + " " + A); A = 1 - 1 / (A + 3); n++; } </code></pre> <p>Python</p> <pre><code>A = 1.0 n = 0 while 1: print n, A A = 1 - 1 / (A + 3) n += 1 </code></pre>
3
2009-10-08T21:27:20Z
[ "java", "python", "wolfram-mathematica", "sequence" ]
Recurrence sequence in Java / Python / Mathematica
1,540,519
<p><strong>How can you write the following statement in the given languages?</strong></p> <pre><code>a(0) = 1 a_(n+1) = 1 - 1 / ( a_n + 3) </code></pre> <p>I need to find the smallest value of <code>n</code> when <code>a_n -&gt; 0.732050...</code>.</p> <p><strong>My attempt in Mathematica</strong></p> <pre><code>a[(x+1)_] = 1 - 1/(a[x_] + 3) </code></pre> <p>The problem is apparently in this <code>a[(x+1)_]</code>. However, I do not know how to do it iteratively in Mathematica.</p>
3
2009-10-08T21:12:03Z
1,540,622
<p>Mathematica:</p> <pre><code>a[0] := 1 a[k_] := 1 - 1/(a[k - 1] + 3) </code></pre> <p>I substituted k = n + 1 because that makes the expression simpler. The result is equivalent.</p>
3
2009-10-08T21:30:28Z
[ "java", "python", "wolfram-mathematica", "sequence" ]