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
Python value unpacking error
1,144,953
<p>I'm building a per-user file browsing/uploading application using Django and when I run this function</p> <pre><code> def walkdeep(request, path): path, dirs, files = walktoo('/home/damon/walktemp/%s' % path) return render_to_response('walk.html', { 'path' : path[0], 'dirs' : path[1], 'files' : path[2], }, context_instance=RequestContext(request)) def walktoo(dir): for path, dirs, files in os.walk(dir): yield path, dirs, files print path, dirs, files </code></pre> <p>I get this error:</p> <p><code>need more than 1 value to unpack</code></p> <p>Also, i know this is a silly way to do this, any advice would be appreciated.</p> <p>edit:</p> <p>this was actually very silly on my part, i completely forgot about os.listdir(dir) which is a much more reasonable function for my purposes. if you use the selected answer, it clears up the above issue i was having, but not with the results i wanted.</p>
0
2009-07-17T18:31:32Z
1,144,987
<pre><code>path, dirs, files = walktoo('/home/damon/walktemp/%s' % path) </code></pre> <p>In this line, you're expecting <code>walktoo</code> to return a tuple of three values, which are then to be unpacked into <code>path</code>, <code>dirs</code>, and <code>files</code>. However, your <code>walktoo</code> function is a generator object: calling <code>walktoo()</code> yields a single value, the generator. You have to call <code>next()</code> on the generator (or call it implicitly by doing some sort of iteration on it) to get what you actually want, namely the 3-tuple that it yields.</p> <p>I'm not entirely clear what you want to do -- your <code>walkdeep()</code> function is written like it only wants to use the first value returned by <code>walktoo()</code>. Did you mean to do something like this?</p> <pre><code>for path, dirs, files in walktoo(...): # do something </code></pre>
7
2009-07-17T18:38:19Z
[ "python", "django" ]
Python value unpacking error
1,144,953
<p>I'm building a per-user file browsing/uploading application using Django and when I run this function</p> <pre><code> def walkdeep(request, path): path, dirs, files = walktoo('/home/damon/walktemp/%s' % path) return render_to_response('walk.html', { 'path' : path[0], 'dirs' : path[1], 'files' : path[2], }, context_instance=RequestContext(request)) def walktoo(dir): for path, dirs, files in os.walk(dir): yield path, dirs, files print path, dirs, files </code></pre> <p>I get this error:</p> <p><code>need more than 1 value to unpack</code></p> <p>Also, i know this is a silly way to do this, any advice would be appreciated.</p> <p>edit:</p> <p>this was actually very silly on my part, i completely forgot about os.listdir(dir) which is a much more reasonable function for my purposes. if you use the selected answer, it clears up the above issue i was having, but not with the results i wanted.</p>
0
2009-07-17T18:31:32Z
1,145,235
<p>Based on your comment to <a href="http://stackoverflow.com/users/9530/adam-rosenfield">Adam Rosenfield</a>, this is another approach to get one layer of os.walk(dir).</p> <pre><code>path, dirs, files = [_ for _ in os.walk('/home/damon/walktemp/%s' % path)][0] </code></pre> <p>This is as an alternative to your walktoo(dir) funciton.</p> <p>Also, make sure your second parameter to <code>render_to_response</code> uses the variables you created:</p> <pre><code>{'path' : path, 'dirs' : dirs, 'files' : files,} </code></pre> <p><code>path</code> is a string, so by saying <code>path[0]</code> ... <code>path[1]</code> ... <code>path[2]</code> you're actually saying to use the first, second, and third character of the string.</p>
1
2009-07-17T19:33:00Z
[ "python", "django" ]
XML parsing expat in python handling data
1,145,015
<p>I am attempting to parse an XML file using python expat. I have the following line in my XML file:</p> <pre><code>&lt;Action&gt;&amp;lt;fail/&amp;gt;&lt;/Action&gt; </code></pre> <p>expat identifies the start and end tags but converts the &amp; lt; to the less than character and the same for the greater than character and thus parses it like this:</p> <p>outcome:</p> <pre><code>START 'Action' DATA '&lt;' DATA 'fail/' DATA '&gt;' END 'Action' </code></pre> <p>instead of the desired:</p> <pre><code>START 'Action' DATA '&amp;lt;fail/&amp;gt;' END 'Action' </code></pre> <p>I would like to have the desired outcome, how do I prevent expat from messing up?</p>
0
2009-07-17T18:44:04Z
1,145,032
<p>expat does not mess up, <code>&amp;lt;</code> is simply the XML encoding for the character <code>&lt;</code>. Quite to the contrary, if expat would return the literal <code>&amp;lt;</code>, this would be a bug with respect to the XML spec. That being said, you can of course get the escaped version back by using <code>xml.sax.saxutils.escape</code>:</p> <pre><code>&gt;&gt;&gt; from xml.sax.saxutils import escape &gt;&gt;&gt; escape("&lt;fail/&gt;") '&amp;lt;fail/&amp;gt;' </code></pre> <p>The expat parser is also free to report all string data in whatever chunks it seems fit, so you have to concatenate them yourself.</p>
2
2009-07-17T18:49:20Z
[ "python", "xml", "parsing", "expat-parser" ]
XML parsing expat in python handling data
1,145,015
<p>I am attempting to parse an XML file using python expat. I have the following line in my XML file:</p> <pre><code>&lt;Action&gt;&amp;lt;fail/&amp;gt;&lt;/Action&gt; </code></pre> <p>expat identifies the start and end tags but converts the &amp; lt; to the less than character and the same for the greater than character and thus parses it like this:</p> <p>outcome:</p> <pre><code>START 'Action' DATA '&lt;' DATA 'fail/' DATA '&gt;' END 'Action' </code></pre> <p>instead of the desired:</p> <pre><code>START 'Action' DATA '&amp;lt;fail/&amp;gt;' END 'Action' </code></pre> <p>I would like to have the desired outcome, how do I prevent expat from messing up?</p>
0
2009-07-17T18:44:04Z
1,145,808
<p>Both SAX and StAX parsers are free to break up the strings in whatever way is convenient for them (although StAX has a COALESCE mode for forcing it to assemble the pieces for you).</p> <p>The reason is that it is often possible to write software in certain cases that streams and doesn't have to care about the overhead of reassembling the string fragments.</p> <p>Usually I accumulate text in a variable, and use the contents when I see the next StartElement or EndElement event. At that point, I also reset the accumulated-text variable to empty.</p>
0
2009-07-17T21:37:28Z
[ "python", "xml", "parsing", "expat-parser" ]
Change python file in place
1,145,286
<p>I have a large xml file (40 Gb) that I need to split into smaller chunks. I am working with limited space, so is there a way to delete lines from the original file as I write them to new files?</p> <p>Thanks!</p>
8
2009-07-17T19:41:37Z
1,145,329
<p>I'm pretty sure there is, as I've even been able to edit/read from the source files of scripts I've run, but the biggest problem would probably be all the shifting that would be done if you started at the beginning of the file. On the other hand, if you go through the file and record all the starting positions of the lines, you could then go in reverse order of position to copy the lines out; once that's done, you could go back, take the new files, one at a time, and (if they're small enough), use readlines() to generate a list, reverse the order of the list, then seek to the beginning of the file and overwrite the lines in their old order with the lines in their new one.</p> <p>(You would truncate the file after reading the first block of lines from the end by using the <code>truncate()</code> method, which truncates all data past the current file position if used without any arguments besides that of the file object, assuming you're using one of the classes or a subclass of one of the classes from the <code>io</code> package to read your file. You'd just have to make sure that the current file position ends up at the beginning of the last line to be written to a new file.)</p> <p>EDIT: Based on your comment about having to make the separations at the proper closing tags, you'll probably also have to develop an algorithm to detect such tags (perhaps using the <code>peek</code> method), possibly using a regular expression.</p>
1
2009-07-17T19:51:14Z
[ "python", "file" ]
Change python file in place
1,145,286
<p>I have a large xml file (40 Gb) that I need to split into smaller chunks. I am working with limited space, so is there a way to delete lines from the original file as I write them to new files?</p> <p>Thanks!</p>
8
2009-07-17T19:41:37Z
1,145,338
<p>If you're on Linux/Unix, why not use the split command like <a href="http://www.techiecorner.com/107/how-to-split-large-file-into-several-smaller-files-linux/" rel="nofollow">this guy</a> does?</p> <pre><code>split --bytes=100m /input/file /output/dir/prefix </code></pre> <p>EDIT: then use <a href="http://linux.die.net/man/1/csplit" rel="nofollow">csplit</a>.</p>
2
2009-07-17T19:53:04Z
[ "python", "file" ]
Change python file in place
1,145,286
<p>I have a large xml file (40 Gb) that I need to split into smaller chunks. I am working with limited space, so is there a way to delete lines from the original file as I write them to new files?</p> <p>Thanks!</p>
8
2009-07-17T19:41:37Z
1,145,341
<p>If time is not a major factor (or wear and tear on your disk drive):</p> <ol> <li>Open handle to file</li> <li>Read up to the size of your partition / logical break point (due to the xml)</li> <li>Save the rest of your file to disk (not sure how python handles this as far as directly overwriting file or memory usage)</li> <li>Write the partition to disk</li> <li>goto 1</li> </ol> <p>If Python does not give you this level of control, you may need to dive into C.</p>
0
2009-07-17T19:53:35Z
[ "python", "file" ]
Change python file in place
1,145,286
<p>I have a large xml file (40 Gb) that I need to split into smaller chunks. I am working with limited space, so is there a way to delete lines from the original file as I write them to new files?</p> <p>Thanks!</p>
8
2009-07-17T19:41:37Z
1,145,417
<p>You could always parse the XML file and write out say every 10000 elements to there own file. Look at the Incremental Parsing section of this link. <a href="http://effbot.org/zone/element-iterparse.htm" rel="nofollow">http://effbot.org/zone/element-iterparse.htm</a></p>
0
2009-07-17T20:06:57Z
[ "python", "file" ]
Change python file in place
1,145,286
<p>I have a large xml file (40 Gb) that I need to split into smaller chunks. I am working with limited space, so is there a way to delete lines from the original file as I write them to new files?</p> <p>Thanks!</p>
8
2009-07-17T19:41:37Z
1,145,434
<p>Say you want to split the file into N pieces, then simply start reading from the back of the file (more or less) and repeatedly call <a href="http://docs.python.org/library/stdtypes.html?highlight=truncate#file.truncate" rel="nofollow">truncate</a>:</p> <blockquote> <p>Truncate the file's size. If the optional size argument is present, the file is truncated to (at most) that size. The size defaults to the current position. The current file position is not changed. ...</p> </blockquote> <pre class="lang-py prettyprint-override"><code>import os import stat BUF_SIZE = 4096 size = os.stat("large_file")[stat.ST_SIZE] chunk_size = size // N # or simply set a fixed chunk size based on your free disk space c = 0 in_ = open("large_file", "r+") while size &gt; 0: in_.seek(-min(size, chunk_size), 2) # now you have to find a safe place to split the file at somehow # just read forward until you found one ... old_pos = in_.tell() with open("small_chunk%2d" % (c, ), "w") as out: b = in_.read(BUF_SIZE) while len(b) &gt; 0: out.write(b) b = in_.read(BUF_SIZE) in_.truncate(old_pos) size = old_pos c += 1 </code></pre> <p>Be careful, as I didn't test any of this. It might be needed to call <code>flush</code> after the truncate call, and I don't know how fast the file system is going to actually free up the space. </p>
7
2009-07-17T20:11:07Z
[ "python", "file" ]
Change python file in place
1,145,286
<p>I have a large xml file (40 Gb) that I need to split into smaller chunks. I am working with limited space, so is there a way to delete lines from the original file as I write them to new files?</p> <p>Thanks!</p>
8
2009-07-17T19:41:37Z
1,148,604
<p>Its a time to buy a new hard drive!</p> <p>You can make backup before trying all other answers and don't get data lost :)</p>
-1
2009-07-18T21:25:10Z
[ "python", "file" ]
Change python file in place
1,145,286
<p>I have a large xml file (40 Gb) that I need to split into smaller chunks. I am working with limited space, so is there a way to delete lines from the original file as I write them to new files?</p> <p>Thanks!</p>
8
2009-07-17T19:41:37Z
1,154,128
<p>Here is my script...</p> <pre><code>import string import os from ftplib import FTP # make ftp connection ftp = FTP('server') ftp.login('user', 'pwd') ftp.cwd('/dir') f1 = open('large_file.xml', 'r') size = 0 split = False count = 0 for line in f1: if not split: file = 'split_'+str(count)+'.xml' f2 = open(file, 'w') if count &gt; 0: f2.write('&lt;?xml version="1.0"?&gt;\n') f2.write('&lt;StartTag xmlns="http://www.blah/1.2.0"&gt;\n') size = 0 count += 1 split = True if size &lt; 1073741824: f2.write(line) size += len(line) elif str(line) == '&lt;/EndTag&gt;\n': f2.write(line) f2.write('&lt;/EndEndTag&gt;\n') print('completed file %s' %str(count)) f2.close() f2 = open(file, 'r') print("ftp'ing file...") ftp.storbinary('STOR ' + file, f2) print('ftp done.') split = False f2.close() os.remove(file) else: f2.write(line) size += len(line) </code></pre>
0
2009-07-20T15:07:04Z
[ "python", "file" ]
Using URLS that accept slashes as part of the parameter in Django
1,145,334
<p>Is there a way in Django to accept 'n' parameters which are delimited by a '/' (forward slash)?</p> <p>I was thinking this may work, but it does not. Django still recognizes forward slashes as delimiters.</p> <pre><code>(r'^(?P&lt;path&gt;[-\w]+/)$', 'some.view', {}), </code></pre>
0
2009-07-17T19:52:05Z
1,145,393
<p>Certainly, Django can accept any URL which can be described by a regular expression - including one which has a prefix followed by a '/' followed by a variable number of segments separated by '/'. The exact regular expression will depend on what you want to accept - but an example in Django is given by /admin URLs which parse the suffix of the URL in the view.</p>
1
2009-07-17T20:02:04Z
[ "python", "django" ]
Using URLS that accept slashes as part of the parameter in Django
1,145,334
<p>Is there a way in Django to accept 'n' parameters which are delimited by a '/' (forward slash)?</p> <p>I was thinking this may work, but it does not. Django still recognizes forward slashes as delimiters.</p> <pre><code>(r'^(?P&lt;path&gt;[-\w]+/)$', 'some.view', {}), </code></pre>
0
2009-07-17T19:52:05Z
1,145,418
<p>Add the right url to your urlpatterns:</p> <pre><code># ... ("^foo/(.*)$", "foo"), # or whatever # ... </code></pre> <p>And process it in your view, like AlbertoPL said:</p> <pre><code>fields = paramPassedInAccordingToThatUrl.split('/') </code></pre>
4
2009-07-17T20:06:59Z
[ "python", "django" ]
Difference between "inspect" and "interactive" command line flags in Python
1,145,428
<p>What is the difference between "inspect" and "interactive" flags? The <a href="http://docs.python.org/library/sys.html#sys.flags" rel="nofollow">sys.flags function</a> prints both of them.</p> <p>How can they both have "-i" flag according to the documentation of sys.flags?</p> <p>How can I set them separately? If I use "python -i", both of them will be set to 1.</p> <h3>Related:</h3> <ul> <li><a href="http://stackoverflow.com/questions/640389/tell-whether-python-is-in-i-mode/640405">tell whether python is in -i mode</a></li> </ul>
4
2009-07-17T20:09:49Z
1,145,452
<p><code>man python</code> says about the <code>-i</code> flag:</p> <blockquote> <p>When a script is passed as first argument or the -c option is used, enter interactive mode after executing the script or the command. It does not read the $PYTHONSTARTUP file. This can be useful to inspect global variables or a stack trace when a script raises an exception.</p> </blockquote> <p>Hence <code>-i</code> allows <strong>inspection</strong> of a script in <strong>interactive</strong> mode. <code>-i</code> <em>implies</em> both of these things. <strike>You can be interactive without inspecting (namely by just calling <code>python</code>, without arguments), but not vice versa.</strike></p>
0
2009-07-17T20:14:52Z
[ "python", "command-line", "interpreter" ]
Difference between "inspect" and "interactive" command line flags in Python
1,145,428
<p>What is the difference between "inspect" and "interactive" flags? The <a href="http://docs.python.org/library/sys.html#sys.flags" rel="nofollow">sys.flags function</a> prints both of them.</p> <p>How can they both have "-i" flag according to the documentation of sys.flags?</p> <p>How can I set them separately? If I use "python -i", both of them will be set to 1.</p> <h3>Related:</h3> <ul> <li><a href="http://stackoverflow.com/questions/640389/tell-whether-python-is-in-i-mode/640405">tell whether python is in -i mode</a></li> </ul>
4
2009-07-17T20:09:49Z
1,145,777
<p>According to <a href="http://svn.python.org/view/python/trunk/Python/pythonrun.c?view=markup" rel="nofollow">pythonrun.c</a> corresponding <code>Py_InspectFlag</code> and <code>Py_InteractiveFlag</code> are used as follows:</p> <pre class="lang-c prettyprint-override"><code>int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */ /* snip */ static void handle_system_exit(void) { PyObject *exception, *value, *tb; int exitcode = 0; if (Py_InspectFlag) /* Don't exit if -i flag was given. This flag is set to 0 * when entering interactive mode for inspecting. */ return; /* snip */ } </code></pre> <p>Python doesn't exit on <code>SystemExit</code> if "inspect" flag is true.</p> <pre class="lang-c prettyprint-override"><code>int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */ /* snip */ /* * The file descriptor fd is considered ``interactive'' if either * a) isatty(fd) is TRUE, or * b) the -i flag was given, and the filename associated with * the descriptor is NULL or "&lt;stdin&gt;" or "???". */ int Py_FdIsInteractive(FILE *fp, const char *filename) { if (isatty((int)fileno(fp))) return 1; if (!Py_InteractiveFlag) return 0; return (filename == NULL) || (strcmp(filename, "&lt;stdin&gt;") == 0) || (strcmp(filename, "???") == 0); } </code></pre> <p>If "interactive" flag is false and current input is not associated with a terminal then python doesn't bother entering "interactive" mode (unbuffering stdout, printing version, showing prompt, etc).</p> <p><code>-i</code> option turns on both flags. "inspect" flag is also on if <code>PYTHONINSPECT</code> environment variable is not empty (see <a href="http://svn.python.org/view/python/trunk/Modules/main.c?view=markup" rel="nofollow">main.c</a>).</p> <p>Basically it means if you set <code>PYTHONINSPECT</code> variable and run your module then python doesn't exit on SystemExit (e.g., at the end of the script) and shows you an interactive prompt instead of (allowing you to inspect your module state (thus "inspect" name for the flag)). </p>
7
2009-07-17T21:28:21Z
[ "python", "command-line", "interpreter" ]
How to make easy_install expand a package into directories rather than a single egg file?
1,145,524
<p>How exactly do I configure my setup.py file so that when someone runs easy_install the package gets expanded into \site-packages\ as a directory, rather than remaining inside an egg.</p> <p>The issue I'm encountering is that one of the django apps I've created won't auto-detect if it resides inside an egg.</p> <p><strong>EDIT:</strong> For example, if I type <code>easy_install photologue</code> it simply installs a <code>\photologue\</code> directory into site-packages. This the the behaviour I'd like, but it seems that in order to make that happen, there needs to be at least one directory/module within the directory being packaged.</p>
3
2009-07-17T20:29:04Z
1,145,611
<p>You add <code>zip_safe = False</code> as an option to setup().</p> <p>I don't think it has to do with directories. Setuptools will happily eggify packages with loads of directories in it.</p> <p>Then of course it's another problem that this part of Django doesn't find the package even though it's zipped. It should.</p>
5
2009-07-17T20:46:35Z
[ "python", "django", "setuptools", "easy-install", "egg" ]
Connection refused when trying to open, write and close a socket a few times (Python)
1,145,540
<p>I have a program that listens on a port waiting for a small amount of data to tell it what to do. I run 5 instances of that program, one on each port from 5000 to 5004 inclusively.</p> <p>I have a second program written in Python that creates a socket "s", writes the data to port 5000, then closes. It then increments the port number and creates a new socket connected to 5001. It does this until it reaches 5004.</p> <p>The first three socket connections work just fine. The programs on ports 5000 to 5002 receive the data just fine and off they go! However, the fourth socket connection results in a "Connection Refused" error message. Meanwhile, the fourth listening program still reports that it is waiting on port 5003 -- I know that it's listening properly because I am able to connect to it using Telnet.</p> <p>I've tried changing the port numbers, and each time it's the fourth connection that fails.</p> <p>Is there some limit in the system I should check on? I only have one socket open at any time on the sending side, and the fact that I can get 3 of the 5 through eliminates a lot of the basic troubleshooting steps I can think of.</p> <p>Any thoughts? Thanks!</p> <p>--- EDIT ---</p> <p>I'm on CentOS Linux with Python version 2.6. Here's some example code:</p> <pre><code>try: portno = 5000 for index, data in enumerate(data_list): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('myhostname', portno)) s.sendall(data) s.close() portno = portno + 1 except socket.error, (value,message): print 'Error: Send could not be performed.\nPort: ' + str(portno) + '\nMessage: ' + message sys.exit(2) </code></pre>
2
2009-07-17T20:32:47Z
1,146,653
<p>This sounds a lot like the anti-portscan measure of your firewall kicking in.</p>
1
2009-07-18T03:40:15Z
[ "python", "sockets", "limit", "max" ]
Connection refused when trying to open, write and close a socket a few times (Python)
1,145,540
<p>I have a program that listens on a port waiting for a small amount of data to tell it what to do. I run 5 instances of that program, one on each port from 5000 to 5004 inclusively.</p> <p>I have a second program written in Python that creates a socket "s", writes the data to port 5000, then closes. It then increments the port number and creates a new socket connected to 5001. It does this until it reaches 5004.</p> <p>The first three socket connections work just fine. The programs on ports 5000 to 5002 receive the data just fine and off they go! However, the fourth socket connection results in a "Connection Refused" error message. Meanwhile, the fourth listening program still reports that it is waiting on port 5003 -- I know that it's listening properly because I am able to connect to it using Telnet.</p> <p>I've tried changing the port numbers, and each time it's the fourth connection that fails.</p> <p>Is there some limit in the system I should check on? I only have one socket open at any time on the sending side, and the fact that I can get 3 of the 5 through eliminates a lot of the basic troubleshooting steps I can think of.</p> <p>Any thoughts? Thanks!</p> <p>--- EDIT ---</p> <p>I'm on CentOS Linux with Python version 2.6. Here's some example code:</p> <pre><code>try: portno = 5000 for index, data in enumerate(data_list): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('myhostname', portno)) s.sendall(data) s.close() portno = portno + 1 except socket.error, (value,message): print 'Error: Send could not be performed.\nPort: ' + str(portno) + '\nMessage: ' + message sys.exit(2) </code></pre>
2
2009-07-17T20:32:47Z
1,147,701
<p>I don't know that much about sockets, so this may be really bad style... use at own risk. This code:</p> <pre><code>#!/usr/bin/python import threading, time from socket import * portrange = range(10000,10005) class Sock(threading.Thread): def __init__(self, port): self.port = port threading.Thread.__init__ ( self ) def start(self): self.s = socket(AF_INET, SOCK_STREAM) self.s.bind(("localhost", self.port)) self.s.listen(1) print "listening on port %i"%self.port threading.Thread.start(self) def run(self): # wait for client to connect connection, address = self.s.accept() data = True while data: data = connection.recv(1024) if data: connection.send('echo %s'%(data)) connection.close() socketHandles = [Sock(port) for port in portrange] for sock in socketHandles: sock.start() # time.sleep(0.5) for port in portrange: print 'sending "ping" to port %i'%port s = socket(AF_INET, SOCK_STREAM) s.connect(("localhost", port)) s.send('ping') data = s.recv(1024) print 'reply was: %s'%data s.close() </code></pre> <p>should output:</p> <pre><code>listening on port 10000 listening on port 10001 listening on port 10002 listening on port 10003 listening on port 10004 sending "ping" to port 10000 reply was: echo ping sending "ping" to port 10001 reply was: echo ping sending "ping" to port 10002 reply was: echo ping sending "ping" to port 10003 reply was: echo ping sending "ping" to port 10004 reply was: echo ping </code></pre> <p>perhaps this will help you see if it's your firewall causing troubles. I suppose you could try splitting this into client and server as well.</p>
1
2009-07-18T14:38:43Z
[ "python", "sockets", "limit", "max" ]
Connection refused when trying to open, write and close a socket a few times (Python)
1,145,540
<p>I have a program that listens on a port waiting for a small amount of data to tell it what to do. I run 5 instances of that program, one on each port from 5000 to 5004 inclusively.</p> <p>I have a second program written in Python that creates a socket "s", writes the data to port 5000, then closes. It then increments the port number and creates a new socket connected to 5001. It does this until it reaches 5004.</p> <p>The first three socket connections work just fine. The programs on ports 5000 to 5002 receive the data just fine and off they go! However, the fourth socket connection results in a "Connection Refused" error message. Meanwhile, the fourth listening program still reports that it is waiting on port 5003 -- I know that it's listening properly because I am able to connect to it using Telnet.</p> <p>I've tried changing the port numbers, and each time it's the fourth connection that fails.</p> <p>Is there some limit in the system I should check on? I only have one socket open at any time on the sending side, and the fact that I can get 3 of the 5 through eliminates a lot of the basic troubleshooting steps I can think of.</p> <p>Any thoughts? Thanks!</p> <p>--- EDIT ---</p> <p>I'm on CentOS Linux with Python version 2.6. Here's some example code:</p> <pre><code>try: portno = 5000 for index, data in enumerate(data_list): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('myhostname', portno)) s.sendall(data) s.close() portno = portno + 1 except socket.error, (value,message): print 'Error: Send could not be performed.\nPort: ' + str(portno) + '\nMessage: ' + message sys.exit(2) </code></pre>
2
2009-07-17T20:32:47Z
1,147,733
<p>Are you running the 2nd Python program from within Idle? If so - try it outside of Idle and see if the results are any different.</p>
0
2009-07-18T14:53:34Z
[ "python", "sockets", "limit", "max" ]
py2exe: Compiled Python Windows Application won't run because of DLL
1,145,662
<p>I will confess I'm very new to Python and I don't really know what I'm doing yet. Recently I created a very small Windows application using Python 2.6.2 and wxPython 2.8. And it works great; I'm quite pleased with how well it works normally. By normally I mean when I invoke it directly through the Python interpreter, like this:</p> <pre><code>&gt; python myapp.py </code></pre> <p>However, I wanted to go a step further and actually compile this into a standalone executable file. So I followed <a href="http://wiki.wxpython.org/DistributingYourApplication" rel="nofollow">these instructions</a> from the wxPython wiki which utilize py2exe. At first it gave me errors in the command line, saying MSVCR90.dll was missing. Then I copied MSVCR90.dll to my Python\DLLs folder. That looked at first like it fixed it, since it successfully did what it needed to do. It did finish with a quick warning that there were some DLL files the program depends on and I may or may not need to distribute them.</p> <p>So I navigated into the dist folder that py2exe had created and tried running my executable. But trying to open it only popped up an error dialog that said:</p> <pre><code>This application failed to start because MSVCR90.dll was not found. Re-installing the application may fix this problem. </code></pre> <p>So I went ahead and copied MSVCR90.dll again into this dist folder. But that didn't do the trick. Then I copied it into the WINDOWS\system32 directory. That didn't do it either. What do I need to do to get this thing to work?</p>
6
2009-07-17T21:01:13Z
1,145,698
<p>I believe installing <a href="http://www.microsoft.com/downloads/details.aspx?familyid=9B2DA534-3E03-4391-8A4D-074B9F2BC1BF&amp;displaylang=en" rel="nofollow">Microsoft C++ Redistributable Package</a> will install the DLL you need correctly.</p>
2
2009-07-17T21:09:43Z
[ "python", "wxpython", "py2exe" ]
py2exe: Compiled Python Windows Application won't run because of DLL
1,145,662
<p>I will confess I'm very new to Python and I don't really know what I'm doing yet. Recently I created a very small Windows application using Python 2.6.2 and wxPython 2.8. And it works great; I'm quite pleased with how well it works normally. By normally I mean when I invoke it directly through the Python interpreter, like this:</p> <pre><code>&gt; python myapp.py </code></pre> <p>However, I wanted to go a step further and actually compile this into a standalone executable file. So I followed <a href="http://wiki.wxpython.org/DistributingYourApplication" rel="nofollow">these instructions</a> from the wxPython wiki which utilize py2exe. At first it gave me errors in the command line, saying MSVCR90.dll was missing. Then I copied MSVCR90.dll to my Python\DLLs folder. That looked at first like it fixed it, since it successfully did what it needed to do. It did finish with a quick warning that there were some DLL files the program depends on and I may or may not need to distribute them.</p> <p>So I navigated into the dist folder that py2exe had created and tried running my executable. But trying to open it only popped up an error dialog that said:</p> <pre><code>This application failed to start because MSVCR90.dll was not found. Re-installing the application may fix this problem. </code></pre> <p>So I went ahead and copied MSVCR90.dll again into this dist folder. But that didn't do the trick. Then I copied it into the WINDOWS\system32 directory. That didn't do it either. What do I need to do to get this thing to work?</p>
6
2009-07-17T21:01:13Z
1,145,725
<p>You can't just copy msvcr*.dll - they need to be set up using the rules for side-by-side assemblies. You can do this by installing the redistributable package as Sam points out, or you can put them alongside your executables as long as you obey the rules.</p> <p>See the section "Deploying Visual C++ library DLLs as private assemblies" here: <a href="http://msdn.microsoft.com/en-us/library/ms235291%28VS.80%29.aspx" rel="nofollow">How to Deploy using XCopy</a> for details, but basically your application looks like this:</p> <pre><code>c:\My App\MyApp.exe c:\My App\Microsoft.VC90.CRT\Microsoft.VC90.CRT.manifest c:\My App\Microsoft.VC90.CRT\msvcr90.dll </code></pre> <p>One benefit of this is that non-admin users can use your app (I believe you need to be an admin to install the runtime via the redistributable installer). And there's no need for any installer - you can just copy the files onto a PC and it all works.</p>
8
2009-07-17T21:14:48Z
[ "python", "wxpython", "py2exe" ]
Simulating Pointers in Python
1,145,722
<p>I'm trying to cross compile an in house language(ihl) to Python.</p> <p>One of the ihl features is pointers and references that behave like you would expect from C or C++.</p> <p>For instance you can do this:</p> <pre><code>a = [1,2]; // a has an array b = &amp;a; // b points to a *b = 2; // derefernce b to store 2 in a print(a); // outputs 2 print(*b); // outputs 2 </code></pre> <p>Is there a way to duplicate this functionality in Python. </p> <p><strong>I should point out that I think I've confused a few people. I don't want pointers in Python. I just wanted to get a sense from the Python experts out there, what Python I should generate to simulate the case I've shown above</strong></p> <p>My Python isn't the greatest but so far my exploration hasn't yielded anything promising:(</p> <p>I should point out that we are looking to move from our ihl to a more common language so we aren't really tied to Python if someone can suggest another language that may be more suitable.</p>
42
2009-07-17T21:13:59Z
1,145,735
<p>Negative, no pointers. You should not need them with the way the language is designed. However, I heard a nasty rumor that you could use the: <a href="http://starship.python.net/crew/theller/ctypes/" rel="nofollow">ctypes</a> module to use them. I haven't used it, but it smells messy to me.</p>
0
2009-07-17T21:17:29Z
[ "python", "pointers" ]
Simulating Pointers in Python
1,145,722
<p>I'm trying to cross compile an in house language(ihl) to Python.</p> <p>One of the ihl features is pointers and references that behave like you would expect from C or C++.</p> <p>For instance you can do this:</p> <pre><code>a = [1,2]; // a has an array b = &amp;a; // b points to a *b = 2; // derefernce b to store 2 in a print(a); // outputs 2 print(*b); // outputs 2 </code></pre> <p>Is there a way to duplicate this functionality in Python. </p> <p><strong>I should point out that I think I've confused a few people. I don't want pointers in Python. I just wanted to get a sense from the Python experts out there, what Python I should generate to simulate the case I've shown above</strong></p> <p>My Python isn't the greatest but so far my exploration hasn't yielded anything promising:(</p> <p>I should point out that we are looking to move from our ihl to a more common language so we aren't really tied to Python if someone can suggest another language that may be more suitable.</p>
42
2009-07-17T21:13:59Z
1,145,747
<p>You may want to read <a href="http://rg03.wordpress.com/2007/04/21/semantics-of-python-variable-names-from-a-c-perspective/"><em>Semantics of Python variable names from a C++ perspective</em></a>. The bottom line: <strong>All variables are references</strong>.</p> <p>More to the point, don't think in terms of variables, but in terms of objects which can be <em>named</em>.</p>
19
2009-07-17T21:20:22Z
[ "python", "pointers" ]
Simulating Pointers in Python
1,145,722
<p>I'm trying to cross compile an in house language(ihl) to Python.</p> <p>One of the ihl features is pointers and references that behave like you would expect from C or C++.</p> <p>For instance you can do this:</p> <pre><code>a = [1,2]; // a has an array b = &amp;a; // b points to a *b = 2; // derefernce b to store 2 in a print(a); // outputs 2 print(*b); // outputs 2 </code></pre> <p>Is there a way to duplicate this functionality in Python. </p> <p><strong>I should point out that I think I've confused a few people. I don't want pointers in Python. I just wanted to get a sense from the Python experts out there, what Python I should generate to simulate the case I've shown above</strong></p> <p>My Python isn't the greatest but so far my exploration hasn't yielded anything promising:(</p> <p>I should point out that we are looking to move from our ihl to a more common language so we aren't really tied to Python if someone can suggest another language that may be more suitable.</p>
42
2009-07-17T21:13:59Z
1,145,769
<p>Everything in Python is pointers already, but it's called "references" in Python. This is the translation of your code to Python:</p> <pre><code>a = [1,2] // a has an array b = a // b points to a a = 2 // store 2 in a. print(a) // outputs 2 print(b) // outputs [1,2] </code></pre> <p>"Dereferencing" makes no sense, as it's <em>all</em> references. There isn't anything else, so nothing to dereference to.</p>
3
2009-07-17T21:24:41Z
[ "python", "pointers" ]
Simulating Pointers in Python
1,145,722
<p>I'm trying to cross compile an in house language(ihl) to Python.</p> <p>One of the ihl features is pointers and references that behave like you would expect from C or C++.</p> <p>For instance you can do this:</p> <pre><code>a = [1,2]; // a has an array b = &amp;a; // b points to a *b = 2; // derefernce b to store 2 in a print(a); // outputs 2 print(*b); // outputs 2 </code></pre> <p>Is there a way to duplicate this functionality in Python. </p> <p><strong>I should point out that I think I've confused a few people. I don't want pointers in Python. I just wanted to get a sense from the Python experts out there, what Python I should generate to simulate the case I've shown above</strong></p> <p>My Python isn't the greatest but so far my exploration hasn't yielded anything promising:(</p> <p>I should point out that we are looking to move from our ihl to a more common language so we aren't really tied to Python if someone can suggest another language that may be more suitable.</p>
42
2009-07-17T21:13:59Z
1,145,826
<p>As others here have said, all Python variables are essentially pointers.</p> <p>The key to understanding this from a C perspective is to use the unknown by many id() function. It tells you what address the variable points to.</p> <pre><code>&gt;&gt;&gt; a = [1,2] &gt;&gt;&gt; id(a) 28354600 &gt;&gt;&gt; b = a &gt;&gt;&gt; id(a) 28354600 &gt;&gt;&gt; id(b) 28354600 </code></pre>
4
2009-07-17T21:43:05Z
[ "python", "pointers" ]
Simulating Pointers in Python
1,145,722
<p>I'm trying to cross compile an in house language(ihl) to Python.</p> <p>One of the ihl features is pointers and references that behave like you would expect from C or C++.</p> <p>For instance you can do this:</p> <pre><code>a = [1,2]; // a has an array b = &amp;a; // b points to a *b = 2; // derefernce b to store 2 in a print(a); // outputs 2 print(*b); // outputs 2 </code></pre> <p>Is there a way to duplicate this functionality in Python. </p> <p><strong>I should point out that I think I've confused a few people. I don't want pointers in Python. I just wanted to get a sense from the Python experts out there, what Python I should generate to simulate the case I've shown above</strong></p> <p>My Python isn't the greatest but so far my exploration hasn't yielded anything promising:(</p> <p>I should point out that we are looking to move from our ihl to a more common language so we aren't really tied to Python if someone can suggest another language that may be more suitable.</p>
42
2009-07-17T21:13:59Z
1,145,848
<p>This can be done explicitly.</p> <pre><code>class ref: def __init__(self, obj): self.obj = obj def get(self): return self.obj def set(self, obj): self.obj = obj a = ref([1, 2]) b = a print a.get() # =&gt; [1, 2] print b.get() # =&gt; [1, 2] b.set(2) print a.get() # =&gt; 2 print b.get() # =&gt; 2 </code></pre>
66
2009-07-17T21:49:07Z
[ "python", "pointers" ]
Simulating Pointers in Python
1,145,722
<p>I'm trying to cross compile an in house language(ihl) to Python.</p> <p>One of the ihl features is pointers and references that behave like you would expect from C or C++.</p> <p>For instance you can do this:</p> <pre><code>a = [1,2]; // a has an array b = &amp;a; // b points to a *b = 2; // derefernce b to store 2 in a print(a); // outputs 2 print(*b); // outputs 2 </code></pre> <p>Is there a way to duplicate this functionality in Python. </p> <p><strong>I should point out that I think I've confused a few people. I don't want pointers in Python. I just wanted to get a sense from the Python experts out there, what Python I should generate to simulate the case I've shown above</strong></p> <p>My Python isn't the greatest but so far my exploration hasn't yielded anything promising:(</p> <p>I should point out that we are looking to move from our ihl to a more common language so we aren't really tied to Python if someone can suggest another language that may be more suitable.</p>
42
2009-07-17T21:13:59Z
1,145,862
<p>This is goofy, but a thought...</p> <pre><code># Change operations like: b = &amp;a # To: b = "a" # And change operations like: *b = 2 # To: locals()[b] = 2 &gt;&gt;&gt; a = [1,2] &gt;&gt;&gt; b = "a" &gt;&gt;&gt; locals()[b] = 2 &gt;&gt;&gt; print(a) 2 &gt;&gt;&gt; print(locals()[b]) 2 </code></pre> <p>But there would be no pointer arithmetic or such, and no telling what other problems you might run into...</p>
1
2009-07-17T21:53:20Z
[ "python", "pointers" ]
Simulating Pointers in Python
1,145,722
<p>I'm trying to cross compile an in house language(ihl) to Python.</p> <p>One of the ihl features is pointers and references that behave like you would expect from C or C++.</p> <p>For instance you can do this:</p> <pre><code>a = [1,2]; // a has an array b = &amp;a; // b points to a *b = 2; // derefernce b to store 2 in a print(a); // outputs 2 print(*b); // outputs 2 </code></pre> <p>Is there a way to duplicate this functionality in Python. </p> <p><strong>I should point out that I think I've confused a few people. I don't want pointers in Python. I just wanted to get a sense from the Python experts out there, what Python I should generate to simulate the case I've shown above</strong></p> <p>My Python isn't the greatest but so far my exploration hasn't yielded anything promising:(</p> <p>I should point out that we are looking to move from our ihl to a more common language so we aren't really tied to Python if someone can suggest another language that may be more suitable.</p>
42
2009-07-17T21:13:59Z
1,145,884
<p>If you're compiling a C-like language, say:</p> <pre><code>func() { var a = 1; var *b = &amp;a; *b = 2; assert(a == 2); } </code></pre> <p>into Python, then all of the "everything in Python is a reference" stuff is a misnomer.</p> <p>It's true that everything in Python is a reference, but the fact that many core types (ints, strings) are immutable effectively undoes this for many cases. There's no <em>direct</em> way to implement the above in Python.</p> <p>Now, you can do it indirectly: for any immutable type, wrap it in a mutable type. Ephemient's solution works, but I often just do this:</p> <pre><code>a = [1] b = a b[0] = 2 assert a[0] == 2 </code></pre> <p>(I've done this to work around Python's lack of "nonlocal" in 2.x a few times.)</p> <p>This implies a lot more overhead: every immutable type (or every type, if you don't try to distinguish) suddenly creates a list (or another container object), so you're increasing the overhead for variables significantly. Individually, it's not a lot, but it'll add up when applied to a whole codebase.</p> <p>You could reduce this by only wrapping immutable types, but then you'll need to keep track of which variables in the output are wrapped and which aren't, so you can access the value with "a" or "a[0]" appropriately. It'll probably get hairy.</p> <p>As to whether this is a good idea or not--that depends on why you're doing it. If you just want something to run a VM, I'd tend to say no. If you want to be able to call to your existing language from Python, I'd suggest taking your existing VM and creating Python bindings for it, so you can access and call into it from Python.</p>
11
2009-07-17T22:01:56Z
[ "python", "pointers" ]
Simulating Pointers in Python
1,145,722
<p>I'm trying to cross compile an in house language(ihl) to Python.</p> <p>One of the ihl features is pointers and references that behave like you would expect from C or C++.</p> <p>For instance you can do this:</p> <pre><code>a = [1,2]; // a has an array b = &amp;a; // b points to a *b = 2; // derefernce b to store 2 in a print(a); // outputs 2 print(*b); // outputs 2 </code></pre> <p>Is there a way to duplicate this functionality in Python. </p> <p><strong>I should point out that I think I've confused a few people. I don't want pointers in Python. I just wanted to get a sense from the Python experts out there, what Python I should generate to simulate the case I've shown above</strong></p> <p>My Python isn't the greatest but so far my exploration hasn't yielded anything promising:(</p> <p>I should point out that we are looking to move from our ihl to a more common language so we aren't really tied to Python if someone can suggest another language that may be more suitable.</p>
42
2009-07-17T21:13:59Z
14,000,962
<p>Almost exactly like <a href="http://stackoverflow.com/users/20713/ephemient">ephemient</a> <a href="http://stackoverflow.com/a/1145848/1020470">answer</a>, which I voted up, you could use Python's builtin <a href="http://docs.python.org/2/library/functions.html#property" rel="nofollow">property</a> function. It will do something nearly similar to the <code>ref</code> class in ephemient's answer, except now, instead of being forced to use <code>get</code> and <code>set</code> methods to access a <code>ref</code> instance, you just call the attributes of your instance which you've assigned as <em>properties</em> in the class definition. From Python docs (except I changed <strong>C</strong> to <strong>ptr</strong>):</p> <pre><code>class ptr(object): def __init__(self): self._x = None def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, "I'm the 'x' property.") </code></pre> <p>Both methods work like a C pointer, without resorting to <code>global</code>. For example if you have a function that takes a pointer:</p> <pre><code>def do_stuff_with_pointer(pointer, property, value): setattr(pointer, property, value) </code></pre> <p>For example</p> <pre><code>a_ref = ptr() # make pointer a_ref.x = [1, 2] # a_ref pointer has an array [1, 2] b_ref = a_ref # b_ref points to a_ref # pass ``ptr`` instance to function that changes its content do_stuff_with_pointer(b_ref, 'x', 3) print a_ref.x # outputs 3 print b_ref.x # outputs 3 </code></pre> <p>Another, and totally crazy option would be to use Python's <a href="http://docs.python.org/2/library/ctypes.html" rel="nofollow">ctypes</a>. Try this:</p> <pre><code>from ctypes import * a = py_object([1,2]) # a has an array b = a # b points to a b.value = 2 # derefernce b to store 2 in a print a.value # outputs 2 print b.value # outputs 2 </code></pre> <p>or if you want to get really fancy</p> <pre><code>from ctypes import * a = py_object([1,2]) # a has an array b = pointer(a) # b points to a b.contents.value = 2 # derefernce b to store 2 in a print a.value # outputs 2 print b.contents.value # outputs 2 </code></pre> <p>which is more like OP's original request. crazy!</p>
7
2012-12-22T07:32:38Z
[ "python", "pointers" ]
Simulating Pointers in Python
1,145,722
<p>I'm trying to cross compile an in house language(ihl) to Python.</p> <p>One of the ihl features is pointers and references that behave like you would expect from C or C++.</p> <p>For instance you can do this:</p> <pre><code>a = [1,2]; // a has an array b = &amp;a; // b points to a *b = 2; // derefernce b to store 2 in a print(a); // outputs 2 print(*b); // outputs 2 </code></pre> <p>Is there a way to duplicate this functionality in Python. </p> <p><strong>I should point out that I think I've confused a few people. I don't want pointers in Python. I just wanted to get a sense from the Python experts out there, what Python I should generate to simulate the case I've shown above</strong></p> <p>My Python isn't the greatest but so far my exploration hasn't yielded anything promising:(</p> <p>I should point out that we are looking to move from our ihl to a more common language so we aren't really tied to Python if someone can suggest another language that may be more suitable.</p>
42
2009-07-17T21:13:59Z
26,989,738
<pre><code>class Pointer(object): def __init__(self, target=None): self.target = target _noarg = object() def __call__(self, target=_noarg): if target is not self._noarg: self.target = target return self.target </code></pre> <pre><code>a = Pointer([1, 2]) b = a print a() # =&gt; [1, 2] print b() # =&gt; [1, 2] b(2) print a() # =&gt; 2 print b() # =&gt; 2 </code></pre>
0
2014-11-18T08:28:52Z
[ "python", "pointers" ]
Simulating Pointers in Python
1,145,722
<p>I'm trying to cross compile an in house language(ihl) to Python.</p> <p>One of the ihl features is pointers and references that behave like you would expect from C or C++.</p> <p>For instance you can do this:</p> <pre><code>a = [1,2]; // a has an array b = &amp;a; // b points to a *b = 2; // derefernce b to store 2 in a print(a); // outputs 2 print(*b); // outputs 2 </code></pre> <p>Is there a way to duplicate this functionality in Python. </p> <p><strong>I should point out that I think I've confused a few people. I don't want pointers in Python. I just wanted to get a sense from the Python experts out there, what Python I should generate to simulate the case I've shown above</strong></p> <p>My Python isn't the greatest but so far my exploration hasn't yielded anything promising:(</p> <p>I should point out that we are looking to move from our ihl to a more common language so we aren't really tied to Python if someone can suggest another language that may be more suitable.</p>
42
2009-07-17T21:13:59Z
31,242,714
<p>I think that this example is short and clear. </p> <p>Here we have class with implicit list:</p> <pre><code>class A: foo = [] a, b = A(), A() a.foo.append(5) b.foo ans: [5] </code></pre> <p>Looking at this memory profile (using: <code>from memory_profiler import profile</code>), my intuition tells me that this may somehow simulate pointers like in C:</p> <pre><code>Filename: F:/MegaSync/Desktop/python_simulate_pointer_with_class.py Line # Mem usage Increment Line Contents ================================================ 7 31.2 MiB 0.0 MiB @profile 8 def f(): 9 31.2 MiB 0.0 MiB a, b = A(), A() 10 #here memoery increase and is coupled 11 50.3 MiB 19.1 MiB a.foo.append(np.arange(5000000)) 12 73.2 MiB 22.9 MiB b.foo.append(np.arange(6000000)) 13 73.2 MiB 0.0 MiB return a,b [array([ 0, 1, 2, ..., 4999997, 4999998, 4999999]), array([ 0, 1, 2, ..., 5999997, 5999998, 5999999])] [array([ 0, 1, 2, ..., 4999997, 4999998, 4999999]), array([ 0, 1, 2, ..., 5999997, 5999998, 5999999])] Filename: F:/MegaSync/Desktop/python_simulate_pointer_with_class.py Line # Mem usage Increment Line Contents ================================================ 14 73.4 MiB 0.0 MiB @profile 15 def g(): 16 #clearing b.foo list clears a.foo 17 31.5 MiB -42.0 MiB b.foo.clear() 18 31.5 MiB 0.0 MiB return a,b [] [] Filename: F:/MegaSync/Desktop/python_simulate_pointer_with_class.py Line # Mem usage Increment Line Contents ================================================ 19 31.5 MiB 0.0 MiB @profile 20 def h(): 21 #and here mem. coupling is lost ;/ 22 69.6 MiB 38.1 MiB b.foo=np.arange(10000000) 23 #memory inc. when b.foo is replaced 24 107.8 MiB 38.1 MiB a.foo.append(np.arange(10000000)) 25 #so its seams that modyfing items of 26 #existing object of variable a.foo, 27 #changes automaticcly items of b.foo 28 #and vice versa,but changing object 29 #a.foo itself splits with b.foo 30 107.8 MiB 0.0 MiB return b,a [array([ 0, 1, 2, ..., 9999997, 9999998, 9999999])] [ 0 1 2 ..., 9999997 9999998 9999999] </code></pre> <p>And here we have explicit self in class:</p> <pre><code>class A: def __init__(self): self.foo = [] a, b = A(), A() a.foo.append(5) b.foo ans: [] Filename: F:/MegaSync/Desktop/python_simulate_pointer_with_class.py Line # Mem usage Increment Line Contents ================================================ 44 107.8 MiB 0.0 MiB @profile 45 def f(): 46 107.8 MiB 0.0 MiB a, b = B(), B() 47 #here some memory increase 48 #and this mem. is not coupled 49 126.8 MiB 19.1 MiB a.foo.append(np.arange(5000000)) 50 149.7 MiB 22.9 MiB b.foo.append(np.arange(6000000)) 51 149.7 MiB 0.0 MiB return a,b [array([ 0, 1, 2, ..., 5999997, 5999998, 5999999])] [array([ 0, 1, 2, ..., 4999997, 4999998, 4999999])] Filename: F:/MegaSync/Desktop/python_simulate_pointer_with_class.py Line # Mem usage Increment Line Contents ================================================ 52 111.6 MiB 0.0 MiB @profile 53 def g(): 54 #clearing b.foo list 55 #do not clear a.foo 56 92.5 MiB -19.1 MiB b.foo.clear() 57 92.5 MiB 0.0 MiB return a,b [] [array([ 0, 1, 2, ..., 5999997, 5999998, 5999999])] Filename: F:/MegaSync/Desktop/python_simulate_pointer_with_class.py Line # Mem usage Increment Line Contents ================================================ 58 92.5 MiB 0.0 MiB @profile 59 def h(): 60 #and here memory increse again ;/ 61 107.8 MiB 15.3 MiB b.foo=np.arange(10000000) 62 #memory inc. when b.foo is replaced 63 145.9 MiB 38.1 MiB a.foo.append(np.arange(10000000)) 64 145.9 MiB 0.0 MiB return b,a [array([ 0, 1, 2, ..., 9999997, 9999998, 9999999])] [ 0 1 2 ..., 9999997 9999998 9999999] </code></pre> <p>ps: I'm self learning programming (started with Python) so please do not hate me if I'm wrong. Its just mine intuition, that let me think that way, so do not hate me!</p>
0
2015-07-06T09:52:19Z
[ "python", "pointers" ]
MPI signal handling
1,145,741
<p>When using <code>mpirun</code>, is it possible to catch signals (for example, the SIGINT generated by <code>^C</code>) in the code being run?</p> <p>For example, I'm running a parallelized python code. I can <code>except KeyboardInterrupt</code> to catch those errors when running <code>python blah.py</code> by itself, but I can't when doing <code>mpirun -np 1 python blah.py</code>.</p> <p><s>Does anyone have a suggestion? Even finding how to catch signals in a C or C++ compiled program would be a helpful start.</s></p> <p>If I send a signal to the spawned Python processes, they can handle the signals properly; however, signals sent to the parent <code>orterun</code> process (i.e. from exceeding wall time on a cluster, or pressing control-C in a terminal) will kill everything immediately.</p>
3
2009-07-17T21:18:05Z
1,145,984
<p>The <a href="http://docs.python.org/library/signal.html#module-signal" rel="nofollow">signal</a> module supports setting signal handlers using <code>signal.signal</code>:</p> <blockquote> <p>Set the handler for signal signalnum to the function handler. handler can be a callable Python object taking two arguments (see below), or one of the special values signal.SIG_IGN or signal.SIG_DFL. The previous signal handler will be returned ...</p> </blockquote> <pre><code>import signal def ignore(sig, stack): print "I'm ignoring signal %d" % (sig, ) signal.signal(signal.SIGINT, ignore) while True: pass </code></pre> <p>If you send a <code>SIGINT</code> to a Python interpreter running this script (via <code>kill -INT &lt;pid&gt;</code>), it will print a message and simply continue to run.</p>
0
2009-07-17T22:37:22Z
[ "python", "signals", "mpi" ]
MPI signal handling
1,145,741
<p>When using <code>mpirun</code>, is it possible to catch signals (for example, the SIGINT generated by <code>^C</code>) in the code being run?</p> <p>For example, I'm running a parallelized python code. I can <code>except KeyboardInterrupt</code> to catch those errors when running <code>python blah.py</code> by itself, but I can't when doing <code>mpirun -np 1 python blah.py</code>.</p> <p><s>Does anyone have a suggestion? Even finding how to catch signals in a C or C++ compiled program would be a helpful start.</s></p> <p>If I send a signal to the spawned Python processes, they can handle the signals properly; however, signals sent to the parent <code>orterun</code> process (i.e. from exceeding wall time on a cluster, or pressing control-C in a terminal) will kill everything immediately.</p>
3
2009-07-17T21:18:05Z
1,149,142
<p>If you use <code>mpirun --nw</code>, then <code>mpirun</code> itself should terminate as soon as it's started the subprocesses, instead of waiting for their termination; if that's acceptable then I believe your processes would be able to catch their own signals.</p>
0
2009-07-19T03:08:53Z
[ "python", "signals", "mpi" ]
Trying to import a module that imports another module, getting ImportError
1,145,794
<p>In ajax.py, I have this import statement:</p> <pre><code>import components.db_init as db </code></pre> <p>In components/db_init.py, I have this import statement:</p> <pre><code># import locals from ORM (Storm) from storm.locals import * </code></pre> <p>And in components/storm/locals.py, it has this:</p> <pre><code>from storm.properties import Bool, Int, Float, RawStr, Chars, Unicode, Pickle from storm.properties import List, Decimal, DateTime, Date, Time, Enum from storm.properties import TimeDelta from storm.references import Reference, ReferenceSet, Proxy from storm.database import create_database from storm.exceptions import StormError from storm.store import Store, AutoReload from storm.expr import Select, Insert, Update, Delete, Join, SQL from storm.expr import Like, In, Asc, Desc, And, Or, Min, Max, Count, Not from storm.info import ClassAlias from storm.base import Storm </code></pre> <p>So, when I run that import statement in ajax.py, I get this error:</p> <pre><code>&lt;type 'exceptions.ImportError'&gt;: No module named storm.properties </code></pre> <p>I can run components/db_init.py fine without any exceptions... so I have no idea what's up.</p> <p>Can someone shed some light on this problem?</p>
0
2009-07-17T21:33:07Z
1,145,820
<p>I would guess that <code>storm.locals</code>' idea of its package name is different from what you think it is (most likely it thinks it's in <code>components.storm.locals</code>). You can check this by printing <code>__name__</code> at the top of <code>storm.locals</code>, I believe. If you use imports which aren't relative to the current package, the package names have to match.</p> <p>Using a relative import would probably work here. Since <code>locals</code> and <code>properties</code> are in the same package, inside <code>storm.locals</code> you should be able to just do</p> <pre><code>from properties import Bool </code></pre> <p>and so on.</p>
2
2009-07-17T21:41:32Z
[ "python", "import", "packages", "relative-path" ]
Trying to import a module that imports another module, getting ImportError
1,145,794
<p>In ajax.py, I have this import statement:</p> <pre><code>import components.db_init as db </code></pre> <p>In components/db_init.py, I have this import statement:</p> <pre><code># import locals from ORM (Storm) from storm.locals import * </code></pre> <p>And in components/storm/locals.py, it has this:</p> <pre><code>from storm.properties import Bool, Int, Float, RawStr, Chars, Unicode, Pickle from storm.properties import List, Decimal, DateTime, Date, Time, Enum from storm.properties import TimeDelta from storm.references import Reference, ReferenceSet, Proxy from storm.database import create_database from storm.exceptions import StormError from storm.store import Store, AutoReload from storm.expr import Select, Insert, Update, Delete, Join, SQL from storm.expr import Like, In, Asc, Desc, And, Or, Min, Max, Count, Not from storm.info import ClassAlias from storm.base import Storm </code></pre> <p>So, when I run that import statement in ajax.py, I get this error:</p> <pre><code>&lt;type 'exceptions.ImportError'&gt;: No module named storm.properties </code></pre> <p>I can run components/db_init.py fine without any exceptions... so I have no idea what's up.</p> <p>Can someone shed some light on this problem?</p>
0
2009-07-17T21:33:07Z
1,145,834
<p>You either need to </p> <ul> <li>add (...)/components/storm to PYTHONPATH,</li> <li>use relative imports in components/storm/locals.py or </li> <li>import properties instead of storm.properties</li> </ul>
1
2009-07-17T21:44:38Z
[ "python", "import", "packages", "relative-path" ]
SQLAlchemy: Scan huge tables using ORM?
1,145,905
<p>I am currently playing around with SQLAlchemy a bit, which is really quite neat.</p> <p>For testing I created a huge table containing my pictures archive, indexed by SHA1 hashes (to remove duplicates :-)). Which was impressingly fast...</p> <p>For fun I did the equivalent of a <code>select *</code> over the resulting SQLite database:</p> <pre><code>session = Session() for p in session.query(Picture): print(p) </code></pre> <p>I expected to see hashes scrolling by, but instead it just kept scanning the disk. At the same time, memory usage was skyrocketing, reaching 1GB after a few seconds. This seems to come from the identity map feature of SQLAlchemy, which I thought was only keeping weak references.</p> <p>Can somebody explain this to me? I thought that each Picture p would be collected after the hash is written out!?</p>
26
2009-07-17T22:07:02Z
1,145,941
<p>Okay, I just found a way to do this myself. Changing the code to</p> <pre><code>session = Session() for p in session.query(Picture).yield_per(5): print(p) </code></pre> <p>loads only 5 pictures at a time. It seems like the query will load all rows at a time by default. However, I don't yet understand the disclaimer on that method. Quote from <a href="http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.yield_per">SQLAlchemy docs</a></p> <blockquote> <p>WARNING: use this method with caution; if the same instance is present in more than one batch of rows, end-user changes to attributes will be overwritten. In particular, it’s usually impossible to use this setting with eagerly loaded collections (i.e. any lazy=False) since those collections will be cleared for a new load when encountered in a subsequent result batch.</p> </blockquote> <p>So if using <code>yield_per</code> is actually <i>the right way (tm)</i> to scan over copious amounts of SQL data while using the ORM, when is it safe to use it?</p>
36
2009-07-17T22:23:39Z
[ "python", "performance", "orm", "sqlalchemy" ]
SQLAlchemy: Scan huge tables using ORM?
1,145,905
<p>I am currently playing around with SQLAlchemy a bit, which is really quite neat.</p> <p>For testing I created a huge table containing my pictures archive, indexed by SHA1 hashes (to remove duplicates :-)). Which was impressingly fast...</p> <p>For fun I did the equivalent of a <code>select *</code> over the resulting SQLite database:</p> <pre><code>session = Session() for p in session.query(Picture): print(p) </code></pre> <p>I expected to see hashes scrolling by, but instead it just kept scanning the disk. At the same time, memory usage was skyrocketing, reaching 1GB after a few seconds. This seems to come from the identity map feature of SQLAlchemy, which I thought was only keeping weak references.</p> <p>Can somebody explain this to me? I thought that each Picture p would be collected after the hash is written out!?</p>
26
2009-07-17T22:07:02Z
1,146,078
<p>You can defer the picture to only retrieve on access. You can do it on a query by query basis. like</p> <pre><code>session = Session() for p in session.query(Picture).options(sqlalchemy.orm.defer("picture")): print(p) </code></pre> <p>or you can do it in the mapper </p> <pre><code>mapper(Picture, pictures, properties={ 'picture': deferred(pictures.c.picture) }) </code></pre> <p>How you do it is in the documentation <a href="http://www.sqlalchemy.org/docs/05/mappers.html?highlight=defered#deferred-column-loading">here</a></p> <p>Doing it either way will make sure that the picture is only loaded when you access the attribute.</p>
6
2009-07-17T23:06:52Z
[ "python", "performance", "orm", "sqlalchemy" ]
SQLAlchemy: Scan huge tables using ORM?
1,145,905
<p>I am currently playing around with SQLAlchemy a bit, which is really quite neat.</p> <p>For testing I created a huge table containing my pictures archive, indexed by SHA1 hashes (to remove duplicates :-)). Which was impressingly fast...</p> <p>For fun I did the equivalent of a <code>select *</code> over the resulting SQLite database:</p> <pre><code>session = Session() for p in session.query(Picture): print(p) </code></pre> <p>I expected to see hashes scrolling by, but instead it just kept scanning the disk. At the same time, memory usage was skyrocketing, reaching 1GB after a few seconds. This seems to come from the identity map feature of SQLAlchemy, which I thought was only keeping weak references.</p> <p>Can somebody explain this to me? I thought that each Picture p would be collected after the hash is written out!?</p>
26
2009-07-17T22:07:02Z
1,217,947
<p>here's what I usually do for this situation:</p> <pre><code>def page_query(q): offset = 0 while True: r = False for elem in q.limit(1000).offset(offset): r = True yield elem offset += 1000 if not r: break for item in page_query(Session.query(Picture)): print item </code></pre> <p>This avoids the various buffering that DBAPIs do as well (such as psycopg2 and MySQLdb). It still needs to be used appropriately if your query has explicit JOINs, although eagerly loaded collections are guaranteed to load fully since they are applied to a subquery which has the actual LIMIT/OFFSET supplied.</p> <p>I have noticed that Postgresql takes almost as long to return the last 100 rows of a large result set as it does to return the entire result (minus the actual row-fetching overhead) since OFFSET just does a simple scan of the whole thing.</p>
21
2009-08-02T01:28:45Z
[ "python", "performance", "orm", "sqlalchemy" ]
How to override Py_GetPrefix(), Py_GetPath()?
1,145,932
<p>I'm trying to embed the Python interpreter and need to customize the way the Python standard library is loaded. Our library will be loaded from the same directory as the executable, not from prefix/lib/.</p> <p>We have been successful in making this work by manually modifying sys.path after calling Py_Initialize(), however, this generates a warning because Py_Initialize is looking for site.py in ./lib/, and it's not present until after Py_Initialize has been called and we have updated sys.path.</p> <p>The Python c-api docs <em>hint</em> that it's possible to override Py_GetPrefix() and Py_GetPath(), but give no indication of how. Does anyone know how I would go about overriding them?</p>
4
2009-07-17T22:18:26Z
1,146,134
<p>Have you considered using <code>putenv</code> to adjust <code>PYTHONPATH</code> before calling Py_Initialize?</p>
2
2009-07-17T23:30:02Z
[ "c++", "python", "api" ]
How to override Py_GetPrefix(), Py_GetPath()?
1,145,932
<p>I'm trying to embed the Python interpreter and need to customize the way the Python standard library is loaded. Our library will be loaded from the same directory as the executable, not from prefix/lib/.</p> <p>We have been successful in making this work by manually modifying sys.path after calling Py_Initialize(), however, this generates a warning because Py_Initialize is looking for site.py in ./lib/, and it's not present until after Py_Initialize has been called and we have updated sys.path.</p> <p>The Python c-api docs <em>hint</em> that it's possible to override Py_GetPrefix() and Py_GetPath(), but give no indication of how. Does anyone know how I would go about overriding them?</p>
4
2009-07-17T22:18:26Z
1,146,654
<p>You could set <code>Py_NoSiteFlag = 1</code>, call <code>PyInitialize</code> and import site.py yourself as needed.</p>
4
2009-07-18T03:41:44Z
[ "c++", "python", "api" ]
How to override Py_GetPrefix(), Py_GetPath()?
1,145,932
<p>I'm trying to embed the Python interpreter and need to customize the way the Python standard library is loaded. Our library will be loaded from the same directory as the executable, not from prefix/lib/.</p> <p>We have been successful in making this work by manually modifying sys.path after calling Py_Initialize(), however, this generates a warning because Py_Initialize is looking for site.py in ./lib/, and it's not present until after Py_Initialize has been called and we have updated sys.path.</p> <p>The Python c-api docs <em>hint</em> that it's possible to override Py_GetPrefix() and Py_GetPath(), but give no indication of how. Does anyone know how I would go about overriding them?</p>
4
2009-07-17T22:18:26Z
4,229,240
<p>I see it was asked long ago, but I've just hit the same problem. <code>Py_NoSiteFlag</code> will help with the site module, but generally it's better to rewrite <code>Modules/getpath.c</code>; Python docs <a href="http://docs.python.org/c-api/intro.html#embedding-python" rel="nofollow">officially recommend</a> this for “[a]n application that requires total control.” Python does import some modules <strong>during</strong> initialization (the one that hit me was <code>encodings</code>), so, unless you don't want them or have embedded them too, the module search path has to be ready <strong>before</strong> you call <code>Py_Initialize()</code>.</p> <p>From what I understand <code>Py_GetPath</code> merely returns module search path; <code>Py_GetProgramFullPath</code> is self-describing; and <code>Py_GetPrefix</code> and <code>Py_GetExecPrefix</code> are not used by anyone, except some mysterious “<code>ILU</code>”.</p>
3
2010-11-19T20:49:32Z
[ "c++", "python", "api" ]
how would i design a db to contain a set of url regexes (python) that could be matched against an incoming url
1,145,955
<p>Say I have the following set of urls in a db</p> <pre><code>url data ^(.*)google.com/search foobar ^(.*)google.com/alerts barfoo ^(.*)blah.com/foo/(.*) foofoo ... 100's more </code></pre> <p>Given any url in the wild, I would like to check to see if that url belongs to an existing set of urls and get the corresponding data field.</p> <p>My questions are:</p> <ol> <li>How would I design the db to do it</li> <li>django does urlresolution by looping through each regex and checking for a match given that there maybe 1000's of urls is this the best way to approach this?</li> <li>Are there any existing implementations I can look at?</li> </ol>
1
2009-07-17T22:27:49Z
1,146,002
<p>Django has the advantage that its URLs are generally hierarchical. While the entire Django project may well have 100s or more URLs it's probably dealing only with a dozen or less patterns at a time. Do you have any structure in your URLs that you could exploit this way?</p> <p>Other than that, you could try creating some kind of heuristics. E.g. finding the "fixed" parts of your patterns and then eliminating some of them and then (by a simple substring search) and only then switch to regex matching.</p> <p>At the extreme end of the spectrum, you could create a product automaton. That would be super fast but the memory requirements would probably be impractical (and likely to remain so for the next few centuries).</p>
0
2009-07-17T22:40:58Z
[ "python", "regex", "url-routing" ]
how would i design a db to contain a set of url regexes (python) that could be matched against an incoming url
1,145,955
<p>Say I have the following set of urls in a db</p> <pre><code>url data ^(.*)google.com/search foobar ^(.*)google.com/alerts barfoo ^(.*)blah.com/foo/(.*) foofoo ... 100's more </code></pre> <p>Given any url in the wild, I would like to check to see if that url belongs to an existing set of urls and get the corresponding data field.</p> <p>My questions are:</p> <ol> <li>How would I design the db to do it</li> <li>django does urlresolution by looping through each regex and checking for a match given that there maybe 1000's of urls is this the best way to approach this?</li> <li>Are there any existing implementations I can look at?</li> </ol>
1
2009-07-17T22:27:49Z
1,146,061
<p>Before determining that the django approach could not possibly work, try implementing it, and applying a typical workload. For a really thourough approach, you could actually time the cost of each regex and that can guide you in improving the most costly and most frequently used regexes. In particular, you could arrange for the most frequently used, inexpensive regexes to the front of the list. This is probably a better choice than inventing a new technology to fix a problem you don't even know you have yet.</p>
0
2009-07-17T22:59:39Z
[ "python", "regex", "url-routing" ]
how would i design a db to contain a set of url regexes (python) that could be matched against an incoming url
1,145,955
<p>Say I have the following set of urls in a db</p> <pre><code>url data ^(.*)google.com/search foobar ^(.*)google.com/alerts barfoo ^(.*)blah.com/foo/(.*) foofoo ... 100's more </code></pre> <p>Given any url in the wild, I would like to check to see if that url belongs to an existing set of urls and get the corresponding data field.</p> <p>My questions are:</p> <ol> <li>How would I design the db to do it</li> <li>django does urlresolution by looping through each regex and checking for a match given that there maybe 1000's of urls is this the best way to approach this?</li> <li>Are there any existing implementations I can look at?</li> </ol>
1
2009-07-17T22:27:49Z
1,147,370
<p>You'll certainly need more care in your design of regular expressions. For example, the prefix <code>^(.*)</code> will match any input - and while you may need the prefix to capture a group for various reasons, having it there will mean that you can't really eliminate any of the URLs in your database easily. </p> <p>I sort of agree with TokenMacGuy's comment about the intractability of regexes, but the situation may not be completely hopeless depending on the true scale of your problem. For example, for an URL to match, then its first character should match; so for example you could pre-filter your URLs by saying which first character in the input will match that URL. So, you have a secondary table <code>MatchingFirstCharacters</code> which is a lookup between initial characters and URLs which match up to that initial character. (This will only work if you don't have lots of ambiguous prefixes, as I mentioned in the first paragraph of my answer.) Using this approach will mean you don't necessarily have to load all the regexes for full matching - just the ones where at least the first character matches. I suppose the idea could be generalised further, but that's an exercise for the reader ;-)</p>
0
2009-07-18T12:04:34Z
[ "python", "regex", "url-routing" ]
how would i design a db to contain a set of url regexes (python) that could be matched against an incoming url
1,145,955
<p>Say I have the following set of urls in a db</p> <pre><code>url data ^(.*)google.com/search foobar ^(.*)google.com/alerts barfoo ^(.*)blah.com/foo/(.*) foofoo ... 100's more </code></pre> <p>Given any url in the wild, I would like to check to see if that url belongs to an existing set of urls and get the corresponding data field.</p> <p>My questions are:</p> <ol> <li>How would I design the db to do it</li> <li>django does urlresolution by looping through each regex and checking for a match given that there maybe 1000's of urls is this the best way to approach this?</li> <li>Are there any existing implementations I can look at?</li> </ol>
1
2009-07-17T22:27:49Z
1,147,754
<p>The plan I'm leaning towards is one which picks of the domain name + tld from a url, uses that as a key to find out all the regexes and than loops through each of this regex subset to find a match.</p> <p>I use two tables for this</p> <pre><code>class Urlregex(db.Model): """ the data field is structured as a newline separated record list and each record is a space separated list of regex's and dispatch key. Example of one such record domain_tld: google.com data: ^(.*)google.com/search(.*) google-search """ domain_tld = db.StringProperty() data = db.TextProperty() class Urldispatch(db.Model): urlkey = db.StringProperty() data = db.TextProperty() </code></pre> <p>So, for the cost of 2 db reads and looping through a domain specific url subset any incoming url should be able to be matched against a large db of urls.</p>
0
2009-07-18T15:02:42Z
[ "python", "regex", "url-routing" ]
how would i design a db to contain a set of url regexes (python) that could be matched against an incoming url
1,145,955
<p>Say I have the following set of urls in a db</p> <pre><code>url data ^(.*)google.com/search foobar ^(.*)google.com/alerts barfoo ^(.*)blah.com/foo/(.*) foofoo ... 100's more </code></pre> <p>Given any url in the wild, I would like to check to see if that url belongs to an existing set of urls and get the corresponding data field.</p> <p>My questions are:</p> <ol> <li>How would I design the db to do it</li> <li>django does urlresolution by looping through each regex and checking for a match given that there maybe 1000's of urls is this the best way to approach this?</li> <li>Are there any existing implementations I can look at?</li> </ol>
1
2009-07-17T22:27:49Z
1,149,218
<blockquote> <p>"2. django does urlresolution by looping through each regex and checking for a match given that there maybe 1000's of urls is this the best way to approach this?"</p> <p>"3. Are there any existing implementations I can look at?"</p> </blockquote> <p>If running a large number of regular expressions does turn out to be a problem, you should check out <a href="http://code.google.com/p/esmre/" rel="nofollow">esmre</a>, which is a Python extension module for speeding up large collections of regular expressions. It works by extracting the fixed strings of each regular expression and putting them in an <a href="http://en.wikipedia.org/wiki/Aho-Corasick%5Falgorithm" rel="nofollow">Aho-Corasick</a>-inspired pattern matcher to quickly eliminate almost all of the work.</p>
1
2009-07-19T04:01:23Z
[ "python", "regex", "url-routing" ]
Python xml.dom and bad XML
1,147,090
<p>I'm trying to extract some data from various HTML pages using a python program. Unfortunately, some of these pages contain user-entered data which occasionally has "slight" errors - namely tag mismatching.</p> <p>Is there a good way to have python's xml.dom try to correct errors or something of the sort? Alternatively, is there a better way to extract data from HTML pages which may contain errors?</p>
0
2009-07-18T09:24:49Z
1,147,101
<p>You could use <a href="http://utidylib.berlios.de/" rel="nofollow">HTML Tidy</a> to clean up, or <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a> to parse. Could be that you have to save the result to a temp file, but it should work.</p> <p>Cheers,</p>
3
2009-07-18T09:33:48Z
[ "python", "xml", "dom", "expat-parser" ]
Python xml.dom and bad XML
1,147,090
<p>I'm trying to extract some data from various HTML pages using a python program. Unfortunately, some of these pages contain user-entered data which occasionally has "slight" errors - namely tag mismatching.</p> <p>Is there a good way to have python's xml.dom try to correct errors or something of the sort? Alternatively, is there a better way to extract data from HTML pages which may contain errors?</p>
0
2009-07-18T09:24:49Z
1,147,161
<p>I used to use BeautifulSoup for such tasks but now I have shifted to <strong>HTML5lib</strong> (<a href="http://code.google.com/p/html5lib/" rel="nofollow">http://code.google.com/p/html5lib/</a>) which works well in many cases where BeautifulSoup fails</p> <p>other alternative is to use "<strong>Element Soup</strong>" (<a href="http://effbot.org/zone/element-soup.htm" rel="nofollow">http://effbot.org/zone/element-soup.htm</a>) which is a wrapper for Beautiful Soup using ElementTree</p>
0
2009-07-18T10:05:53Z
[ "python", "xml", "dom", "expat-parser" ]
Python xml.dom and bad XML
1,147,090
<p>I'm trying to extract some data from various HTML pages using a python program. Unfortunately, some of these pages contain user-entered data which occasionally has "slight" errors - namely tag mismatching.</p> <p>Is there a good way to have python's xml.dom try to correct errors or something of the sort? Alternatively, is there a better way to extract data from HTML pages which may contain errors?</p>
0
2009-07-18T09:24:49Z
1,147,209
<p><a href="http://codespeak.net/lxml/" rel="nofollow">lxml</a> does a decent job at parsing invalid HTML.</p> <p>According to their documentation <a href="http://codespeak.net/lxml/elementsoup.html" rel="nofollow">Beautiful Soup</a> and <a href="http://codespeak.net/lxml/html5parser.html" rel="nofollow">html5lib</a> sometimes perform better depending on the input. With lxml you can choose which parser to use, and access them via an unified API.</p>
0
2009-07-18T10:31:53Z
[ "python", "xml", "dom", "expat-parser" ]
Python xml.dom and bad XML
1,147,090
<p>I'm trying to extract some data from various HTML pages using a python program. Unfortunately, some of these pages contain user-entered data which occasionally has "slight" errors - namely tag mismatching.</p> <p>Is there a good way to have python's xml.dom try to correct errors or something of the sort? Alternatively, is there a better way to extract data from HTML pages which may contain errors?</p>
0
2009-07-18T09:24:49Z
1,149,208
<p>If jython is acceptable to you, tagsoup is very good at parsing junk - if it is, I found the jdom libraries far easier to use than other xml alternatives.</p> <p>This is a snippet from a demo mockup to do with screen scraping from tfl's journey planner:</p> <pre> private Document getRoutePage(HashMap params) throws Exception { String uri = "http://journeyplanner.tfl.gov.uk/bcl/XSLT_TRIP_REQUEST2"; HttpWrapper hw = new HttpWrapper(); String page = hw.urlEncPost(uri, params); SAXBuilder builder = new SAXBuilder("org.ccil.cowan.tagsoup.Parser"); Reader pageReader = new StringReader(page); return builder.build(pageReader); } </pre>
0
2009-07-19T03:54:23Z
[ "python", "xml", "dom", "expat-parser" ]
IE8 automation and https
1,147,193
<p>I'm trying to use IE8 through COM to access a secured site (namely, SourceForge), in Python. Here is the script:</p> <pre><code>from win32com.client import gencache from win32com.client import Dispatch import pythoncom gencache.EnsureModule('{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}', 0, 1, 1) class SourceForge(object): def __init__(self, baseURL='https://sourceforget.net/', *args, **kwargs): super(SourceForge, self).__init__(*args, **kwargs) self.__browser = Dispatch('InternetExplorer.Application') self.__browser.Visible = True self.__browser.Navigate(baseURL) def run(self): while True: pythoncom.PumpMessages() def main(): sf = SourceForge() sf.run() if __name__ == '__main__': main() </code></pre> <p>If I launch IE by hand, fine. If I launch the script, I get a generic error page "Internet Explorer cannot display this page". If I change baseURL to use http instead of https, the script works. I guess this is some security "feature". I tried adding the site to the list of trusted sites. I tried to enable IE scripting in the options for the Internet zone. Doesn't work. Google was no help.</p> <p>So, does anybody know something about this ? Is there a mysterious option to enable or am I doomed ?</p> <p>I'm on Windows XP SP3 BTW, Python 2.5 and pywin32 build 213.</p>
1
2009-07-18T10:24:07Z
1,147,227
<p>I can't open <strong><a href="https://sourceforget.net/" rel="nofollow">https://sourceforget.net/</a></strong> -- not by hand, not by script.</p> <p>Are you sure this link is right?</p>
2
2009-07-18T10:39:59Z
[ "python", "windows", "winapi" ]
Create instance of a python class , declared in python, with C API
1,147,452
<p>I want to create an instance of a Python class defined in the <code>__main__</code> scope with the C API.</p> <p>For example, the class is called <code>MyClass</code> and is defined as follows:</p> <pre><code>class MyClass: def __init__(self): pass </code></pre> <p>The class type lives under <code>__main__</code> scope.</p> <p>Within the C application, I want to create an instance of this class. This could have been simply possible with <code>PyInstance_New</code> as it takes class name. However this function is not available in Python3. </p> <p>Any help or suggestions for alternatives are appreciated.</p> <p>Thanks, Paul</p>
5
2009-07-18T12:38:40Z
1,147,840
<p>I believe the simplest approach is:</p> <pre><code>/* get sys.modules dict */ PyObject* sys_mod_dict = PyImport_GetModuleDict(); /* get the __main__ module object */ PyObject* main_mod = PyMapping_GetItemString(sys_mod_dict, "__main__"); /* call the class inside the __main__ module */ PyObject* instance = PyObject_CallMethod(main_mod, "MyClass", ""); </code></pre> <p>plus of course error checking. You need only DECREF <code>instance</code> when you're done with it, the other two are borrowed references.</p>
15
2009-07-18T15:41:44Z
[ "python", "c", "python-c-api" ]
Scrolling through a `wx.ScrolledPanel` with the mouse wheel and arrow keys
1,147,581
<p>In my wxPython application I've created a <code>wx.ScrolledPanel</code>, in which there is a big <code>wx.StaticBitmap</code> that needs to be scrolled.</p> <p>The scroll bars do appear and I can scroll with them, but I'd also like to be able to scroll with the mouse wheel and the arrow keys on the keyboard. It would be nice if the "Home", "Page Up", and those other keys would also function as expected.</p> <p>How do I do this?</p> <p><strong>UPDATE:</strong></p> <p>I see the problem. The ScrolledPanel is able to scroll, but only when it is under focus. Problem is, how do I get to be under focus? Even clicking on it doesn't do it. Only if I put a text control inside of it I can focus on it and thus scroll with the wheel. But I don't want to have a text control in it. So how do I make it focus?</p> <p><strong>UPDATE 2:</strong></p> <p>Here is a code sample that shows this phenomena. Uncomment to see how a text control makes the mouse wheel work.</p> <pre><code>import wx, wx.lib.scrolledpanel class MyFrame(wx.Frame): def __init__(self, *args, **kwargs): wx.Frame.__init__(self, *args, **kwargs) scrolled_panel = \ wx.lib.scrolledpanel.ScrolledPanel(parent=self, id=-1) scrolled_panel.SetupScrolling() text = "Ooga booga\n" * 50 static_text=wx.StaticText(scrolled_panel, -1, text) sizer=wx.BoxSizer(wx.VERTICAL) sizer.Add(static_text, wx.EXPAND, 0) # Uncomment the following 2 lines to see how adding # a text control to the scrolled panel makes the # mouse wheel work. # #text_control=wx.TextCtrl(scrolled_panel, -1) #sizer.Add(text_control, wx.EXPAND, 0) scrolled_panel.SetSizer(sizer) self.Show() if __name__=="__main__": app = wx.PySimpleApp() my_frame=MyFrame(None, -1) #import cProfile; cProfile.run("app.MainLoop()") app.MainLoop() </code></pre>
5
2009-07-18T13:51:37Z
1,147,996
<p>Here's an example that should do what you want, I hope. (<strong>Edit</strong>: In retrospect, this doesnt' quite work, for example, when there are two scrolled panels... I'll leave it up here though so peole can downvote it or whatever.) Basically I put everything in a panel inside the frame (generally a good idea), and then set the focus to this main panel. </p> <pre><code>import wx import wx, wx.lib.scrolledpanel class MyFrame(wx.Frame): def __init__(self, *args, **kwargs): wx.Frame.__init__(self, *args, **kwargs) main_panel = wx.Panel(self, -1) main_panel.SetBackgroundColour((150, 100, 100)) self.main_panel = main_panel scrolled_panel = \ wx.lib.scrolledpanel.ScrolledPanel(parent=main_panel, id=-1) scrolled_panel.SetupScrolling() self.scrolled_panel = scrolled_panel cpanel = wx.Panel(main_panel, -1) cpanel.SetBackgroundColour((100, 150, 100)) b = wx.Button(cpanel, -1, size=(40,40)) self.Bind(wx.EVT_BUTTON, self.OnClick, b) self.b = b text = "Ooga booga\n" * 50 static_text=wx.StaticText(scrolled_panel, -1, text) main_sizer=wx.BoxSizer(wx.VERTICAL) main_sizer.Add(scrolled_panel, 1, wx.EXPAND) main_sizer.Add(cpanel, 1, wx.EXPAND) main_panel.SetSizer(main_sizer) text_sizer=wx.BoxSizer(wx.VERTICAL) text_sizer.Add(static_text, 1, wx.EXPAND) scrolled_panel.SetSizer(text_sizer) self.main_panel.SetFocus() self.Show() def OnClick(self, evt): print "click" if __name__=="__main__": class MyApp(wx.App): def OnInit(self): frame = MyFrame(None, -1) frame.Show(True) self.SetTopWindow(frame) return True app = MyApp(0) app.MainLoop() </code></pre> <p>For keyboard control, like setting action from the home key, I think you'll need to bind to those events, and respond appropriately, such as using <code>mypanel.Scroll(0,0)</code> for the <code>home</code> key (and remember to call <code>evt.Skip()</code> for the keyboard events you don't act on). (<strong>Edit:</strong> I don't think there are any default key bindings for scrolling. I'm not sure I'd want any either, for example, what should happen if there's a scrolled panel within a scrolled panel?)</p>
0
2009-07-18T16:49:11Z
[ "python", "user-interface", "wxpython", "scroll" ]
Scrolling through a `wx.ScrolledPanel` with the mouse wheel and arrow keys
1,147,581
<p>In my wxPython application I've created a <code>wx.ScrolledPanel</code>, in which there is a big <code>wx.StaticBitmap</code> that needs to be scrolled.</p> <p>The scroll bars do appear and I can scroll with them, but I'd also like to be able to scroll with the mouse wheel and the arrow keys on the keyboard. It would be nice if the "Home", "Page Up", and those other keys would also function as expected.</p> <p>How do I do this?</p> <p><strong>UPDATE:</strong></p> <p>I see the problem. The ScrolledPanel is able to scroll, but only when it is under focus. Problem is, how do I get to be under focus? Even clicking on it doesn't do it. Only if I put a text control inside of it I can focus on it and thus scroll with the wheel. But I don't want to have a text control in it. So how do I make it focus?</p> <p><strong>UPDATE 2:</strong></p> <p>Here is a code sample that shows this phenomena. Uncomment to see how a text control makes the mouse wheel work.</p> <pre><code>import wx, wx.lib.scrolledpanel class MyFrame(wx.Frame): def __init__(self, *args, **kwargs): wx.Frame.__init__(self, *args, **kwargs) scrolled_panel = \ wx.lib.scrolledpanel.ScrolledPanel(parent=self, id=-1) scrolled_panel.SetupScrolling() text = "Ooga booga\n" * 50 static_text=wx.StaticText(scrolled_panel, -1, text) sizer=wx.BoxSizer(wx.VERTICAL) sizer.Add(static_text, wx.EXPAND, 0) # Uncomment the following 2 lines to see how adding # a text control to the scrolled panel makes the # mouse wheel work. # #text_control=wx.TextCtrl(scrolled_panel, -1) #sizer.Add(text_control, wx.EXPAND, 0) scrolled_panel.SetSizer(sizer) self.Show() if __name__=="__main__": app = wx.PySimpleApp() my_frame=MyFrame(None, -1) #import cProfile; cProfile.run("app.MainLoop()") app.MainLoop() </code></pre>
5
2009-07-18T13:51:37Z
1,157,267
<p>Problem is on window Frame gets the focus and child panel is not getting the Focus (on ubuntu linux it is working fine). Workaround can be as simple as to redirect Frame focus event to set focus to panel e.g.</p> <pre><code>import wx, wx.lib.scrolledpanel class MyFrame(wx.Frame): def __init__(self, *args, **kwargs): wx.Frame.__init__(self, *args, **kwargs) self.panel = scrolled_panel = \ wx.lib.scrolledpanel.ScrolledPanel(parent=self, id=-1) scrolled_panel.SetupScrolling() text = "Ooga booga\n" * 50 static_text=wx.StaticText(scrolled_panel, -1, text) sizer=wx.BoxSizer(wx.VERTICAL) sizer.Add(static_text, wx.EXPAND, 0) scrolled_panel.SetSizer(sizer) self.Show() self.panel.SetFocus() scrolled_panel.Bind(wx.EVT_SET_FOCUS, self.onFocus) def onFocus(self, event): self.panel.SetFocus() if __name__=="__main__": app = wx.PySimpleApp() my_frame=MyFrame(None, -1) app.MainLoop() </code></pre> <p>or onmouse move over panel, set focus to it, and all keys + mousewheeel will start working e.g.</p> <pre><code>import wx, wx.lib.scrolledpanel class MyFrame(wx.Frame): def __init__(self, *args, **kwargs): wx.Frame.__init__(self, *args, **kwargs) self.panel = scrolled_panel = \ wx.lib.scrolledpanel.ScrolledPanel(parent=self, id=-1) scrolled_panel.SetupScrolling() scrolled_panel.Bind(wx.EVT_MOTION, self.onMouseMove) text = "Ooga booga\n" * 50 static_text=wx.StaticText(scrolled_panel, -1, text) sizer=wx.BoxSizer(wx.VERTICAL) sizer.Add(static_text, wx.EXPAND, 0) scrolled_panel.SetSizer(sizer) self.Show() def onMouseMove(self, event): self.panel.SetFocus() if __name__=="__main__": app = wx.PySimpleApp() my_frame=MyFrame(None, -1) app.MainLoop() </code></pre>
3
2009-07-21T04:10:21Z
[ "python", "user-interface", "wxpython", "scroll" ]
Python Xlib catch/send mouseclick
1,147,653
<p>At the moment I'm trying to use Python to detect when the left mouse button is being held and then start to rapidly send this event instead of only once. What I basically want to do is that when the left mouse button is held it clicks and clicks again until you let it go. But I'm a bit puzzled with the whole Xlib, I think it's very confusing actually. Any help on how to do this would be really awesome. That's what I've got so far:</p> <pre><code>#!/usr/bin/env python import Xlib import Xlib.display def main(): display = Xlib.display.Display() root = display.screen().root while True: event = root.display.next_event() print event if __name__ == "__main__": main() </code></pre> <p>But there is unfortunately no output in the console. After a quick search on the internet I found the following:</p> <pre><code>root.change_attributes(event_mask=Xlib.X.KeyPressMask) root.grab_key(keycode, Xlib.X.AnyModifier, 1, Xlib.X.GrabModeAsync, Xlib.X.GrabModeAsync) </code></pre> <p>This is seemingly import to catch a special event with the given keycode. But firstly what keycode does the left-mouse click have, if any at all? And secondly how can I detect when it is being held down and then start sending the mouseclick event rapidly. I would be really grateful for help. (Maybe a way to stop this script with a hotkey would be cool aswell...)</p>
1
2009-07-18T14:19:33Z
1,147,878
<p>Actually you want <code>Xlib.X.ButtonPressMask | Xlib.X.ButtonReleaseMask</code>, to get events for button presses and releases (different from key presses and releases). The events are <code>ButtonPress</code> and <code>ButtonRelease</code>, and the <code>detail</code> instance variable gives you the button number. From when you get the press event, to when you get the release event, you know the button is being held down. Of course you can <em>also</em> receive key events and do something else (e.g. exit your script) when a certain key is pressed.</p> <p><strong>Edit</strong>: this version works fine for me, for example...:</p> <pre><code>import Xlib import Xlib.display def main(): display = Xlib.display.Display(':0') root = display.screen().root root.change_attributes(event_mask= Xlib.X.ButtonPressMask | Xlib.X.ButtonReleaseMask) while True: event = root.display.next_event() print event if __name__ == "__main__": main() </code></pre>
4
2009-07-18T15:57:55Z
[ "python", "events", "mouse", "click", "xlib" ]
How to install Python 3rd party libgmail-0.1.11.tar.tar into Python in Windows XP home?
1,147,713
<p>I do not know Python, I have installed it only and downloaded the libgmail package. So, please give me verbatim steps in installing the libgmail library. My python directory is c:\python26, so please do not skip any steps in the answer.</p> <p>Thanks!</p>
1
2009-07-18T14:45:11Z
1,147,770
<p>The easiest way might be to install <a href="http://pypi.python.org/pypi/setuptools" rel="nofollow">easy_install</a> using the instructions at that page and then typing the following at the command line:</p> <pre><code>easy_install libgmail </code></pre> <p>If it can't be found, then you can point it directly to the file that you downloaded:</p> <pre><code>easy_install c:\biglongpath\libgmail.zip </code></pre>
3
2009-07-18T15:12:52Z
[ "python" ]
How to install Python 3rd party libgmail-0.1.11.tar.tar into Python in Windows XP home?
1,147,713
<p>I do not know Python, I have installed it only and downloaded the libgmail package. So, please give me verbatim steps in installing the libgmail library. My python directory is c:\python26, so please do not skip any steps in the answer.</p> <p>Thanks!</p>
1
2009-07-18T14:45:11Z
1,147,791
<p>All you have to do is extract it, and put it somewhere (I prefer the Libs folder in your Python directory). Then read the readme. It explains that you need to do:</p> <pre><code>python setup.py </code></pre> <p>in your command line. Then you're done.</p>
1
2009-07-18T15:21:55Z
[ "python" ]
How to install Python 3rd party libgmail-0.1.11.tar.tar into Python in Windows XP home?
1,147,713
<p>I do not know Python, I have installed it only and downloaded the libgmail package. So, please give me verbatim steps in installing the libgmail library. My python directory is c:\python26, so please do not skip any steps in the answer.</p> <p>Thanks!</p>
1
2009-07-18T14:45:11Z
1,147,801
<p>Let's say you downloaded and unzipped it to <code>C:/libgmail-0.1.11</code>. Open a command prompt and:</p> <pre><code>cd C:/libgmail-0.1.11 </code></pre> <p>Then build an Windows installer:</p> <pre><code>python setup.py bdist --format=wininst </code></pre> <p>Then go to <code>C:/libgmail-0.1.11/dist</code> and you'll find an installer. Double click it, follow the "next" procedure and you're done.</p> <p>What's nice about this method is that you can easily uninstall the library from Control Panel/Add or Remove Programs.</p>
1
2009-07-18T15:25:27Z
[ "python" ]
How to install Python 3rd party libgmail-0.1.11.tar.tar into Python in Windows XP home?
1,147,713
<p>I do not know Python, I have installed it only and downloaded the libgmail package. So, please give me verbatim steps in installing the libgmail library. My python directory is c:\python26, so please do not skip any steps in the answer.</p> <p>Thanks!</p>
1
2009-07-18T14:45:11Z
1,148,018
<p>Extract the archive to a temporary directory, and type "python setup.py <strong>install</strong>".</p>
2
2009-07-18T17:01:40Z
[ "python" ]
How to install Python 3rd party libgmail-0.1.11.tar.tar into Python in Windows XP home?
1,147,713
<p>I do not know Python, I have installed it only and downloaded the libgmail package. So, please give me verbatim steps in installing the libgmail library. My python directory is c:\python26, so please do not skip any steps in the answer.</p> <p>Thanks!</p>
1
2009-07-18T14:45:11Z
1,148,313
<p>Here's how I did it:</p> <ol> <li>Make sure C:\Python26 and C:\Python26\scripts are both on your system path.</li> <li>Install <a href="http://pypi.python.org/pypi/setuptools" rel="nofollow">setuptools</a>. You'll have to download the source distribution, and extract it. You will likely need something like <a href="http://www.7-zip.org/" rel="nofollow">7zip</a> for this. If you use 7zip note that you will need to extract it twice. Once to get a .tar file, and again to get a directory out of that tar file.</li> <li>Open a command prompt and cd to the directory you created. Run the command <code>python setup.py install</code>.</li> <li>Run the command <code>easy_install mechanize</code>.</li> <li>Install libgmail just like you did setuptools.</li> </ol> <p>This was a lot of work, but you now have the <code>easy_install</code> tool available to simplify installing these kinds of things in the future. If you're doing anything serious, you may also want to consider setting up a <a href="http://pypi.python.org/pypi/virtualenv/1.3.3" rel="nofollow">virtualenv</a> and using <a href="http://pypi.python.org/pypi/pip/0.4" rel="nofollow">pip</a> instead of <code>easy_install</code>.</p>
1
2009-07-18T19:06:04Z
[ "python" ]
What is the DRY way to configure different log file locations for different settings?
1,147,812
<p>I am using python's <code>logging</code> module in a django project. I am performing the basic logging configuration in my <code>settings.py</code> file. Something like this:</p> <pre><code>import logging import logging.handlers logger = logging.getLogger('project_logger') logger.setLevel(logging.INFO) LOG_FILENAME = '/path/to/log/file/in/development/environment' handler = logging.handlers.TimedRotatingFileHandler(LOG_FILENAME, when = 'midnight') formatter = logging.Formatter(LOG_MSG_FORMAT) handler.setFormatter(formatter) logger.addHandler(handler) </code></pre> <p>I have a separate settings file for production. This file (<code>production.py</code>) imports everything from <code>settings</code> and overrides some of the options (set <code>DEBUG</code> to <code>False</code>, for instance). I wish to use a different <code>LOG_FILENAME</code> for production. How should I go about it? I can repeat the entire configuration section in <code>production.py</code> but that creates problems if <code>/path/to/log/file/in/development/environment</code> is not present in the production machine. Besides it doesn't look too "DRY". </p> <p>Can anyone suggest a better way to go about this?</p>
4
2009-07-18T15:28:15Z
1,147,831
<p>Why don't you put this statements at the end of settings.py and use the DEBUG flal es indicator for developement?</p> <p>Something like this:</p> <pre><code>import logging import logging.handlers logger = logging.getLogger('project_logger') logger.setLevel(logging.INFO) [snip] if DEBUG: LOG_FILENAME = '/path/to/log/file/in/development/environment' else: LOG_FILENAME = '/path/to/log/file/in/production/environment' handler = logging.handlers.TimedRotatingFileHandler(LOG_FILENAME, when = 'midnight') formatter = logging.Formatter(LOG_MSG_FORMAT) handler.setFormatter(formatter) logger.addHandler(handler) </code></pre>
1
2009-07-18T15:36:45Z
[ "python", "django", "logging" ]
What is the DRY way to configure different log file locations for different settings?
1,147,812
<p>I am using python's <code>logging</code> module in a django project. I am performing the basic logging configuration in my <code>settings.py</code> file. Something like this:</p> <pre><code>import logging import logging.handlers logger = logging.getLogger('project_logger') logger.setLevel(logging.INFO) LOG_FILENAME = '/path/to/log/file/in/development/environment' handler = logging.handlers.TimedRotatingFileHandler(LOG_FILENAME, when = 'midnight') formatter = logging.Formatter(LOG_MSG_FORMAT) handler.setFormatter(formatter) logger.addHandler(handler) </code></pre> <p>I have a separate settings file for production. This file (<code>production.py</code>) imports everything from <code>settings</code> and overrides some of the options (set <code>DEBUG</code> to <code>False</code>, for instance). I wish to use a different <code>LOG_FILENAME</code> for production. How should I go about it? I can repeat the entire configuration section in <code>production.py</code> but that creates problems if <code>/path/to/log/file/in/development/environment</code> is not present in the production machine. Besides it doesn't look too "DRY". </p> <p>Can anyone suggest a better way to go about this?</p>
4
2009-07-18T15:28:15Z
1,148,039
<p>Found a reasonably "DRY" solution that worked. Thanks to <a href="http://stackoverflow.com/questions/342434/python-logging-in-django/343575#343575">http://stackoverflow.com/questions/342434/python-logging-in-django/343575#343575</a></p> <p>I now have a log.py which looks something like this:</p> <pre><code>import logging, logging.handlers from django.conf import settings LOGGING_INITIATED = False LOGGER_NAME = 'project_logger' def init_logging(): logger = logging.getLogger(LOGGER_NAME) logger.setLevel(logging.INFO) handler = logging.handlers.TimedRotatingFileHandler(settings.LOG_FILENAME, when = 'midnight') formatter = logging.Formatter(LOG_MSG_FORMAT) handler.setFormatter(formatter) logger.addHandler(handler) if not LOGGING_INITIATED: LOGGING_INITIATED = True init_logging() </code></pre> <p>My <code>settings.py</code> now contains </p> <pre><code>LOG_FILENAME = '/path/to/log/file/in/development/environment </code></pre> <p>and <code>production.py</code> contains:</p> <pre><code>from settings import * LOG_FILENAME = '/path/to/log/file/in/production/environment' </code></pre>
1
2009-07-18T17:12:14Z
[ "python", "django", "logging" ]
Difference in SHA512 between python hashlib and sha512sum tool
1,147,875
<p>I am getting different message digests from the linux 'sha512sum' tool and the python hashlib library.</p> <p>Here is what I get on my Ubuntu 8.10:</p> <pre><code>$ echo test | sha512sum 0e3e75234abc68f4378a86b3f4b32a198ba301845b0cd6e50106e874345700cc6663a86c1ea125dc5e92be17c98f9a0f85ca9d5f595db2012f7cc3571945c123 - $ python Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import hashlib &gt;&gt;&gt; hashlib.sha512("test").hexdigest() 'ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff' </code></pre> <p>Both should calculate the message digest of the string "test", why do you think I am getting different results? </p>
4
2009-07-18T15:56:13Z
1,147,880
<p>I think the difference is that echo adds a newline character to its output. Try echo -n test | sha512sum</p>
14
2009-07-18T15:59:05Z
[ "python", "digest", "sha512", "hashlib" ]
Difference in SHA512 between python hashlib and sha512sum tool
1,147,875
<p>I am getting different message digests from the linux 'sha512sum' tool and the python hashlib library.</p> <p>Here is what I get on my Ubuntu 8.10:</p> <pre><code>$ echo test | sha512sum 0e3e75234abc68f4378a86b3f4b32a198ba301845b0cd6e50106e874345700cc6663a86c1ea125dc5e92be17c98f9a0f85ca9d5f595db2012f7cc3571945c123 - $ python Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import hashlib &gt;&gt;&gt; hashlib.sha512("test").hexdigest() 'ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff' </code></pre> <p>Both should calculate the message digest of the string "test", why do you think I am getting different results? </p>
4
2009-07-18T15:56:13Z
1,147,883
<p><code>echo</code> is adding a newline:</p> <pre><code>$ python -c 'import hashlib; print hashlib.sha512("test\n").hexdigest()' 0e3e75234abc68f4378a86b3f4b32a198ba301845b0cd6e50106e874345700cc6663a86c1ea125dc5e92be17c98f9a0f85ca9d5f595db2012f7cc3571945c123 </code></pre> <p>To avoid that, use <code>echo -n</code>.</p>
10
2009-07-18T16:00:09Z
[ "python", "digest", "sha512", "hashlib" ]
Difference in SHA512 between python hashlib and sha512sum tool
1,147,875
<p>I am getting different message digests from the linux 'sha512sum' tool and the python hashlib library.</p> <p>Here is what I get on my Ubuntu 8.10:</p> <pre><code>$ echo test | sha512sum 0e3e75234abc68f4378a86b3f4b32a198ba301845b0cd6e50106e874345700cc6663a86c1ea125dc5e92be17c98f9a0f85ca9d5f595db2012f7cc3571945c123 - $ python Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import hashlib &gt;&gt;&gt; hashlib.sha512("test").hexdigest() 'ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff' </code></pre> <p>Both should calculate the message digest of the string "test", why do you think I am getting different results? </p>
4
2009-07-18T15:56:13Z
1,148,988
<p>Different input, different output. Try comparing like with like:</p> <pre><code>C:\junk&gt;echo test| python -c "import sys, hashlib; x = sys.stdin.read(); print len(x), repr(x); print hashlib.sha512(x).hexdigest()" 5 'test\n' 0e3e75234abc68f4378a86b3f4b32a198ba301845b0cd6e50106e874345700cc6663a86c1ea125dc5e92be17c98f9a0f85ca9d5f595db2012f7cc3571945c123 </code></pre>
2
2009-07-19T00:47:46Z
[ "python", "digest", "sha512", "hashlib" ]
Python socket accept blocks - prevents app from quitting
1,148,062
<p>I've written a very simple python class which waits for connections on a socket. The intention is to stick this class into an existing app and asyncronously send data to connecting clients. </p> <p>The problem is that when waiting on an socket.accept(), I cannot end my application by pressing ctrl-c. Neither can I detect when my class goes out of scope and notify it to end. </p> <p>Ideally the application below should quit after the time.sleep(4) expires. As you can see below, I tried using select, but this also prevents the app from responding to ctrl-c. If I could detect that the variable 'a' has gone out of scope in the main method, I could set the quitting flag (and reduce the timeout on select to make it responsive). </p> <p>Any ideas? </p> <p>thanks</p> <p><hr /></p> <pre><code>import sys import socket import threading import time import select class Server( threading.Thread ): def __init__( self, i_port ): threading.Thread.__init__( self ) self.quitting = False self.serversocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) self.serversocket.bind( (socket.gethostname(), i_port ) ) self.serversocket.listen(5) self.start() def run( self ): # Wait for connection while not self.quitting: rr,rw,err = select.select( [self.serversocket],[],[], 20 ) if rr: (clientsocket, address) = self.serversocket.accept() clientsocket.close() def main(): a = Server( 6543 ) time.sleep(4) if __name__=='__main__': main() </code></pre> <p><hr /></p>
8
2009-07-18T17:23:39Z
1,148,126
<p>Add <code>self.setDaemon(True)</code> to the <code>__init__</code> before <code>self.start()</code>.</p> <p>(In Python 2.6 and later, <code>self.daemon = True</code> is preferred).</p> <p>The key idea is explained <a href="http://docs.python.org/library/threading.html#threading.Thread.daemon">here</a>:</p> <blockquote> <p>The entire Python program exits when no alive non-daemon threads are left.</p> </blockquote> <p>So, you need to make "daemons" of those threads who should not keep the whole process alive just by being alive themselves. The main thread is always non-daemon, by the way.</p>
9
2009-07-18T17:49:38Z
[ "python", "sockets" ]
Python socket accept blocks - prevents app from quitting
1,148,062
<p>I've written a very simple python class which waits for connections on a socket. The intention is to stick this class into an existing app and asyncronously send data to connecting clients. </p> <p>The problem is that when waiting on an socket.accept(), I cannot end my application by pressing ctrl-c. Neither can I detect when my class goes out of scope and notify it to end. </p> <p>Ideally the application below should quit after the time.sleep(4) expires. As you can see below, I tried using select, but this also prevents the app from responding to ctrl-c. If I could detect that the variable 'a' has gone out of scope in the main method, I could set the quitting flag (and reduce the timeout on select to make it responsive). </p> <p>Any ideas? </p> <p>thanks</p> <p><hr /></p> <pre><code>import sys import socket import threading import time import select class Server( threading.Thread ): def __init__( self, i_port ): threading.Thread.__init__( self ) self.quitting = False self.serversocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) self.serversocket.bind( (socket.gethostname(), i_port ) ) self.serversocket.listen(5) self.start() def run( self ): # Wait for connection while not self.quitting: rr,rw,err = select.select( [self.serversocket],[],[], 20 ) if rr: (clientsocket, address) = self.serversocket.accept() clientsocket.close() def main(): a = Server( 6543 ) time.sleep(4) if __name__=='__main__': main() </code></pre> <p><hr /></p>
8
2009-07-18T17:23:39Z
1,148,237
<p>I don't recommend the setDaemon feature for normal shutdown. It's sloppy; instead of having a clean shutdown path for threads, it simply kills the thread with no chance for cleanup. It's good to set it, so your program doesn't get stuck if the main thread exits unexpectedly, but it's not a good normal shutdown path except for quick hacks.</p> <pre><code>import sys, os, socket, threading, time, select class Server(threading.Thread): def __init__(self, i_port): threading.Thread.__init__(self) self.setDaemon(True) self.quitting = False self.serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.serversocket.bind((socket.gethostname(), i_port)) self.serversocket.listen(5) self.start() def shutdown(self): if self.quitting: return self.quitting = True self.join() def run(self): # Wait for connection while not self.quitting: rr,rw,err = select.select([self.serversocket],[],[], 1) print rr if rr: (clientsocket, address) = self.serversocket.accept() clientsocket.close() print "shutting down" self.serversocket.close() def main(): a = Server(6543) try: time.sleep(4) finally: a.shutdown() if __name__=='__main__': main() </code></pre> <p>Note that this will delay for up to a second after calling shutdown(), which is poor behavior. This is normally easy to fix: create a wakeup pipe() that you can write to, and include it in the select; but although this is very basic, I couldn't find any way to do this in Python. (os.pipe() returns file descriptors, not file objects that we can write to.) I havn't dig deeper, since it's tangental to the question.</p>
3
2009-07-18T18:34:46Z
[ "python", "sockets" ]
Possible to access gdata api when using Java App Engine?
1,148,165
<p>I have a dilemma where I want to create an application that manipulates google contacts information. The problem comes down to the fact that Python only supports version 1.0 of the api whilst Java supports 3.0.</p> <p>I also want it to be web-based so I'm having a look at google app engine, but it seems that only the python version of app engine supports the import of gdata apis whilst java does not.</p> <p>So its either web based and version 1.0 of the api or non-web based and version 3.0 of the api.</p> <p>I actually need version 3.0 to get access to the extra fields provided by google contacts.</p> <p>So my question is, is there a way to get access to the gdata api under Google App Engine using Java?</p> <p>If not is there an ETA on when version 3.0 of the gdata api will be released for python?</p> <p>Cheers.</p>
0
2009-07-18T18:08:04Z
1,149,886
<p>I'm having a look into the google data api protocol which seems to solve the problem.</p>
0
2009-07-19T13:19:25Z
[ "java", "python", "google-app-engine", "gdata-api" ]
Possible to access gdata api when using Java App Engine?
1,148,165
<p>I have a dilemma where I want to create an application that manipulates google contacts information. The problem comes down to the fact that Python only supports version 1.0 of the api whilst Java supports 3.0.</p> <p>I also want it to be web-based so I'm having a look at google app engine, but it seems that only the python version of app engine supports the import of gdata apis whilst java does not.</p> <p>So its either web based and version 1.0 of the api or non-web based and version 3.0 of the api.</p> <p>I actually need version 3.0 to get access to the extra fields provided by google contacts.</p> <p>So my question is, is there a way to get access to the gdata api under Google App Engine using Java?</p> <p>If not is there an ETA on when version 3.0 of the gdata api will be released for python?</p> <p>Cheers.</p>
0
2009-07-18T18:08:04Z
1,401,123
<p>Google Data API Java Client : <a href="http://code.google.com/p/gdata-java-client/" rel="nofollow">link1</a></p> <p>Getting Started with the Google Data Java Client Library <a href="http://code.google.com/apis/gdata/articles/java%5Fclient%5Flib.html" rel="nofollow">link2</a> </p> <p>I guess this is what you were looking for.</p>
0
2009-09-09T18:01:14Z
[ "java", "python", "google-app-engine", "gdata-api" ]
Possible to access gdata api when using Java App Engine?
1,148,165
<p>I have a dilemma where I want to create an application that manipulates google contacts information. The problem comes down to the fact that Python only supports version 1.0 of the api whilst Java supports 3.0.</p> <p>I also want it to be web-based so I'm having a look at google app engine, but it seems that only the python version of app engine supports the import of gdata apis whilst java does not.</p> <p>So its either web based and version 1.0 of the api or non-web based and version 3.0 of the api.</p> <p>I actually need version 3.0 to get access to the extra fields provided by google contacts.</p> <p>So my question is, is there a way to get access to the gdata api under Google App Engine using Java?</p> <p>If not is there an ETA on when version 3.0 of the gdata api will be released for python?</p> <p>Cheers.</p>
0
2009-07-18T18:08:04Z
2,832,965
<p>I use GDATA apis for my JAVA appengine webapp. So GDATA can be used with JAVA runtime.</p> <p>From <a href="http://code.google.com/appengine/kb/java.html" rel="nofollow">http://code.google.com/appengine/kb/java.html</a></p> <blockquote> <p>Yes, the Google Data Java client library can be used in App Engine, but you need to set a configuration option to avoid a runtime permissions error.<br/><br/> Add the following to your <strong>appengine-web.xml</strong> file:</p> </blockquote> <pre><code>&lt;system-properties&gt; &lt;property name="com.google.gdata.DisableCookieHandler" value="true"/&gt; &lt;/system-properties&gt; </code></pre> <blockquote> <p>If the following is not included, you may see the following exception: java.security.AccessControlException: access denied (java.net.NetPermission getCookieHandler)</p> </blockquote>
0
2010-05-14T09:11:20Z
[ "java", "python", "google-app-engine", "gdata-api" ]
cx_Oracle and the data source paradigm
1,148,472
<p>There is a Java paradigm for database access implemented in the Java <code>DataSource</code>. This object create a useful abstraction around the creation of database connections. The <code>DataSource</code> object keeps database configuration, but will only create database connections on request. This is allows you to keep all database configuration and initialization code in one place, and makes it easy to change database implementation, or use a mock database for testing.</p> <p>I currently working on a Python project which uses cx_Oracle. In cx_Oracle, one gets a connection directly from the module:</p> <pre><code>import cx_Oracle as dbapi connection = dbapi.connect(connection_string) # At this point I am assuming that a real connection has been made to the database. # Is this true? </code></pre> <p>I am trying to find a parallel to the <code>DataSource</code> in cx_Oracle. I can easily create this by creating a new class and wrapping cx_Oracle, but I was wondering if this is the right way to do it in Python.</p>
3
2009-07-18T20:19:18Z
1,148,530
<p>I don't think there is a "right" way to do this in Python, except maybe to go one step further and use another layer between yourself and the database.</p> <p>Depending on the reason for wanting to use the DataSource concept (which I've only ever come across in Java), SQLAlchemy (or something similar) might solve the problems for you, without you having to write something from scratch.</p> <p>If that doesn't fit the bill, writing your own wrapper sounds like a reasonable solution.</p>
1
2009-07-18T20:50:45Z
[ "python", "database", "oracle", "cx-oracle" ]
cx_Oracle and the data source paradigm
1,148,472
<p>There is a Java paradigm for database access implemented in the Java <code>DataSource</code>. This object create a useful abstraction around the creation of database connections. The <code>DataSource</code> object keeps database configuration, but will only create database connections on request. This is allows you to keep all database configuration and initialization code in one place, and makes it easy to change database implementation, or use a mock database for testing.</p> <p>I currently working on a Python project which uses cx_Oracle. In cx_Oracle, one gets a connection directly from the module:</p> <pre><code>import cx_Oracle as dbapi connection = dbapi.connect(connection_string) # At this point I am assuming that a real connection has been made to the database. # Is this true? </code></pre> <p>I am trying to find a parallel to the <code>DataSource</code> in cx_Oracle. I can easily create this by creating a new class and wrapping cx_Oracle, but I was wondering if this is the right way to do it in Python.</p>
3
2009-07-18T20:19:18Z
1,148,609
<p>You'll find relevant information of how to access databases in Python by looking at <a href="http://www.python.org/dev/peps/pep-0249/" rel="nofollow">PEP-249: Python Database API Specification v2.0</a>. <code>cx_Oracle</code> conforms to this specification, as do many database drivers for Python.</p> <p>In this specification a <code>Connection</code> object represents a database connection, but there is no built-in pooling. Tools such as <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a> do provide pooling facilities, and although SQLAlchemy is often billed as an ORM, it does not have to be used as such and offers nice abstractions for use on top of SQL engines.</p> <p>If you do want to do object-relational-mapping, then SQLAlchemy does the business, and you can consider either its own declarative syntax or another layer such as <a href="http://elixir.ematia.de/" rel="nofollow">Elixir</a> which sits on top of SQLAlchemy and provides increased ease of use for more common use cases.</p>
3
2009-07-18T21:30:47Z
[ "python", "database", "oracle", "cx-oracle" ]
cx_Oracle and the data source paradigm
1,148,472
<p>There is a Java paradigm for database access implemented in the Java <code>DataSource</code>. This object create a useful abstraction around the creation of database connections. The <code>DataSource</code> object keeps database configuration, but will only create database connections on request. This is allows you to keep all database configuration and initialization code in one place, and makes it easy to change database implementation, or use a mock database for testing.</p> <p>I currently working on a Python project which uses cx_Oracle. In cx_Oracle, one gets a connection directly from the module:</p> <pre><code>import cx_Oracle as dbapi connection = dbapi.connect(connection_string) # At this point I am assuming that a real connection has been made to the database. # Is this true? </code></pre> <p>I am trying to find a parallel to the <code>DataSource</code> in cx_Oracle. I can easily create this by creating a new class and wrapping cx_Oracle, but I was wondering if this is the right way to do it in Python.</p>
3
2009-07-18T20:19:18Z
1,148,995
<p>Yes, Python has a similar abstraction.</p> <p>This is from our local build regression test, where we assure that we can talk to all of our databases whenever we build a new python.</p> <pre><code>if database == SYBASE: import Sybase conn = Sybase.connect('sybasetestdb','mh','secret') elif database == POSTRESQL: import pgdb conn = pgdb.connect('pgtestdb:mh:secret') elif database == ORACLE: import cx_Oracle conn = cx_Oracle.connect("mh/secret@oracletestdb") curs=conn.cursor() curs.execute('select a,b from testtable') for row in curs.fetchall(): print row </code></pre> <p>(note, this is the simple version, in our multidb-aware code we have a dbconnection class that has this logic inside.)</p>
0
2009-07-19T00:50:08Z
[ "python", "database", "oracle", "cx-oracle" ]
cx_Oracle and the data source paradigm
1,148,472
<p>There is a Java paradigm for database access implemented in the Java <code>DataSource</code>. This object create a useful abstraction around the creation of database connections. The <code>DataSource</code> object keeps database configuration, but will only create database connections on request. This is allows you to keep all database configuration and initialization code in one place, and makes it easy to change database implementation, or use a mock database for testing.</p> <p>I currently working on a Python project which uses cx_Oracle. In cx_Oracle, one gets a connection directly from the module:</p> <pre><code>import cx_Oracle as dbapi connection = dbapi.connect(connection_string) # At this point I am assuming that a real connection has been made to the database. # Is this true? </code></pre> <p>I am trying to find a parallel to the <code>DataSource</code> in cx_Oracle. I can easily create this by creating a new class and wrapping cx_Oracle, but I was wondering if this is the right way to do it in Python.</p>
3
2009-07-18T20:19:18Z
1,157,015
<p>I just sucked it up and wrote my own. It allowed me to add things like abstracting the database (Oracle/MySQL/Access/etc), adding logging, error handling with transaction rollbacks, etc.</p>
0
2009-07-21T02:28:17Z
[ "python", "database", "oracle", "cx-oracle" ]
Python threads - crashing when they access postgreSQL
1,148,671
<p>here is a simple threading program which works fine: </p> <pre><code>import psycopg2 import threading import time class testit(threading.Thread): def __init__(self, currency): threading.Thread.__init__(self) self.currency = currency def run(self): global SQLConnection global cursor SQLString = "Select dval from ddata where dname ='%s' and ddate = '2009-07-17'" \ %self.currency z = time.time() while (time.time() - z) &lt; 2: print SQLString SQLConnection = psycopg2.connect(database = "db", user = "xxxx", password = "xxxx") cursor = SQLConnection.cursor() a = testit('EURCZK') b = testit('EURPLN') a.start() b.start() </code></pre> <p>However as soon as I try to start accessing the postgresql database in the thread with the following code, I always get a stop-sign crash: </p> <pre><code>import psycopg2 import threading import time class testit(threading.Thread): def __init__(self, currency): threading.Thread.__init__(self) self.currency = currency def run(self): global SQLConnection global cursor SQLString = "Select dval from ddata where dname ='%s'and ddate = '2009-07-17'" %self.currency z = time.time() while (time.time() - z) &lt; 2: cursor.execute(SQLString) print cursor.fetchall() SQLConnection = psycopg2.connect(database = "db", user = "xxxx", password = "xxxx") cursor = SQLConnection.cursor() a = testit('EURCZK') b = testit('EURPLN') a.start() b.start() </code></pre> <p>The only difference between the two is in the while loop. I am fairly new to thread programming. Is the postgres library (psycopg2) not "thread safe"? All this is running on Windows XP. Anything I can do?</p> <p>Thanks. </p>
1
2009-07-18T21:50:50Z
1,148,710
<pre><code>global SQLConnection global cursor </code></pre> <p>Seems you're accessing globals from multiple threads ? You should <strong>never</strong> do that unless those globals are thread safe, or you provide the proper locking yourself.</p> <p>You now have 2 threads accessing the same connection and the same cursor. They'll step on eachothers toes. psycopg2 connection might be thread safe but cursors are not.</p> <p>Use one cursor(probably one connection as well) per thread.</p>
1
2009-07-18T22:04:19Z
[ "python", "postgresql" ]
Python threads - crashing when they access postgreSQL
1,148,671
<p>here is a simple threading program which works fine: </p> <pre><code>import psycopg2 import threading import time class testit(threading.Thread): def __init__(self, currency): threading.Thread.__init__(self) self.currency = currency def run(self): global SQLConnection global cursor SQLString = "Select dval from ddata where dname ='%s' and ddate = '2009-07-17'" \ %self.currency z = time.time() while (time.time() - z) &lt; 2: print SQLString SQLConnection = psycopg2.connect(database = "db", user = "xxxx", password = "xxxx") cursor = SQLConnection.cursor() a = testit('EURCZK') b = testit('EURPLN') a.start() b.start() </code></pre> <p>However as soon as I try to start accessing the postgresql database in the thread with the following code, I always get a stop-sign crash: </p> <pre><code>import psycopg2 import threading import time class testit(threading.Thread): def __init__(self, currency): threading.Thread.__init__(self) self.currency = currency def run(self): global SQLConnection global cursor SQLString = "Select dval from ddata where dname ='%s'and ddate = '2009-07-17'" %self.currency z = time.time() while (time.time() - z) &lt; 2: cursor.execute(SQLString) print cursor.fetchall() SQLConnection = psycopg2.connect(database = "db", user = "xxxx", password = "xxxx") cursor = SQLConnection.cursor() a = testit('EURCZK') b = testit('EURPLN') a.start() b.start() </code></pre> <p>The only difference between the two is in the while loop. I am fairly new to thread programming. Is the postgres library (psycopg2) not "thread safe"? All this is running on Windows XP. Anything I can do?</p> <p>Thanks. </p>
1
2009-07-18T21:50:50Z
1,148,716
<p>bingo it's working. Someone left an answer but then seems to have removed it, to give each thread its own connection. And yep that solves it. So this code works:</p> <pre><code>import psycopg2 import threading import time class testit(threading.Thread): def __init__(self, currency): threading.Thread.__init__(self) self.currency = currency self.SQLConnection = psycopg2.connect(database = "db", user = "xxxx", password = "xxxx") self.cursor = self.SQLConnection.cursor() def run(self): SQLString = "Select dval from ddata where dname ='%s' and ddate = '2009-07-17'" \ %self.currency z = time.time() while (time.time() - z) &lt; 2: self.cursor.execute(SQLString) print self.cursor.fetchall() a = testit('EURCZK') b = testit('EURPLN') a.start() b.start() </code></pre>
0
2009-07-18T22:08:29Z
[ "python", "postgresql" ]
using task queues to schedule the fetching/parsing of a number of feeds in appengine python
1,148,709
<p>Say I had over 10,000 feeds that I wanted to periodically fetch/parse. If the period were say 1h that would be 24x10000 = 240,000 fetches.</p> <p>The current 10k limit of the labs taskqueue api would preclude one from setting up one task per fetch. How then would one do this?</p> <p>Update: re: fetching nurls per task: given the 30second timeout per request at some point this would hit a ceiling. Is there anyway to paralellize it so each tasqueue initiates a bunch of async paralell fetches each of which would take less than 30sec to finish but the lot togethere may take more than that</p>
0
2009-07-18T22:04:17Z
1,148,720
<p>2 fetches per task? 3?</p>
2
2009-07-18T22:10:25Z
[ "python", "google-app-engine", "feeds" ]
using task queues to schedule the fetching/parsing of a number of feeds in appengine python
1,148,709
<p>Say I had over 10,000 feeds that I wanted to periodically fetch/parse. If the period were say 1h that would be 24x10000 = 240,000 fetches.</p> <p>The current 10k limit of the labs taskqueue api would preclude one from setting up one task per fetch. How then would one do this?</p> <p>Update: re: fetching nurls per task: given the 30second timeout per request at some point this would hit a ceiling. Is there anyway to paralellize it so each tasqueue initiates a bunch of async paralell fetches each of which would take less than 30sec to finish but the lot togethere may take more than that</p>
0
2009-07-18T22:04:17Z
1,148,729
<p>Group up the fetches, so instead of queuing 1 fetch you queue up, say, a work unit that does 10 fetches.</p>
0
2009-07-18T22:16:01Z
[ "python", "google-app-engine", "feeds" ]
using task queues to schedule the fetching/parsing of a number of feeds in appengine python
1,148,709
<p>Say I had over 10,000 feeds that I wanted to periodically fetch/parse. If the period were say 1h that would be 24x10000 = 240,000 fetches.</p> <p>The current 10k limit of the labs taskqueue api would preclude one from setting up one task per fetch. How then would one do this?</p> <p>Update: re: fetching nurls per task: given the 30second timeout per request at some point this would hit a ceiling. Is there anyway to paralellize it so each tasqueue initiates a bunch of async paralell fetches each of which would take less than 30sec to finish but the lot togethere may take more than that</p>
0
2009-07-18T22:04:17Z
1,148,869
<p>Here's the asynchronous urlfetch API:</p> <p><a href="http://code.google.com/appengine/docs/python/urlfetch/asynchronousrequests.html" rel="nofollow">http://code.google.com/appengine/docs/python/urlfetch/asynchronousrequests.html</a></p> <p>Set of a bunch of requests with a reasonable deadline (give yourself some headroom under your timeout, so that if one request times out you still have time to process the others). Then wait on each one in turn and process as they complete.</p> <p>I haven't used this technique myself in GAE, so you're on your own finding any non-obvious gotchas. Sadly there doesn't seem to be a <code>select()</code> style call in the API to wait for the first of several requests to complete.</p>
3
2009-07-18T23:28:57Z
[ "python", "google-app-engine", "feeds" ]
MetaPython: Adding Methods to a Class
1,148,827
<p>I would like to add some methods to a class definition at runtime. However, when running the following code, I get some surprising (to me) results.</p> <h3>test.py</h3> <pre><code>class klass(object): pass for i in [1,2]: def f(self): print(i) setattr(klass, 'f' + str(i), f) </code></pre> <p>I get the following when testing on the command line:</p> <pre><code>&gt;&gt;&gt; import test &gt;&gt;&gt; k = test.klass() &gt;&gt;&gt; k.f1() 2 &gt;&gt;&gt; k.f2() 2 </code></pre> <p>Why does <code>k.f1()</code> return 2 instead of 1? It seems rather counter intuitive to me.</p> <h3>notes</h3> <p>This test was done using python3.0 on a kubuntu machine.</p>
1
2009-07-18T23:03:40Z
1,148,839
<p>My guess is that it's because <code>print (i)</code> prints <code>i</code> not <em>by value</em>, but <em>by reference</em>. Thus, when leaving the for loop, <em>i</em> has the value <strong>2</strong>, which will be printed both times. </p>
0
2009-07-18T23:10:21Z
[ "python", "binding", "metaprogramming" ]
MetaPython: Adding Methods to a Class
1,148,827
<p>I would like to add some methods to a class definition at runtime. However, when running the following code, I get some surprising (to me) results.</p> <h3>test.py</h3> <pre><code>class klass(object): pass for i in [1,2]: def f(self): print(i) setattr(klass, 'f' + str(i), f) </code></pre> <p>I get the following when testing on the command line:</p> <pre><code>&gt;&gt;&gt; import test &gt;&gt;&gt; k = test.klass() &gt;&gt;&gt; k.f1() 2 &gt;&gt;&gt; k.f2() 2 </code></pre> <p>Why does <code>k.f1()</code> return 2 instead of 1? It seems rather counter intuitive to me.</p> <h3>notes</h3> <p>This test was done using python3.0 on a kubuntu machine.</p>
1
2009-07-18T23:03:40Z
1,148,843
<p>It's the usual problem of binding -- you want early binding for the use of <code>i</code> inside the function and Python is doing late binding for it. You can force the earlier binding this way:</p> <pre><code>class klass(object): pass for i in [1,2]: def f(self, i=i): print(i) setattr(klass, 'f' + str(i), f) </code></pre> <p>or by wrapping f into an outer function layer taking i as an argument:</p> <pre><code>class klass(object): pass def fmaker(i): def f(self): print(i) return f for i in [1,2]: setattr(klass, 'f' + str(i), fmaker(i)) </code></pre>
11
2009-07-18T23:11:23Z
[ "python", "binding", "metaprogramming" ]
Rendering common session information in every view
1,148,854
<p>I'd like to output some information that depends on session data in Django. Let's take a "Login" / "Logged in as | Logout" fragment for example. It depends on my <code>request.session['user']</code>.</p> <p>Of course I can put a user object in the context every time I render a page and then switch on <code>{% if user %}</code>, but that seems to break DRY idea - I would have to add user to every context in every view.</p> <p>How can I extract a fragment like that and make it more common?</p>
0
2009-07-18T23:18:49Z
1,148,886
<p>Are you trying to make certain areas of your site only accessible when logged on? Or certain areas of a particular page?</p> <p>If you want to block off access to a whole URL you can use the @login_required decorator in your functions in your view to block certain access. Also, you can use includes to keep the common parts of your site that require user login in a separate html that gets included, that way you're only writing your if statements once.</p>
0
2009-07-18T23:45:47Z
[ "python", "django", "session", "templates" ]
Rendering common session information in every view
1,148,854
<p>I'd like to output some information that depends on session data in Django. Let's take a "Login" / "Logged in as | Logout" fragment for example. It depends on my <code>request.session['user']</code>.</p> <p>Of course I can put a user object in the context every time I render a page and then switch on <code>{% if user %}</code>, but that seems to break DRY idea - I would have to add user to every context in every view.</p> <p>How can I extract a fragment like that and make it more common?</p>
0
2009-07-18T23:18:49Z
1,148,887
<p>Use <a href="http://docs.djangoproject.com/en/dev/topics/templates/#template-inheritance" rel="nofollow">template inheritance</a> to derive all of your templates from a common base that suitably uses the common parts of the context, and make all your contexts with a factory function that ensures the insertion in them of those common parts.</p>
5
2009-07-18T23:46:47Z
[ "python", "django", "session", "templates" ]
Rendering common session information in every view
1,148,854
<p>I'd like to output some information that depends on session data in Django. Let's take a "Login" / "Logged in as | Logout" fragment for example. It depends on my <code>request.session['user']</code>.</p> <p>Of course I can put a user object in the context every time I render a page and then switch on <code>{% if user %}</code>, but that seems to break DRY idea - I would have to add user to every context in every view.</p> <p>How can I extract a fragment like that and make it more common?</p>
0
2009-07-18T23:18:49Z
7,569,126
<p>You may want to use a context processor that includes logic and place it into a variable you can use in any of your pages without adding it to each call.</p> <p>See more info at <a href="http://stackoverflow.com/questions/3221592/how-to-pass-common-dictionary-data-to-every-pages-in-django">how to pass common dictionary data to every pages in django</a></p>
0
2011-09-27T12:30:14Z
[ "python", "django", "session", "templates" ]
How to resume program (or exit) after opening webbrowser?
1,149,233
<p>I'm making a small Python program, which calls the <code>webbrowser</code> module to open a URL. Opening the URL works wonderfully.</p> <p>My problem is that once this line of code is reached, the problem is unresponsive. How do I get the program to proceed past this line of code and continue to execute? Below the problematic line is the problematic line, in context:</p> <pre><code>if viewinbrowser == "y": print "I can definitely do that. Loading URL now!" webbrowser.open_new(url) print "Exiting..." sys.exit() </code></pre> <p>The program does not get as far as executing the <code>print "Exiting..."</code>, which I added because I noticed the program wasn't leaving the if statement for some reason.</p> <p>I am running this program from the command line, in case that's important. <strong>Edit:</strong> I am running on Kubuntu 9.04 i386, using KDE 4.3 via backports. I use Firefox 3.5 as my default browser, declared in the System Settings for KDE, and it is called correctly by the program. (At least, a new tab opens up in Firefox with the desired URL—I believe that is the desired functionality.) <strong>/Edit</strong></p> <p>Also, I assume this problem would happen with pretty much any external call, but I'm very new to Python and don't know the terminology to search for on this site. (Searching for "python webbrowser" didn't yield anything helpful.) So, I apologize if it's already been discussed under a different heading!</p> <p>Any suggestions?</p>
2
2009-07-19T04:21:16Z
1,149,254
<p>The webbrowser module makes a system call to start a separate program (the web browser), then waits ( "blocks" ) for an exit code. This happens any time you start a program from another program. You have to (A) write your own function that does not block waiting for the webbrowser to exit (by using threads, fork(), or similar), or find out if the webbrowser module has a non-blocking call.</p>
0
2009-07-19T04:43:24Z
[ "python", "browser", "if-statement" ]
How to resume program (or exit) after opening webbrowser?
1,149,233
<p>I'm making a small Python program, which calls the <code>webbrowser</code> module to open a URL. Opening the URL works wonderfully.</p> <p>My problem is that once this line of code is reached, the problem is unresponsive. How do I get the program to proceed past this line of code and continue to execute? Below the problematic line is the problematic line, in context:</p> <pre><code>if viewinbrowser == "y": print "I can definitely do that. Loading URL now!" webbrowser.open_new(url) print "Exiting..." sys.exit() </code></pre> <p>The program does not get as far as executing the <code>print "Exiting..."</code>, which I added because I noticed the program wasn't leaving the if statement for some reason.</p> <p>I am running this program from the command line, in case that's important. <strong>Edit:</strong> I am running on Kubuntu 9.04 i386, using KDE 4.3 via backports. I use Firefox 3.5 as my default browser, declared in the System Settings for KDE, and it is called correctly by the program. (At least, a new tab opens up in Firefox with the desired URL—I believe that is the desired functionality.) <strong>/Edit</strong></p> <p>Also, I assume this problem would happen with pretty much any external call, but I'm very new to Python and don't know the terminology to search for on this site. (Searching for "python webbrowser" didn't yield anything helpful.) So, I apologize if it's already been discussed under a different heading!</p> <p>Any suggestions?</p>
2
2009-07-19T04:21:16Z
1,149,264
<p>The easiest thing to do here is probably to fork. I'm pretty sure this doesn't work in windows unfortunately, since I think their process model might be different from unix-like operating systems. The process will be similar, though.</p> <pre><code>pid = os.fork() if pid: # we are the parent, continue on print "This runs in a separate process from the else clause." else: #child runs browser then quits. webbrowser.open_new(url) print "Exiting..." sys.exit() </code></pre>
3
2009-07-19T04:56:31Z
[ "python", "browser", "if-statement" ]
How to resume program (or exit) after opening webbrowser?
1,149,233
<p>I'm making a small Python program, which calls the <code>webbrowser</code> module to open a URL. Opening the URL works wonderfully.</p> <p>My problem is that once this line of code is reached, the problem is unresponsive. How do I get the program to proceed past this line of code and continue to execute? Below the problematic line is the problematic line, in context:</p> <pre><code>if viewinbrowser == "y": print "I can definitely do that. Loading URL now!" webbrowser.open_new(url) print "Exiting..." sys.exit() </code></pre> <p>The program does not get as far as executing the <code>print "Exiting..."</code>, which I added because I noticed the program wasn't leaving the if statement for some reason.</p> <p>I am running this program from the command line, in case that's important. <strong>Edit:</strong> I am running on Kubuntu 9.04 i386, using KDE 4.3 via backports. I use Firefox 3.5 as my default browser, declared in the System Settings for KDE, and it is called correctly by the program. (At least, a new tab opens up in Firefox with the desired URL—I believe that is the desired functionality.) <strong>/Edit</strong></p> <p>Also, I assume this problem would happen with pretty much any external call, but I'm very new to Python and don't know the terminology to search for on this site. (Searching for "python webbrowser" didn't yield anything helpful.) So, I apologize if it's already been discussed under a different heading!</p> <p>Any suggestions?</p>
2
2009-07-19T04:21:16Z
1,149,285
<p>This looks like it depends on which platform you're running on.</p> <ul> <li>MacOSX - returns True immediately and opens up browser window. Presumably your desired behavior.</li> <li>Linux (no X) - Open up links textmode browser. Once this is closed, returns True.</li> <li>Linux (with X) - Opens up Konquerer (in my case). Returns True immediately. Your desired behavior.</li> </ul> <p>I'm guessing you're on Windows, which, as another commentor mentioned doesn't have fork. I'm also guessing that the webbrowser module uses fork internally, which is why it's not working for you on Windows. If so, then using the threading module to create a new thread that opens the webbrowser might be the easiest solution:</p> <pre><code>&gt;&gt;&gt; import webbrowser &gt;&gt;&gt; import threading &gt;&gt;&gt; x=lambda: webbrowser.open_new('http://scompt.com') &gt;&gt;&gt; t=threading.Thread(target=x) &gt;&gt;&gt; t.start() </code></pre>
4
2009-07-19T05:09:51Z
[ "python", "browser", "if-statement" ]
How to create Classes in Python with highly constrained instances
1,149,253
<p>In Python, there are examples of built-in classes with highly constrained instances. For example, "None" is the only instance of its class, and in the bool class there are only two objects, "True" and "False" (I hope I am more-or-less correct so far). </p> <p>Another good example are integers: if a and b are instances of the int type then a == b implies that a is b. </p> <p>Two questions:</p> <ol> <li><p>How does one create a class with similarly constrained instances? For example we could ask for a class with exactly 5 instances. Or there could be infinitely many instances, like type int, but these are not arbitrary. </p></li> <li><p>if integers form a class, why does int() give the 0 instance? compare this to a user-defined class Cl, where Cl() would give an instance of the class, not <em>a specific unique instance</em>, like 0. Shouldn't int() return an unspecified integer object, i.e. an integer without a specified value?</p></li> </ol>
2
2009-07-19T04:42:10Z
1,149,265
<p>I think some names for the concept you're thinking about are <a href="http://en.wikipedia.org/wiki/String%5Finterning" rel="nofollow">interning</a> and <a href="http://en.wikipedia.org/wiki/Immutable%5Fobject" rel="nofollow">immutable objects</a>.</p> <p>As for an answer to your specific questions, I think for #1, you could look up your constrained instance in a class method and return it. </p> <p>For question #2, I think it's just a matter of how you specify your class. A non-specific instance of the int class would be pretty useless, so just spec it so it's impossible to create.</p>
1
2009-07-19T04:56:43Z
[ "python", "math", "class" ]
How to create Classes in Python with highly constrained instances
1,149,253
<p>In Python, there are examples of built-in classes with highly constrained instances. For example, "None" is the only instance of its class, and in the bool class there are only two objects, "True" and "False" (I hope I am more-or-less correct so far). </p> <p>Another good example are integers: if a and b are instances of the int type then a == b implies that a is b. </p> <p>Two questions:</p> <ol> <li><p>How does one create a class with similarly constrained instances? For example we could ask for a class with exactly 5 instances. Or there could be infinitely many instances, like type int, but these are not arbitrary. </p></li> <li><p>if integers form a class, why does int() give the 0 instance? compare this to a user-defined class Cl, where Cl() would give an instance of the class, not <em>a specific unique instance</em>, like 0. Shouldn't int() return an unspecified integer object, i.e. an integer without a specified value?</p></li> </ol>
2
2009-07-19T04:42:10Z
1,149,269
<p>For the first question you could implement a singleton class design pattern <a href="http://en.wikipedia.org/wiki/Singleton_pattern" rel="nofollow">http://en.wikipedia.org/wiki/Singleton_pattern</a> you should from that restrict the number of instances.</p> <p>For the second question, I think this kind of explains your issue <a href="http://docs.python.org/library/stdtypes.html" rel="nofollow">http://docs.python.org/library/stdtypes.html</a></p> <p>Because integers are types, there are limitations to it.</p> <p>Here is another resource... <a href="http://docs.python.org/library/functions.html#built-in-funcs" rel="nofollow">http://docs.python.org/library/functions.html#built-in-funcs</a></p>
3
2009-07-19T04:58:43Z
[ "python", "math", "class" ]
How to create Classes in Python with highly constrained instances
1,149,253
<p>In Python, there are examples of built-in classes with highly constrained instances. For example, "None" is the only instance of its class, and in the bool class there are only two objects, "True" and "False" (I hope I am more-or-less correct so far). </p> <p>Another good example are integers: if a and b are instances of the int type then a == b implies that a is b. </p> <p>Two questions:</p> <ol> <li><p>How does one create a class with similarly constrained instances? For example we could ask for a class with exactly 5 instances. Or there could be infinitely many instances, like type int, but these are not arbitrary. </p></li> <li><p>if integers form a class, why does int() give the 0 instance? compare this to a user-defined class Cl, where Cl() would give an instance of the class, not <em>a specific unique instance</em>, like 0. Shouldn't int() return an unspecified integer object, i.e. an integer without a specified value?</p></li> </ol>
2
2009-07-19T04:42:10Z
1,149,272
<p>You're talking about giving a class <em>value semantics</em>, which is typically done by creating class instances in the normal way, but remembering each one, and if a matching instance would be created, give the already created instance instead. In python, this can be achieved by overloading a classes <code>__new__</code> <a href="http://docs.python.org/reference/datamodel.html" rel="nofollow">method</a>. </p> <p>Brief example, say we wanted to use pairs of integers to represent coordinates, and have the proper value semantics. </p> <pre><code>class point(object): memo = {} def __new__(cls, x, y): if (x, y) in cls.memo: # if it already exists, return cls.memo[(x, y)] # return the existing instance else: # otherwise, newPoint = object.__new__(cls) # create it, newPoint.x = x # initialize it, as you would in __init__ newPoint.y = y cls.memo[(x, y)] = newPoint # memoize it, return newPoint # and return it! </code></pre> <p><hr /></p>
5
2009-07-19T05:00:00Z
[ "python", "math", "class" ]
How to create Classes in Python with highly constrained instances
1,149,253
<p>In Python, there are examples of built-in classes with highly constrained instances. For example, "None" is the only instance of its class, and in the bool class there are only two objects, "True" and "False" (I hope I am more-or-less correct so far). </p> <p>Another good example are integers: if a and b are instances of the int type then a == b implies that a is b. </p> <p>Two questions:</p> <ol> <li><p>How does one create a class with similarly constrained instances? For example we could ask for a class with exactly 5 instances. Or there could be infinitely many instances, like type int, but these are not arbitrary. </p></li> <li><p>if integers form a class, why does int() give the 0 instance? compare this to a user-defined class Cl, where Cl() would give an instance of the class, not <em>a specific unique instance</em>, like 0. Shouldn't int() return an unspecified integer object, i.e. an integer without a specified value?</p></li> </ol>
2
2009-07-19T04:42:10Z
1,149,275
<ol> <li>Create them in advance and return one of those from <code>__new__</code> instead of creating a new object, or cache created instances (<a href="http://docs.python.org/library/weakref.html#weakref.WeakValueDictionary" rel="nofollow">weakrefs</a> are handy here) and return one of those instead of creating a new object.</li> <li>Integers are special. Effectively this means you can never use identity to compare them as you would use identity to compare other objects. Since they are immutable and rarely used in any way other than a value context, this isn't much of a problem. This is done, as far as I can tell, for implementation reasons more than anything else. (And since there's no clear indication that it's an incorrect way, it's a good decision.)</li> </ol> <p><em>Singletons such as None:</em> Create the class with the name you want to give the variable, and then rebind the variable to the (only) instance, or delete the class afterwards. This is handy when you want to emulate an interface such as <code>getattr</code>, where a parameter is optional but using <code>None</code> is different from not providing a value.</p> <pre><code>class raise_error(object): pass raise_error = raise_error() def example(d, key, default=raise_error): """Return d[key] if key in d, else return default or raise KeyError if default isn't supplied.""" try: return d[key] except KeyError: if default is raise_error: raise return default </code></pre>
2
2009-07-19T05:04:01Z
[ "python", "math", "class" ]
How to create Classes in Python with highly constrained instances
1,149,253
<p>In Python, there are examples of built-in classes with highly constrained instances. For example, "None" is the only instance of its class, and in the bool class there are only two objects, "True" and "False" (I hope I am more-or-less correct so far). </p> <p>Another good example are integers: if a and b are instances of the int type then a == b implies that a is b. </p> <p>Two questions:</p> <ol> <li><p>How does one create a class with similarly constrained instances? For example we could ask for a class with exactly 5 instances. Or there could be infinitely many instances, like type int, but these are not arbitrary. </p></li> <li><p>if integers form a class, why does int() give the 0 instance? compare this to a user-defined class Cl, where Cl() would give an instance of the class, not <em>a specific unique instance</em>, like 0. Shouldn't int() return an unspecified integer object, i.e. an integer without a specified value?</p></li> </ol>
2
2009-07-19T04:42:10Z
1,149,398
<p>Looks like #1 has been well answered already and I just want to explain a principle, related to #2, which appears to have been missed by all respondents: for most built-in types, calling the type without parameters (the "default constructor") returns an instance of that type <em>which evaluates as false</em>. That means an empty container for container types, a number which compares equal to zero for number types.</p> <pre><code>&gt;&gt;&gt; import decimal &gt;&gt;&gt; decimal.Decimal() Decimal("0") &gt;&gt;&gt; set() set([]) &gt;&gt;&gt; float() 0.0 &gt;&gt;&gt; tuple() () &gt;&gt;&gt; dict() {} &gt;&gt;&gt; list() [] &gt;&gt;&gt; str() '' &gt;&gt;&gt; bool() False </code></pre> <p>See? Pretty regular indeed! Moreover, for mutable types, like most containers, calling the type always returns a new instance; for immutable types, like numbers and strings, it doesn't matter (it's a possible internal optimization to return new reference to an existing immutable instance, but the implementation is not required to perform such optimization, and if it does it can and often will perform them quite selectively) since it's never correct to compare immutable type instances with <code>is</code> or equivalently by <code>id()</code>.</p> <p>If you design a type of which some instances can evaluate as false (by having <code>__len__</code> or <code>__nonzero__</code> special methods in the class), it's advisable to follow the same precept (have <code>__init__</code> [or <code>__new__</code> for immutables], if called without arguments [[beyond <code>self</code> for <code>__init__</code> and 'cls' for <code>__new__</code> of course]], prepare a [[new, if mutable]] "empty" or "zero-like" instance of the class).</p>
4
2009-07-19T07:08:49Z
[ "python", "math", "class" ]
How to create Classes in Python with highly constrained instances
1,149,253
<p>In Python, there are examples of built-in classes with highly constrained instances. For example, "None" is the only instance of its class, and in the bool class there are only two objects, "True" and "False" (I hope I am more-or-less correct so far). </p> <p>Another good example are integers: if a and b are instances of the int type then a == b implies that a is b. </p> <p>Two questions:</p> <ol> <li><p>How does one create a class with similarly constrained instances? For example we could ask for a class with exactly 5 instances. Or there could be infinitely many instances, like type int, but these are not arbitrary. </p></li> <li><p>if integers form a class, why does int() give the 0 instance? compare this to a user-defined class Cl, where Cl() would give an instance of the class, not <em>a specific unique instance</em>, like 0. Shouldn't int() return an unspecified integer object, i.e. an integer without a specified value?</p></li> </ol>
2
2009-07-19T04:42:10Z
1,149,415
<p>To answer the more generic question of how to create constrained instances, it depends on the constraint. Both you examples above are a sort of "singletons", although the second example is a variation where you can have many instances of one class, but you will have only one per input value.</p> <p>These can both done by overriding the class' <code>__new__</code> method, so that the class creates the instances if it hasn't been created already, and both returns it, <em>and</em> stores it as an attribute on the class (as has been suggested above). However, a slightly less hackish way is to use metaclasses. These are classes that change the behaviour of classes, and singletons is a great example of when to use metaclasses. And the great thing about this is that you can reuse metaclasses. By creating a Singleton metaclass, you can then use this metaclass for all Singletons you have. </p> <p>A nice Python example in on Wikipedia: <a href="http://en.wikipedia.org/wiki/Singleton_pattern#Python" rel="nofollow">http://en.wikipedia.org/wiki/Singleton_pattern#Python</a></p> <p>Here is a variation that will create a different instance depending on parameters: (It's not perfect. If you pass in a parameter which is a dict, it will fail, for example. But it's a start):</p> <pre><code># Notice how you subclass not from object, but from type. You are in other words # creating a new type of type. class SingletonPerValue(type): def __init__(cls, name, bases, dict): super(SingletonPerValue, cls).__init__(name, bases, dict) # Here we store the created instances later. cls.instances = {} def __call__(cls, *args, **kw): # We make a tuple out of all parameters. This is so we can use it as a key # This will fail if you send in unhasheable parameters. params = args + tuple(kw.items()) # Check in cls.instances if this combination of parameter has been used: if params not in cls.instances: # No, this is a new combination of parameters. Create a new instance, # and store it in the dictionary: cls.instances[params] = super(SingletonPerValue, cls).__call__(*args, **kw) return cls.instances[params] class MyClass(object): # Say that this class should use a specific metaclass: __metaclass__ = SingletonPerValue def __init__(self, value): self.value = value print 1, MyClass(1) print 2, MyClass(2) print 2, MyClass(2) print 2, MyClass(2) print 3, MyClass(3) </code></pre> <p>But there are other constraints in Python than instantiation. Many of them can be done with metaclasses. Others have shortcuts, here is a class that only allows you to set the attributes 'items' and 'fruit', for example. </p> <pre><code>class Constrained(object): __slots__ = ['items', 'fruit'] con = Constrained() con.items = 6 con.fruit = "Banana" con.yummy = True </code></pre> <p>If you want restrictions on attributes, but not quite these strong, you can override <code>__getattr__, __setattr__ and __delattr__</code> to make many fantastic and horrid things happen. :-) There are also packages out there that let you set constraints on attributes, etc.</p>
2
2009-07-19T07:31:14Z
[ "python", "math", "class" ]
How to create Classes in Python with highly constrained instances
1,149,253
<p>In Python, there are examples of built-in classes with highly constrained instances. For example, "None" is the only instance of its class, and in the bool class there are only two objects, "True" and "False" (I hope I am more-or-less correct so far). </p> <p>Another good example are integers: if a and b are instances of the int type then a == b implies that a is b. </p> <p>Two questions:</p> <ol> <li><p>How does one create a class with similarly constrained instances? For example we could ask for a class with exactly 5 instances. Or there could be infinitely many instances, like type int, but these are not arbitrary. </p></li> <li><p>if integers form a class, why does int() give the 0 instance? compare this to a user-defined class Cl, where Cl() would give an instance of the class, not <em>a specific unique instance</em>, like 0. Shouldn't int() return an unspecified integer object, i.e. an integer without a specified value?</p></li> </ol>
2
2009-07-19T04:42:10Z
1,149,503
<p>Note: this is not really an answer to your question, but more a comment I could not fit in the "comment" space.</p> <p>Please note that <code>a == b</code> does <strong>NOT</strong> implies that <code>a is b</code>.</p> <p>It is true only for first handfuls of integers (like first hundred or so - I do not know exactly) and it is only an implementation detail of CPython, that actually changed with the switch to Python 3.0.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; n1 = 4000 &gt;&gt;&gt; n2 = 4000 &gt;&gt;&gt; n1 == n2 True &gt;&gt;&gt; n1 is n2 False </code></pre>
1
2009-07-19T08:53:16Z
[ "python", "math", "class" ]
How can I use Sphinx' Autodoc-extension for private methods?
1,149,280
<p>I am using Sphinx for documenting my python project. I have the autodoc extension enabled and have the following in my docs.</p> <pre><code>.. autoclass:: ClassName :members: </code></pre> <p>The problem is, it only documents the <a href="http://sphinx.pocoo.org/ext/autodoc.html">non-private methods</a> in the class. How do I include the private methods too?</p>
18
2009-07-19T05:07:51Z
1,149,354
<p>Have you tried using a <a href="http://sphinx.pocoo.org/ext/autodoc.html#skipping-members" rel="nofollow">custom method</a> for determining whether a member should be included in the documentation, using <code>autodoc-skip-member</code>?</p>
4
2009-07-19T06:28:49Z
[ "python", "documentation", "python-sphinx" ]
How can I use Sphinx' Autodoc-extension for private methods?
1,149,280
<p>I am using Sphinx for documenting my python project. I have the autodoc extension enabled and have the following in my docs.</p> <pre><code>.. autoclass:: ClassName :members: </code></pre> <p>The problem is, it only documents the <a href="http://sphinx.pocoo.org/ext/autodoc.html">non-private methods</a> in the class. How do I include the private methods too?</p>
18
2009-07-19T05:07:51Z
1,149,714
<p>Here's a hint: imagine that private means "secret". </p> <p>That's why Sphinx won't document them. </p> <p>If you don't mean "secret", consider changing their names. Avoid using the single-leading-underscore name in general; it doesn't help unless you have a reason to keep the implementation secret.</p>
-7
2009-07-19T11:37:02Z
[ "python", "documentation", "python-sphinx" ]
How can I use Sphinx' Autodoc-extension for private methods?
1,149,280
<p>I am using Sphinx for documenting my python project. I have the autodoc extension enabled and have the following in my docs.</p> <pre><code>.. autoclass:: ClassName :members: </code></pre> <p>The problem is, it only documents the <a href="http://sphinx.pocoo.org/ext/autodoc.html">non-private methods</a> in the class. How do I include the private methods too?</p>
18
2009-07-19T05:07:51Z
1,200,075
<p>No, private means private to the class and that it shouldn't be used from the public API. It's not meant to mean secret and for those of us wishing to use sphinx for full documentation of classes, excluding private methods is rather annoying.</p> <p>The previous answer is correct. You will have to use a custom method as Sphinx does not currently support autodoc in conjunction with private methods.</p>
2
2009-07-29T13:00:36Z
[ "python", "documentation", "python-sphinx" ]
How can I use Sphinx' Autodoc-extension for private methods?
1,149,280
<p>I am using Sphinx for documenting my python project. I have the autodoc extension enabled and have the following in my docs.</p> <pre><code>.. autoclass:: ClassName :members: </code></pre> <p>The problem is, it only documents the <a href="http://sphinx.pocoo.org/ext/autodoc.html">non-private methods</a> in the class. How do I include the private methods too?</p>
18
2009-07-19T05:07:51Z
6,106,855
<p>One way to get around this is to explicitly force Sphinx to document private members. You can do this by appending <code>automethod</code> to the end of the class level docs:</p> <pre><code>class SmokeMonster(object): """ A large smoke monster that protects the island. """ def __init__(self,speed): """ :param speed: Velocity in MPH of the smoke monster :type speed: int .. document private functions .. automethod:: _evaporate """ self.speed = speed def _evaporate(self): """ Removes the smoke monster from reality. Not to be called by client. """ pass </code></pre>
8
2011-05-24T07:02:59Z
[ "python", "documentation", "python-sphinx" ]
How can I use Sphinx' Autodoc-extension for private methods?
1,149,280
<p>I am using Sphinx for documenting my python project. I have the autodoc extension enabled and have the following in my docs.</p> <pre><code>.. autoclass:: ClassName :members: </code></pre> <p>The problem is, it only documents the <a href="http://sphinx.pocoo.org/ext/autodoc.html">non-private methods</a> in the class. How do I include the private methods too?</p>
18
2009-07-19T05:07:51Z
7,740,295
<p>if you are using sphinx 1.1 or above, from the sphinx documentation site at <a href="http://sphinx.pocoo.org/ext/autodoc.html">http://sphinx.pocoo.org/ext/autodoc.html</a>,</p> <pre><code>:special-members: :private-members: </code></pre>
18
2011-10-12T12:47:28Z
[ "python", "documentation", "python-sphinx" ]
How can I use Sphinx' Autodoc-extension for private methods?
1,149,280
<p>I am using Sphinx for documenting my python project. I have the autodoc extension enabled and have the following in my docs.</p> <pre><code>.. autoclass:: ClassName :members: </code></pre> <p>The problem is, it only documents the <a href="http://sphinx.pocoo.org/ext/autodoc.html">non-private methods</a> in the class. How do I include the private methods too?</p>
18
2009-07-19T05:07:51Z
30,144,019
<p>Looking at <a href="https://github.com/sphinx-doc/sphinx/blob/master/sphinx/apidoc.py#L28" rel="nofollow">apidoc code</a>, we can change what sphinx-apidoc generate setting an environment variable:</p> <pre><code>export SPHINX_APIDOC_OPTIONS='members,special-members,private-members,undoc-members,show-inheritance' </code></pre> <p>You can also add this setup into your Makefile (if your package uses one):</p> <pre><code>docs: rm -rf docs/api SPHINX_APIDOC_OPTIONS='members,special-members,private-members,undoc-members,show-inheritance' sphinx-apidoc -o docs/api/ intellprice $(MAKE) -C docs clean $(MAKE) -C docs html </code></pre>
2
2015-05-09T19:14:55Z
[ "python", "documentation", "python-sphinx" ]