title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How to deliver instance of object to instance of SocketServer.BaseRequestHandler?
711,002
<p>This is problem. My primary work is : deliver "s" object to "handle" method in TestRequestHandler class. My first step was : deliver "s" object through "point" method to TestServer class, but here im stuck. How to deliver "s" object to TestRequestHandler? Some suggestions?</p> <pre><code>import threading import SocketServer from socket import * class TestRequestHandler(SocketServer.BaseRequestHandler): def __init__(self, request, client_address, server): SocketServer.BaseRequestHandler.__init__(self, request, client_address, server) return def setup(self): return SocketServer.BaseRequestHandler.setup(self) def handle(self): data = self.request.recv(1024) if (data): self.request.send(data) print data def finish(self): return SocketServer.BaseRequestHandler.finish(self) class TestServer(SocketServer.TCPServer): def __init__(self, server_address, handler_class=TestRequestHandler): print "__init__" SocketServer.TCPServer.__init__(self, server_address, handler_class) return def point(self,obj): self.obj = obj print "point" def server_activate(self): SocketServer.TCPServer.server_activate(self) return def serve_forever(self): print "serve_forever" while True: self.handle_request() return def handle_request(self): return SocketServer.TCPServer.handle_request(self) if __name__ == '__main__': s = socket(AF_INET, SOCK_STREAM) address = ('localhost', 6666) server = TestServer(address, TestRequestHandler) server.point(s) t = threading.Thread(target=server.serve_forever()) t.setDaemon(True) t.start() </code></pre>
2
2009-04-02T18:26:57Z
711,065
<p>If the value of s is set once, and not reinitialized - you could make it a class variable as opposed to an instance variable of TestServer, and then have the handler retrieve it via a class method of TestServer in the handler's constructor.</p> <p>eg: TestServer._mySocket = s</p>
1
2009-04-02T18:42:07Z
[ "python", "python-2.7", "sockets", "tcp", "socketserver" ]
How to deliver instance of object to instance of SocketServer.BaseRequestHandler?
711,002
<p>This is problem. My primary work is : deliver "s" object to "handle" method in TestRequestHandler class. My first step was : deliver "s" object through "point" method to TestServer class, but here im stuck. How to deliver "s" object to TestRequestHandler? Some suggestions?</p> <pre><code>import threading import SocketServer from socket import * class TestRequestHandler(SocketServer.BaseRequestHandler): def __init__(self, request, client_address, server): SocketServer.BaseRequestHandler.__init__(self, request, client_address, server) return def setup(self): return SocketServer.BaseRequestHandler.setup(self) def handle(self): data = self.request.recv(1024) if (data): self.request.send(data) print data def finish(self): return SocketServer.BaseRequestHandler.finish(self) class TestServer(SocketServer.TCPServer): def __init__(self, server_address, handler_class=TestRequestHandler): print "__init__" SocketServer.TCPServer.__init__(self, server_address, handler_class) return def point(self,obj): self.obj = obj print "point" def server_activate(self): SocketServer.TCPServer.server_activate(self) return def serve_forever(self): print "serve_forever" while True: self.handle_request() return def handle_request(self): return SocketServer.TCPServer.handle_request(self) if __name__ == '__main__': s = socket(AF_INET, SOCK_STREAM) address = ('localhost', 6666) server = TestServer(address, TestRequestHandler) server.point(s) t = threading.Thread(target=server.serve_forever()) t.setDaemon(True) t.start() </code></pre>
2
2009-04-02T18:26:57Z
711,905
<p>If I understand correctly, I think you perhaps are misunderstanding how the module works. You are already specifying an address of 'localhost:6666' for the server to bind on. </p> <p>When you start the server via your call to serve_forever(), this is going to cause the server to start listening to a socket on localhost:6666. </p> <p>According to the documentation, that socket is passed to your RequestHandler as the 'request' object. When data is received on the socket, your 'handle' method should be able to recv/send from/to that object using the documented socket API.</p> <p>If you want a further abstraction, it looks like your RequestHandler can extend from StreamRequestHandler and read/write to the socket using file-like objects instead.</p> <p>The point is, there is no need for you to create an additional socket and then try to force your server to use the new one instead. Part of the value of the SocketServer module is that it manages the lifecycle of the socket for you.</p> <p>On the flip side, if you want to test your server from a client's perspective, then you would want to create a socket that you can read/write your client requests on. But you would never pass this socket to your server, per se. You would probably do this in a completely separate process and test your server via IPC over the socket.</p> <p><strong>Edit based on new information</strong></p> <p>To get server A to open a socket to server B when server A receives data one solution is to simply open a socket from inside your RequestHandler. That said, there are likely some other design concerns that you will need to address based on the requirements of your service. </p> <p>For example, you may want to use a simple connection pool that say opens a few sockets to server B that server A can use like a resource. There may already be some libraries in Python that help with this. </p> <p>Given your current design, your RequestHandler has access to the server as a member variable so you could do something like this:</p> <pre><code>class TestServer(SocketServer.TCPServer): def point (self, socketB): self.socketB = socketB # hold serverB socket class TestRequestHandler(SocketServer.BaseRequestHandler): def handle(self): data = self.request.recv(1024) if (data): self.request.send(data) print data self.server.socketB ... # Do whatever with the socketB </code></pre> <p>But like I said, it may be better for you to have some sort of connection pool or other object that manages your server B socket such that your server A handler can just acquire/release the socket as incoming requests are handled.</p> <p>This way you can better deal with conditions where server B breaks the socket. Your current design wouldn't be able to handle broken sockets very easily. Just some thoughts...</p>
1
2009-04-02T22:39:47Z
[ "python", "python-2.7", "sockets", "tcp", "socketserver" ]
How to deliver instance of object to instance of SocketServer.BaseRequestHandler?
711,002
<p>This is problem. My primary work is : deliver "s" object to "handle" method in TestRequestHandler class. My first step was : deliver "s" object through "point" method to TestServer class, but here im stuck. How to deliver "s" object to TestRequestHandler? Some suggestions?</p> <pre><code>import threading import SocketServer from socket import * class TestRequestHandler(SocketServer.BaseRequestHandler): def __init__(self, request, client_address, server): SocketServer.BaseRequestHandler.__init__(self, request, client_address, server) return def setup(self): return SocketServer.BaseRequestHandler.setup(self) def handle(self): data = self.request.recv(1024) if (data): self.request.send(data) print data def finish(self): return SocketServer.BaseRequestHandler.finish(self) class TestServer(SocketServer.TCPServer): def __init__(self, server_address, handler_class=TestRequestHandler): print "__init__" SocketServer.TCPServer.__init__(self, server_address, handler_class) return def point(self,obj): self.obj = obj print "point" def server_activate(self): SocketServer.TCPServer.server_activate(self) return def serve_forever(self): print "serve_forever" while True: self.handle_request() return def handle_request(self): return SocketServer.TCPServer.handle_request(self) if __name__ == '__main__': s = socket(AF_INET, SOCK_STREAM) address = ('localhost', 6666) server = TestServer(address, TestRequestHandler) server.point(s) t = threading.Thread(target=server.serve_forever()) t.setDaemon(True) t.start() </code></pre>
2
2009-04-02T18:26:57Z
712,976
<p>Ok, my main task is this. Construction of the listening server (A-server - localhost, 6666) which during start will open "hard" connection to the different server (B-server - localhost, 7777). When the customer send data to the A-server this (A-server) sends data (having that hard connection to the B-server) to B-server, the answer receives from the B-server to A-server and answer sends to the customer. Then again : the customer sends data, A-server receives them, then sends to the B-server, the answer receives data from the B-server and A-server send data to the customer. And so round and round. The connection to the B-server is closes just when the server A will stop. All above is the test of making this.</p>
1
2009-04-03T08:06:07Z
[ "python", "python-2.7", "sockets", "tcp", "socketserver" ]
calling execfile() in custom namespace executes code in '__builtin__' namespace
711,066
<p>When I call execfile without passing the globals or locals arguments it creates objects in the current namespace, but if I call execfile and specify a dict for globals (and/or locals), it creates objects in the <code>__builtin__</code> namespace. </p> <p>Take the following example:</p> <pre><code># exec.py def myfunc(): print 'myfunc created in %s namespace' % __name__ </code></pre> <p>exec.py is execfile'd from main.py as follows.</p> <pre><code># main.py print 'execfile in global namespace:' execfile('exec.py') myfunc() print print 'execfile in custom namespace:' d = {} execfile('exec.py', d) d['myfunc']() </code></pre> <p>when I run main.py from the commandline I get the following output.</p> <pre><code>execfile in global namespace: myfunc created in __main__ namespace execfile in custom namespace: myfunc created in __builtin__ namespace </code></pre> <p>Why is it being run in <code>__builtin__</code> namespace in the second case? </p> <p>Furthermore, if I then try to run myfunc from <code>__builtins__</code>, I get an AttributeError. (This is what I would hope happens, but then why is <code>__name__</code> set to <code>__builtin__</code>?)</p> <pre><code>&gt;&gt;&gt; __builtins__.myfunc() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? AttributeError: 'module' object has no attribute 'myfunc' </code></pre> <p>Can anyone explain this behaviour? Thanks</p>
4
2009-04-02T18:42:15Z
711,127
<p>First off, <code>__name__</code> is not a namespace - its a reference to the name of the module it belongs to, ie: somemod.py -> <code>somemod.__name__ == 'somemod'</code> The exception to this being if you run a module as an executable from the commandline, then the <code>__name__</code> is '__main__'.</p> <p>in your example there is a lucky coincidence that your module being run as main is also named main.</p> <p>Execfile executes the contents of the module WITHOUT importing it as a module. As such, the <code>__name__</code> doesn't get set, because its not a module - its just an executed sequence of code.</p>
4
2009-04-02T18:58:00Z
[ "python", "namespaces" ]
calling execfile() in custom namespace executes code in '__builtin__' namespace
711,066
<p>When I call execfile without passing the globals or locals arguments it creates objects in the current namespace, but if I call execfile and specify a dict for globals (and/or locals), it creates objects in the <code>__builtin__</code> namespace. </p> <p>Take the following example:</p> <pre><code># exec.py def myfunc(): print 'myfunc created in %s namespace' % __name__ </code></pre> <p>exec.py is execfile'd from main.py as follows.</p> <pre><code># main.py print 'execfile in global namespace:' execfile('exec.py') myfunc() print print 'execfile in custom namespace:' d = {} execfile('exec.py', d) d['myfunc']() </code></pre> <p>when I run main.py from the commandline I get the following output.</p> <pre><code>execfile in global namespace: myfunc created in __main__ namespace execfile in custom namespace: myfunc created in __builtin__ namespace </code></pre> <p>Why is it being run in <code>__builtin__</code> namespace in the second case? </p> <p>Furthermore, if I then try to run myfunc from <code>__builtins__</code>, I get an AttributeError. (This is what I would hope happens, but then why is <code>__name__</code> set to <code>__builtin__</code>?)</p> <pre><code>&gt;&gt;&gt; __builtins__.myfunc() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? AttributeError: 'module' object has no attribute 'myfunc' </code></pre> <p>Can anyone explain this behaviour? Thanks</p>
4
2009-04-02T18:42:15Z
711,224
<p>The execfile function is similar to the exec statement. If you look at the <a href="http://docs.python.org/reference/simple%5Fstmts.html#exec" rel="nofollow">documentation for exec</a> you'll see the following paragraph that explains the behavior.</p> <blockquote> <p>As a side effect, an implementation may insert additional keys into the dictionaries given besides those corresponding to variable names set by the executed code. For example, the current implementation may add a reference to the dictionary of the built-in module <code>__builtin__</code> under the key <code>__builtins__</code> (!).</p> </blockquote> <p>Edit: I now see that my answer applies to one possible interpretation of the question title. My answer does not apply to the actual question asked.</p>
1
2009-04-02T19:28:29Z
[ "python", "namespaces" ]
calling execfile() in custom namespace executes code in '__builtin__' namespace
711,066
<p>When I call execfile without passing the globals or locals arguments it creates objects in the current namespace, but if I call execfile and specify a dict for globals (and/or locals), it creates objects in the <code>__builtin__</code> namespace. </p> <p>Take the following example:</p> <pre><code># exec.py def myfunc(): print 'myfunc created in %s namespace' % __name__ </code></pre> <p>exec.py is execfile'd from main.py as follows.</p> <pre><code># main.py print 'execfile in global namespace:' execfile('exec.py') myfunc() print print 'execfile in custom namespace:' d = {} execfile('exec.py', d) d['myfunc']() </code></pre> <p>when I run main.py from the commandline I get the following output.</p> <pre><code>execfile in global namespace: myfunc created in __main__ namespace execfile in custom namespace: myfunc created in __builtin__ namespace </code></pre> <p>Why is it being run in <code>__builtin__</code> namespace in the second case? </p> <p>Furthermore, if I then try to run myfunc from <code>__builtins__</code>, I get an AttributeError. (This is what I would hope happens, but then why is <code>__name__</code> set to <code>__builtin__</code>?)</p> <pre><code>&gt;&gt;&gt; __builtins__.myfunc() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? AttributeError: 'module' object has no attribute 'myfunc' </code></pre> <p>Can anyone explain this behaviour? Thanks</p>
4
2009-04-02T18:42:15Z
714,628
<p>As an aside, I prefer using <code>__import__()</code> over <code>execfile</code>:</p> <pre><code>module = __import__(module_name) value = module.__dict__[function_name](arguments) </code></pre> <p>This also works well when adding to the PYTHONPATH, so that modules in other directories can be imported:</p> <pre><code>sys.path.insert(position, directory) </code></pre>
1
2009-04-03T16:12:05Z
[ "python", "namespaces" ]
Changing element value with BeautifulSoup returns empty element
711,376
<pre><code>from BeautifulSoup import BeautifulStoneSoup xml_data = """ &lt;doc&gt; &lt;test&gt;test&lt;/test&gt; &lt;foo:bar&gt;Hello world!&lt;/foo:bar&gt; &lt;/doc&gt; """ soup = BeautifulStoneSoup(xml_data) print soup.prettify() make = soup.find('foo:bar') print make # prints &lt;foo:bar&gt;Hello world!&lt;/foo:bar&gt; make.contents = ['Top of the world Ma!'] print make # prints &lt;foo:bar&gt;&lt;/foo:bar&gt; </code></pre> <p>How do I change the content of the element, in this case the element in the variable "make", without loosing the content? If you could point me to other pure python modules wich can modify existing xml-documents, please let me know.</p> <p>PS! BeautifulSoup is great for screenscraping and parsing of both HTML and XML!</p>
2
2009-04-02T20:04:38Z
711,405
<p>Check out the <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#Replacing%20one%20Element%20with%20Another">documentation on <code>replaceWith</code></a>. This works:</p> <pre><code>make.contents[0].replaceWith('Top of the world Ma!') </code></pre>
8
2009-04-02T20:09:42Z
[ "python", "xml", "parsing", "beautifulsoup" ]
Changing element value with BeautifulSoup returns empty element
711,376
<pre><code>from BeautifulSoup import BeautifulStoneSoup xml_data = """ &lt;doc&gt; &lt;test&gt;test&lt;/test&gt; &lt;foo:bar&gt;Hello world!&lt;/foo:bar&gt; &lt;/doc&gt; """ soup = BeautifulStoneSoup(xml_data) print soup.prettify() make = soup.find('foo:bar') print make # prints &lt;foo:bar&gt;Hello world!&lt;/foo:bar&gt; make.contents = ['Top of the world Ma!'] print make # prints &lt;foo:bar&gt;&lt;/foo:bar&gt; </code></pre> <p>How do I change the content of the element, in this case the element in the variable "make", without loosing the content? If you could point me to other pure python modules wich can modify existing xml-documents, please let me know.</p> <p>PS! BeautifulSoup is great for screenscraping and parsing of both HTML and XML!</p>
2
2009-04-02T20:04:38Z
29,963,805
<p>Using BeautifulSoup version 4 (<code>bs4</code>), you can achieve the same by <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/#modifying-string" rel="nofollow">updating <code>string</code> property</a> directly :</p> <pre><code>from bs4 import BeautifulSoup xml_data = """ &lt;doc&gt; &lt;test&gt;test&lt;/test&gt; &lt;foo:bar&gt;Hello world!&lt;/foo:bar&gt; &lt;parent&gt;Hello &lt;child&gt;world!&lt;/child&gt;&lt;/parent&gt; &lt;/doc&gt; """ soup = BeautifulSoup(xml_data) make = soup.find('foo:bar') make.string = 'Top of the world Ma!' print make # prints &lt;foo:bar&gt;Top of the world Ma!&lt;/foo:bar&gt; </code></pre> <p>This approach works well for the case when the element contains other elements, and you want to replace the entire content with a new one :</p> <pre><code>parent = soup.find('parent') parent.string = 'Top of the world Ma!' print parent # prints &lt;parent&gt;Top of the world Ma!&lt;/parent&gt; </code></pre> <p><sub>I bumped into this rather old question just now, and the solution provided was not quite suitable for me. Further research leads me to the above approach, and I thought it maybe useful to share what I ended up using here.</sub></p>
1
2015-04-30T09:21:05Z
[ "python", "xml", "parsing", "beautifulsoup" ]
generating plural forms into a .pot file
711,637
<p>I'm internationalizing a python program and cant get plural forms into the .pot file. I have marked string that require plural translations with a _pl() eg.</p> <p><code>self.write_info(_pl("%(num)d track checked", "%(num)d tracks checked", song_obj.song_count) % {"num" : song_obj.song_count})</code></p> <p>Then I'm running: <code>xgettext --language=Python --keyword=_pl --output=output.pot *.py</code> Only the first (singular) string is generated in the pot file.</p>
3
2009-04-02T21:08:35Z
712,033
<p>I haven't used this with Python, and can't test at the moment, but try <code>--keyword=_pl:1,2</code> instead.</p> <p>From the GNU gettext <a href="http://www.gnu.org/software/gettext/manual/gettext.html#xgettext-Invocation" rel="nofollow">docs</a>:</p> <blockquote> <p>--keyword[=keywordspec]’ Additional keyword to be looked for (without keywordspec means not to use default keywords).</p> <p>If keywordspec is a C identifier id, xgettext looks for strings in the first argument of each call to the function or macro id. If keywordspec is of the form ‘id:argnum’, xgettext looks for strings in the argnumth argument of the call. If keywordspec is of the form ‘id:argnum1,argnum2’, xgettext looks for strings in the argnum1st argument and in the argnum2nd argument of the call, and treats them as singular/plural variants for a message with plural handling.</p> </blockquote>
3
2009-04-02T23:32:20Z
[ "python", "internationalization", "xgettext" ]
Python naming conventions for modules
711,884
<p>I have a module whose purpose is to define a class called "nib". (and a few related classes too.) How should I call the module itself? "nib"? "nibmodule"? Anything else?</p>
62
2009-04-02T22:31:35Z
711,892
<p>Just nib. Name the class Nib, with a capital N. For more on naming conventions and other style advice, see <a href="https://www.python.org/dev/peps/pep-0008/#package-and-module-names">PEP 8</a>, the Python style guide.</p>
80
2009-04-02T22:34:41Z
[ "python", "naming-conventions" ]
Python naming conventions for modules
711,884
<p>I have a module whose purpose is to define a class called "nib". (and a few related classes too.) How should I call the module itself? "nib"? "nibmodule"? Anything else?</p>
62
2009-04-02T22:31:35Z
711,908
<p>I would call it nib.py. And I would also name the class Nib.</p> <p>In a larger python project I'm working on, we have lots of modules defining basically one important class. Classes are named beginning with a capital letter. The modules are named like the class in lowercase. This leads to imports like the following:</p> <pre><code>from nib import Nib from foo import Foo from spam.eggs import Eggs, FriedEggs </code></pre> <p>It's a bit like emulating the Java way. One class per file. But with the added flexibility, that you can allways add another class to a single file if it makes sense.</p>
25
2009-04-02T22:40:32Z
[ "python", "naming-conventions" ]
Python naming conventions for modules
711,884
<p>I have a module whose purpose is to define a class called "nib". (and a few related classes too.) How should I call the module itself? "nib"? "nibmodule"? Anything else?</p>
62
2009-04-02T22:31:35Z
711,910
<p>nib is fine. If in doubt, refer to the Python style guide.</p> <p>From <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a>:</p> <blockquote> <p>Package and Module Names Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.</p> <p>Since module names are mapped to file names, and some file systems are case insensitive and truncate long names, it is important that module names be chosen to be fairly short -- this won't be a problem on Unix, but it may be a problem when the code is transported to older Mac or Windows versions, or DOS.</p> <p>When an extension module written in C or C++ has an accompanying Python module that provides a higher level (e.g. more object oriented) interface, the C/C++ module has a leading underscore (e.g. _socket).</p> </blockquote>
19
2009-04-02T22:41:13Z
[ "python", "naming-conventions" ]
Python naming conventions for modules
711,884
<p>I have a module whose purpose is to define a class called "nib". (and a few related classes too.) How should I call the module itself? "nib"? "nibmodule"? Anything else?</p>
62
2009-04-02T22:31:35Z
712,035
<p>I know my solution is not very popular from the pythonic point of view, but I prefer to use the Java approach of one module->one class, with the module named as the class. I do understand the reason behind the python style, but I am not too fond of having a very large file containing a lot of classes. I find it difficult to browse, despite folding.</p> <p>Another reason is version control: having a large file means that your commits tend to concentrate on that file. This can potentially lead to a higher quantity of conflicts to be resolved. You also loose the additional log information that your commit modifies specific files (therefore involving specific classes). Instead you see a modification to the module file, with only the commit comment to understand what modification has been done.</p> <p>Summing up, if you prefer the python philosophy, go for the suggestions of the other posts. If you instead prefer the java-like philosophy, create a Nib.py containing class Nib.</p>
24
2009-04-02T23:33:04Z
[ "python", "naming-conventions" ]
Python naming conventions for modules
711,884
<p>I have a module whose purpose is to define a class called "nib". (and a few related classes too.) How should I call the module itself? "nib"? "nibmodule"? Anything else?</p>
62
2009-04-02T22:31:35Z
32,423,522
<p><strong>foo</strong> module in python would be the equivalent to a <strong>Foo</strong> class file in Java</p> <p>or</p> <p><strong>foobar</strong> module in python would be the equivalent to a <strong>FooBar</strong> class file in Java</p>
0
2015-09-06T12:23:51Z
[ "python", "naming-conventions" ]
List all Tests Found by Nosetest
712,020
<p>I use <code>nosetests</code> to run my unittests and it works well. I want to get a list of all the tests <code>nostests</code> finds without actually running them. Is there a way to do that?</p>
28
2009-04-02T23:27:37Z
716,408
<p>There will be soon: a new --collect switch that produces this behavior was demo'd at PyCon last week. It should be on the trunk "soon" and will be in the 0.11 release.</p> <p>The http://groups.google.com/group/nose-users list is a great resource for nose questions.</p>
3
2009-04-04T02:58:03Z
[ "python", "unit-testing", "nose", "nosetests" ]
List all Tests Found by Nosetest
712,020
<p>I use <code>nosetests</code> to run my unittests and it works well. I want to get a list of all the tests <code>nostests</code> finds without actually running them. Is there a way to do that?</p>
28
2009-04-02T23:27:37Z
1,151,294
<p>Version 0.11.1 is currently available. You can get a list of tests without running them as follows:</p> <pre><code>nosetests -v --collect-only </code></pre>
34
2009-07-20T00:32:07Z
[ "python", "unit-testing", "nose", "nosetests" ]
List all Tests Found by Nosetest
712,020
<p>I use <code>nosetests</code> to run my unittests and it works well. I want to get a list of all the tests <code>nostests</code> finds without actually running them. Is there a way to do that?</p>
28
2009-04-02T23:27:37Z
3,448,487
<p>I recommend using:</p> <pre><code>nosetests -vv --collect-only </code></pre> <p>While the <code>-vv</code> option is not described in <code>man nosetests</code>, <a href="http://ivory.idyll.org/articles/nose-intro.html">"An Extended Introduction to the nose Unit Testing Framework"</a> states that:</p> <blockquote> <p>Using the -vv flag gives you verbose output from nose's test discovery algorithm. This will tell you whether or not nose is even looking in the right place(s) to find your tests.</p> </blockquote> <p>The <code>-vv</code> option can save time when trying to determine why nosetests is only finding some of your tests. (In my case, it was because nosetests skipped certain tests because the <code>.py</code> scripts were executable.)</p> <p>Bottom line is that the <code>-vv</code> option is incredibly handy, and I almost always use it instead of the <code>-v</code> option.</p>
15
2010-08-10T11:37:31Z
[ "python", "unit-testing", "nose", "nosetests" ]
Barchart sizing of text & barwidth with matplotlib - python
712,082
<p>I'm creating a bar chart with matplotlib-0.91 (for the first time) but the y axis labels are being cut off. If I increase the width of the figure enough they eventually show up completely but then the output is not the correct size.</p> <p>Any way to deal with this?</p>
1
2009-04-02T23:54:34Z
713,022
<p>I think I ran into a similar problem.</p> <p>See if this helps adjusting the label's font size:</p> <pre><code>import matplotlib.pyplot as plt import matplotlib.font_manager as fm fontsize2use = 10 fig = plt.figure(figsize=(10,5)) plt.xticks(fontsize=fontsize2use) plt.yticks(fontsize=fontsize2use) fontprop = fm.FontProperties(size=fontsize2use) ax = fig.add_subplot(111) ax.set_xlabel('XaxisLabel') ax.set_ylabel('YaxisLabel') . &lt;main plotting code&gt; . ax.legend(loc=0, prop=fontprop) </code></pre> <p>For the bar width, if your using <a href="http://matplotlib.sourceforge.net/api/pyplot%5Fapi.html?#matplotlib.pyplot.bar" rel="nofollow">pyplot.bar</a> it looks like you can play with the width attribute.</p>
3
2009-04-03T08:23:48Z
[ "python", "matplotlib" ]
Barchart sizing of text & barwidth with matplotlib - python
712,082
<p>I'm creating a bar chart with matplotlib-0.91 (for the first time) but the y axis labels are being cut off. If I increase the width of the figure enough they eventually show up completely but then the output is not the correct size.</p> <p>Any way to deal with this?</p>
1
2009-04-02T23:54:34Z
715,916
<p>Take a look at <a href="http://matplotlib.sourceforge.net/api/pyplot%5Fapi.html#matplotlib.pyplot.subplots%5Fadjust" rel="nofollow"><code>subplots_adjust</code></a>, or just use <a href="http://matplotlib.sourceforge.net/api/pyplot%5Fapi.html#matplotlib.pyplot.axes" rel="nofollow"><code>axes</code></a><code>([left,bottom,width,height])</code>.</p>
0
2009-04-03T22:07:00Z
[ "python", "matplotlib" ]
Is there a good python module that does HTML encoding/escaping in C?
712,113
<p>There is cgi.escape but that appears to be implemented in pure python. It seems like most frameworks like Django also just run some regular expressions. This is something we do a lot, so it would be good to have it be as fast as possible.</p> <p>Maybe C implementations wouldn't be much faster than a series of regexes for this?</p>
0
2009-04-03T00:14:23Z
712,154
<p>See <A HREF="http://codespeak.net/lxml/" rel="nofollow">lxml</A>, which is based on <A HREF="http://xmlsoft.org/" rel="nofollow">libxml2</A>. While it's primarily a XML library, <A HREF="http://codespeak.net/lxml/parsing.html#parsing-html" rel="nofollow">HTML support is available</A>.</p>
0
2009-04-03T00:34:50Z
[ "python", "escaping", "python-module" ]
Going nuts with executing python script via crontab on debian!
712,124
<p>This is what my crontab file looks like:</p> <pre><code>* * * * * root /usr/bin/python /root/test.py &gt;&gt; /root/classwatch.log 2&gt;&amp;1 </code></pre> <p>This is what my python script looks like:</p> <pre><code>#!/usr/bin/python print "hello" </code></pre> <p>The cronjob creates the log file. But it is empty. I am also pretty certain that the python file is not being executed.</p> <p>Appreciate any help! I've been playing with it for past 4 hrs with no luck.</p>
5
2009-04-03T00:18:21Z
712,143
<p>Updated...</p> <p>Replace the contents with</p> <pre><code>* * * * * date &gt;&gt; /tmp/foo </code></pre> <p>Does this <a href="http://209.85.173.132/search?q=cache:JZMjUwxr%5F8AJ:ubuntuforums.org/showthread.php%3Ft%3D847446%2Bdebian%2Bcron%2Bmissing%2Boutput&amp;cd=8&amp;hl=en&amp;ct=clnk&amp;gl=us" rel="nofollow">link</a> help?</p> <p>Delete the file it is supposed to create. Does it come back? I thought each user had his own crontab file so the user on the line is suspsect.<br /> DId someone play a joke on you and replace the python binary with a no op?</p> <p>I have to think cron isn't working right since the echo doesn't work. Did you make sure to change the output directory to /tmp with the echo?</p> <p>can you do an od (octal dump) of the file and see if maybe you put a control character or a tab into the cron file?</p>
1
2009-04-03T00:29:27Z
[ "python", "debian", "cron", "crontab" ]
Going nuts with executing python script via crontab on debian!
712,124
<p>This is what my crontab file looks like:</p> <pre><code>* * * * * root /usr/bin/python /root/test.py &gt;&gt; /root/classwatch.log 2&gt;&amp;1 </code></pre> <p>This is what my python script looks like:</p> <pre><code>#!/usr/bin/python print "hello" </code></pre> <p>The cronjob creates the log file. But it is empty. I am also pretty certain that the python file is not being executed.</p> <p>Appreciate any help! I've been playing with it for past 4 hrs with no luck.</p>
5
2009-04-03T00:18:21Z
712,157
<p>Have you tried putting the script someplace else (e.g. /usr/local/bin/)?</p>
0
2009-04-03T00:36:33Z
[ "python", "debian", "cron", "crontab" ]
Going nuts with executing python script via crontab on debian!
712,124
<p>This is what my crontab file looks like:</p> <pre><code>* * * * * root /usr/bin/python /root/test.py &gt;&gt; /root/classwatch.log 2&gt;&amp;1 </code></pre> <p>This is what my python script looks like:</p> <pre><code>#!/usr/bin/python print "hello" </code></pre> <p>The cronjob creates the log file. But it is empty. I am also pretty certain that the python file is not being executed.</p> <p>Appreciate any help! I've been playing with it for past 4 hrs with no luck.</p>
5
2009-04-03T00:18:21Z
712,180
<p>This works fine for me on my RHES 4 Linux box exactly as shown (NOTE: I removed the 'root' username in the crontab).</p> <p>I suspect there's something wrong with the way you're installing your cron job, or the configuration of cron on your system. How are you installing this? Are you using <code>crontab -e</code> or some other method? Are you able to run any other cron jobs for root successfully?</p>
0
2009-04-03T00:47:55Z
[ "python", "debian", "cron", "crontab" ]
Going nuts with executing python script via crontab on debian!
712,124
<p>This is what my crontab file looks like:</p> <pre><code>* * * * * root /usr/bin/python /root/test.py &gt;&gt; /root/classwatch.log 2&gt;&amp;1 </code></pre> <p>This is what my python script looks like:</p> <pre><code>#!/usr/bin/python print "hello" </code></pre> <p>The cronjob creates the log file. But it is empty. I am also pretty certain that the python file is not being executed.</p> <p>Appreciate any help! I've been playing with it for past 4 hrs with no luck.</p>
5
2009-04-03T00:18:21Z
712,234
<p>It might be because of a job declared earlier failing due to syntax error. Can you paste your entire crontab? Your line looks good as far as I can see.</p>
0
2009-04-03T01:20:37Z
[ "python", "debian", "cron", "crontab" ]
Going nuts with executing python script via crontab on debian!
712,124
<p>This is what my crontab file looks like:</p> <pre><code>* * * * * root /usr/bin/python /root/test.py &gt;&gt; /root/classwatch.log 2&gt;&amp;1 </code></pre> <p>This is what my python script looks like:</p> <pre><code>#!/usr/bin/python print "hello" </code></pre> <p>The cronjob creates the log file. But it is empty. I am also pretty certain that the python file is not being executed.</p> <p>Appreciate any help! I've been playing with it for past 4 hrs with no luck.</p>
5
2009-04-03T00:18:21Z
712,291
<p>The crontab entry is correct if you're editing /etc/crontab - however if you're using your normal user's crontab (i.e. crontab -e, crontab crontabfle, etc) the root entry is syntactically incorrect.</p>
0
2009-04-03T01:51:30Z
[ "python", "debian", "cron", "crontab" ]
Going nuts with executing python script via crontab on debian!
712,124
<p>This is what my crontab file looks like:</p> <pre><code>* * * * * root /usr/bin/python /root/test.py &gt;&gt; /root/classwatch.log 2&gt;&amp;1 </code></pre> <p>This is what my python script looks like:</p> <pre><code>#!/usr/bin/python print "hello" </code></pre> <p>The cronjob creates the log file. But it is empty. I am also pretty certain that the python file is not being executed.</p> <p>Appreciate any help! I've been playing with it for past 4 hrs with no luck.</p>
5
2009-04-03T00:18:21Z
712,302
<p>Try just sending stdout to the log file, instead of both stderr and stout:<br> /usr/bin/python /root/test.py > /root/classwatch.log </p>
0
2009-04-03T01:58:46Z
[ "python", "debian", "cron", "crontab" ]
Going nuts with executing python script via crontab on debian!
712,124
<p>This is what my crontab file looks like:</p> <pre><code>* * * * * root /usr/bin/python /root/test.py &gt;&gt; /root/classwatch.log 2&gt;&amp;1 </code></pre> <p>This is what my python script looks like:</p> <pre><code>#!/usr/bin/python print "hello" </code></pre> <p>The cronjob creates the log file. But it is empty. I am also pretty certain that the python file is not being executed.</p> <p>Appreciate any help! I've been playing with it for past 4 hrs with no luck.</p>
5
2009-04-03T00:18:21Z
712,790
<p>There are two ways to create a crontab -- per user or globally. For the global crontab (/etc/crontab) you specify the user, as per:</p> <pre><code># m h dom mon dow user command 17 * * * * root cd / &amp;&amp; run-parts --report /etc/cron.hourly </code></pre> <p>For user crontabs you don't, as per:</p> <pre><code>aj@wherever:~$ crontab -l 0 * * * * /home/aj/bin/update-foobar </code></pre> <p>To get a python script running via #! notation, you just make the script executable (chmod 755 /root/test.py), and invoke it directly, something like:</p> <pre><code>/root/test.py </code></pre> <p>If you don't want to do that, you can run it via the python interpretor by hand, like:</p> <pre><code>/usr/bin/python /root/test.py </code></pre> <p>This assumes whichever user you're running as (ie the user in /etc/crontab, or the user you're running crontab -e as) has permission to see the python script -- /root might be inaccessible to regular users, eg.</p> <p>You can get a good idea of whether your script is being executed at all by adding:</p> <pre><code>import time time.sleep(20) # pause for 20 seconds </code></pre> <p>and then checking with "top" or "ps aux" or "pstree" to see if python's actually running.</p>
4
2009-04-03T06:56:02Z
[ "python", "debian", "cron", "crontab" ]
Going nuts with executing python script via crontab on debian!
712,124
<p>This is what my crontab file looks like:</p> <pre><code>* * * * * root /usr/bin/python /root/test.py &gt;&gt; /root/classwatch.log 2&gt;&amp;1 </code></pre> <p>This is what my python script looks like:</p> <pre><code>#!/usr/bin/python print "hello" </code></pre> <p>The cronjob creates the log file. But it is empty. I am also pretty certain that the python file is not being executed.</p> <p>Appreciate any help! I've been playing with it for past 4 hrs with no luck.</p>
5
2009-04-03T00:18:21Z
7,432,077
<pre><code>chmod 755 /root/test.py </code></pre> <p>and then</p> <pre><code>* * * * * /root/test.py &gt;&gt; /root/classwatch.log 2&gt;&amp;1 </code></pre> <p>should work.</p>
1
2011-09-15T13:58:21Z
[ "python", "debian", "cron", "crontab" ]
How to work around needing to update a dictionary
712,225
<p>I need to delete a k/v pair from a dictionary in a loop. After getting <code>RuntimeError: dictionary changed size during iteration</code> I pickled the dictionary after deleting the k/v and in one of the outer loops I try to reopen the newly pickled/updated dictionary. However, as many of you will probably know-I get the same error-I think when it reaches the top of the loop. I do not use my dictionary in the outermost loop. </p> <p>So my question is-does anyone know how to get around this problem? I want to delete a k/V pair from a dictionary and use that resized dictionary on the next iteration of the loop.</p> <p>to focus the problem and use the solution from Cygil</p> <pre><code>list=[27,29,23,30,3,5,40] testDict={} for x in range(25): tempDict={} tempDict['xsquared']=x*x tempDict['xinverse']=1.0/(x+1.0) testDict[(x,x+1)]=tempDict for item in list: print 'the Dictionary now has',len(testDict.keys()), ' keys' for key in testDict.keys(): if key[0]==item: del testDict[key] </code></pre> <p>I am doing this because I have to have some research assistants compare some observations from two data sets that could not be matched because of name variants. The idea is to throw up a name from one data set (say set A) and then based on a key match find all the names attached to that key in the other dataset (set B). One a match has been identified I don't want to show the value from B again to speed things up for them. Because there are 6,000 observations I also don't want them to have to start at the beginning of A each time they get back to work. However, I can fix that by letting them chose to enter the last key from A they worked with. But I really need to reduce B once the match has been identified </p>
3
2009-04-03T01:14:28Z
712,240
<p>Delete all keys whose value is > 15:</p> <pre><code>for k in mydict.keys(): # makes a list of the keys and iterate # over the list, not over the dict. if mydict[k] &gt; 15: del mydict[k] </code></pre>
4
2009-04-03T01:23:22Z
[ "python", "dictionary", "runtime-error" ]
How to work around needing to update a dictionary
712,225
<p>I need to delete a k/v pair from a dictionary in a loop. After getting <code>RuntimeError: dictionary changed size during iteration</code> I pickled the dictionary after deleting the k/v and in one of the outer loops I try to reopen the newly pickled/updated dictionary. However, as many of you will probably know-I get the same error-I think when it reaches the top of the loop. I do not use my dictionary in the outermost loop. </p> <p>So my question is-does anyone know how to get around this problem? I want to delete a k/V pair from a dictionary and use that resized dictionary on the next iteration of the loop.</p> <p>to focus the problem and use the solution from Cygil</p> <pre><code>list=[27,29,23,30,3,5,40] testDict={} for x in range(25): tempDict={} tempDict['xsquared']=x*x tempDict['xinverse']=1.0/(x+1.0) testDict[(x,x+1)]=tempDict for item in list: print 'the Dictionary now has',len(testDict.keys()), ' keys' for key in testDict.keys(): if key[0]==item: del testDict[key] </code></pre> <p>I am doing this because I have to have some research assistants compare some observations from two data sets that could not be matched because of name variants. The idea is to throw up a name from one data set (say set A) and then based on a key match find all the names attached to that key in the other dataset (set B). One a match has been identified I don't want to show the value from B again to speed things up for them. Because there are 6,000 observations I also don't want them to have to start at the beginning of A each time they get back to work. However, I can fix that by letting them chose to enter the last key from A they worked with. But I really need to reduce B once the match has been identified </p>
3
2009-04-03T01:14:28Z
712,252
<p>Without code, I'm assuming you're writing something like:</p> <pre><code>for key in dict: if check_condition(dict[key]): del dict[key] </code></pre> <p>If so, you can write</p> <pre><code>for key in list(dict.keys()): if key in dict and check_condition(dict[key]): del dict[key] </code></pre> <p><code>list(dict.keys())</code> returns a copy of the keys, not a view, which makes it possible to delete from the dictionary (you are iterating through a copy of the keys, not the keys in the dictionary itself, in this case.)</p>
6
2009-04-03T01:28:50Z
[ "python", "dictionary", "runtime-error" ]
How to work around needing to update a dictionary
712,225
<p>I need to delete a k/v pair from a dictionary in a loop. After getting <code>RuntimeError: dictionary changed size during iteration</code> I pickled the dictionary after deleting the k/v and in one of the outer loops I try to reopen the newly pickled/updated dictionary. However, as many of you will probably know-I get the same error-I think when it reaches the top of the loop. I do not use my dictionary in the outermost loop. </p> <p>So my question is-does anyone know how to get around this problem? I want to delete a k/V pair from a dictionary and use that resized dictionary on the next iteration of the loop.</p> <p>to focus the problem and use the solution from Cygil</p> <pre><code>list=[27,29,23,30,3,5,40] testDict={} for x in range(25): tempDict={} tempDict['xsquared']=x*x tempDict['xinverse']=1.0/(x+1.0) testDict[(x,x+1)]=tempDict for item in list: print 'the Dictionary now has',len(testDict.keys()), ' keys' for key in testDict.keys(): if key[0]==item: del testDict[key] </code></pre> <p>I am doing this because I have to have some research assistants compare some observations from two data sets that could not be matched because of name variants. The idea is to throw up a name from one data set (say set A) and then based on a key match find all the names attached to that key in the other dataset (set B). One a match has been identified I don't want to show the value from B again to speed things up for them. Because there are 6,000 observations I also don't want them to have to start at the beginning of A each time they get back to work. However, I can fix that by letting them chose to enter the last key from A they worked with. But I really need to reduce B once the match has been identified </p>
3
2009-04-03T01:14:28Z
712,325
<p>Change:</p> <pre><code>for ansSeries in notmatched: </code></pre> <p>To:</p> <pre><code>for ansSeries in notmatched.copy(): </code></pre>
1
2009-04-03T02:10:49Z
[ "python", "dictionary", "runtime-error" ]
Is it possible to get a timezone in Python given a UTC timestamp and a UTC offset?
712,322
<p>I have data that is the UTC offset and the UTC time. Given that, is it possible in Python to get the user's local timezone (mainly to figure if it is DST etc. probably using pytz), similar to the function in PHP <code>timezone_name_from_abbr</code>?</p> <p>For example:</p> <p>If my epoch time is 1238720309, I can get the UTC time as:</p> <pre><code>&gt;&gt;&gt; d = datetime.utcfromtimestamp(1238720309) &gt;&gt;&gt; print d + dt.timedelta(0,-28800) #offset for pacific I think 2009-04-02 17:04:41.712143 </code></pre> <p>This is correct except it is PDT right now, so it should be:</p> <pre><code>2009-04-02 18:04:41.712413 </code></pre> <p>I need to get the timezone to use in pytz to figure out if it is daylight saving, I think?</p>
3
2009-04-03T02:09:12Z
712,329
<p>Since, in general, there is more than one possible time zone for a given time zone offset, the general answer is "No, not without more information". The more information is typically the location to which the time applies - which country, or state, or city.</p>
5
2009-04-03T02:14:04Z
[ "python", "timezone", "utc", "dst", "pytz" ]
Is it possible to get a timezone in Python given a UTC timestamp and a UTC offset?
712,322
<p>I have data that is the UTC offset and the UTC time. Given that, is it possible in Python to get the user's local timezone (mainly to figure if it is DST etc. probably using pytz), similar to the function in PHP <code>timezone_name_from_abbr</code>?</p> <p>For example:</p> <p>If my epoch time is 1238720309, I can get the UTC time as:</p> <pre><code>&gt;&gt;&gt; d = datetime.utcfromtimestamp(1238720309) &gt;&gt;&gt; print d + dt.timedelta(0,-28800) #offset for pacific I think 2009-04-02 17:04:41.712143 </code></pre> <p>This is correct except it is PDT right now, so it should be:</p> <pre><code>2009-04-02 18:04:41.712413 </code></pre> <p>I need to get the timezone to use in pytz to figure out if it is daylight saving, I think?</p>
3
2009-04-03T02:09:12Z
712,373
<p>No. <a href="http://en.wikipedia.org/wiki/List_of_U.S._states_by_time_zone" rel="nofollow">http://en.wikipedia.org/wiki/List_of_U.S._states_by_time_zone</a></p>
0
2009-04-03T02:39:00Z
[ "python", "timezone", "utc", "dst", "pytz" ]
Is it possible to get a timezone in Python given a UTC timestamp and a UTC offset?
712,322
<p>I have data that is the UTC offset and the UTC time. Given that, is it possible in Python to get the user's local timezone (mainly to figure if it is DST etc. probably using pytz), similar to the function in PHP <code>timezone_name_from_abbr</code>?</p> <p>For example:</p> <p>If my epoch time is 1238720309, I can get the UTC time as:</p> <pre><code>&gt;&gt;&gt; d = datetime.utcfromtimestamp(1238720309) &gt;&gt;&gt; print d + dt.timedelta(0,-28800) #offset for pacific I think 2009-04-02 17:04:41.712143 </code></pre> <p>This is correct except it is PDT right now, so it should be:</p> <pre><code>2009-04-02 18:04:41.712413 </code></pre> <p>I need to get the timezone to use in pytz to figure out if it is daylight saving, I think?</p>
3
2009-04-03T02:09:12Z
712,475
<p>No. Time zones are too complicated and there are too many that are X hours from UTC.</p> <p><a href="http://en.wikipedia.org/wiki/List_of_time_zones" rel="nofollow">http://en.wikipedia.org/wiki/List_of_time_zones</a></p> <p>For example, -5 from UTC could be Canada, New York, Cuba, Jamaica, Ecuador, etc.</p> <p>The equator zones probably don't use DST since their day is roughly 12 hours year long. The south american ones, if they use some form of DST are probably on the opposite schedule of the north american ones because their summer/winter (i.e. short days/long days) schedules are also opposite.</p>
1
2009-04-03T03:40:29Z
[ "python", "timezone", "utc", "dst", "pytz" ]
Interpreting Number Ranges in Python
712,460
<p>In a Pylons webapp, I need to take a string such as "&lt;3, 45, 46, 48-51, 77" and create a list of ints (which are actually IDs of objects) to search on. </p> <p>Any suggestions on ways to do this? I'm new to Python, and I haven't found anything out there that helps with this kind of thing.</p> <p>The list would be: [1, 2, 3, 45, 46, 48, 49, 50, 51, 77]</p>
4
2009-04-03T03:33:41Z
712,483
<p>Use parseIntSet from <a href="http://thoughtsbyclayg.blogspot.com/2008/10/parsing-list-of-numbers-in-python.html">here</a></p> <p>I also like the pyparsing implementation in the comments at the end.</p> <p>The parseIntSet has been modified here to handle "&lt;3"-type entries and to only spit out the invalid strings if there are any.</p> <pre><code>#! /usr/local/bin/python import sys import os # return a set of selected values when a string in the form: # 1-4,6 # would return: # 1,2,3,4,6 # as expected... def parseIntSet(nputstr=""): selection = set() invalid = set() # tokens are comma seperated values tokens = [x.strip() for x in nputstr.split(',')] for i in tokens: if len(i) &gt; 0: if i[:1] == "&lt;": i = "1-%s"%(i[1:]) try: # typically tokens are plain old integers selection.add(int(i)) except: # if not, then it might be a range try: token = [int(k.strip()) for k in i.split('-')] if len(token) &gt; 1: token.sort() # we have items seperated by a dash # try to build a valid range first = token[0] last = token[len(token)-1] for x in range(first, last+1): selection.add(x) except: # not an int and not a range... invalid.add(i) # Report invalid tokens before returning valid selection if len(invalid) &gt; 0: print "Invalid set: " + str(invalid) return selection # end parseIntSet print 'Generate a list of selected items!' nputstr = raw_input('Enter a list of items: ') selection = parseIntSet(nputstr) print 'Your selection is: ' print str(selection) </code></pre> <p>And here's the output from the sample run:</p> <pre><code>$ python qq.py Generate a list of selected items! Enter a list of items: &lt;3, 45, 46, 48-51, 77 Your selection is: set([1, 2, 3, 45, 46, 77, 48, 49, 50, 51]) </code></pre>
11
2009-04-03T03:42:56Z
[ "python", "numeric-ranges" ]
Interpreting Number Ranges in Python
712,460
<p>In a Pylons webapp, I need to take a string such as "&lt;3, 45, 46, 48-51, 77" and create a list of ints (which are actually IDs of objects) to search on. </p> <p>Any suggestions on ways to do this? I'm new to Python, and I haven't found anything out there that helps with this kind of thing.</p> <p>The list would be: [1, 2, 3, 45, 46, 48, 49, 50, 51, 77]</p>
4
2009-04-03T03:33:41Z
712,486
<p>First, you'll need to figure out what kind of syntax you'll accept. You current have three in your example: </p> <ol> <li><p>Single number: 45, 46</p></li> <li><p>Less than operator </p></li> <li><p>Dash ranging: 48-51</p></li> </ol> <p>After that, it's just a matter of splitting the string into tokens, and checking the format of the token.</p>
0
2009-04-03T03:45:14Z
[ "python", "numeric-ranges" ]
Interpreting Number Ranges in Python
712,460
<p>In a Pylons webapp, I need to take a string such as "&lt;3, 45, 46, 48-51, 77" and create a list of ints (which are actually IDs of objects) to search on. </p> <p>Any suggestions on ways to do this? I'm new to Python, and I haven't found anything out there that helps with this kind of thing.</p> <p>The list would be: [1, 2, 3, 45, 46, 48, 49, 50, 51, 77]</p>
4
2009-04-03T03:33:41Z
712,500
<pre><code>&gt;&gt;&gt; print range.__doc__ range([start,] stop[, step]) -&gt; list of integers </code></pre> <p>Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements.</p> <pre><code>&gt;&gt;&gt; range(33,44) [33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43] &gt;&gt;&gt; range(1,3) [1, 2] </code></pre> <p>I imagine you could iterate your list, and call range appropriately.</p> <pre><code>&gt;&gt;&gt; def lessThan(n) : ... return range(n+1) ... &gt;&gt;&gt; lessThan(4) [0, 1, 2, 3, 4] &gt;&gt;&gt; def toFrom(n,m): ... return range(n,m) ... &gt;&gt;&gt; toFrom(33,44) [33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43] </code></pre> <p>Then split the string on commas, and for each bit, parse it enough to figure out what function to call, catenating the lists returned.</p> <p>Anything more and I'd have written it for you.</p>
0
2009-04-03T03:56:23Z
[ "python", "numeric-ranges" ]
Interpreting Number Ranges in Python
712,460
<p>In a Pylons webapp, I need to take a string such as "&lt;3, 45, 46, 48-51, 77" and create a list of ints (which are actually IDs of objects) to search on. </p> <p>Any suggestions on ways to do this? I'm new to Python, and I haven't found anything out there that helps with this kind of thing.</p> <p>The list would be: [1, 2, 3, 45, 46, 48, 49, 50, 51, 77]</p>
4
2009-04-03T03:33:41Z
713,024
<pre><code>rng = "&lt;3, 45, 46, 48-51, 77" ids = [] for x in map(str.strip,rng.split(',')): if x.isdigit(): ids.append(int(x)) continue if x[0] == '&lt;': ids.extend(range(1,int(x[1:])+1)) continue if '-' in x: xr = map(str.strip,x.split('-')) ids.extend(range(int(xr[0]),int(xr[1])+1)) continue else: raise Exception, 'unknown range type: "%s"'%x </code></pre>
1
2009-04-03T08:24:17Z
[ "python", "numeric-ranges" ]
Interpreting Number Ranges in Python
712,460
<p>In a Pylons webapp, I need to take a string such as "&lt;3, 45, 46, 48-51, 77" and create a list of ints (which are actually IDs of objects) to search on. </p> <p>Any suggestions on ways to do this? I'm new to Python, and I haven't found anything out there that helps with this kind of thing.</p> <p>The list would be: [1, 2, 3, 45, 46, 48, 49, 50, 51, 77]</p>
4
2009-04-03T03:33:41Z
713,040
<p>I also had to do something similar for an app lately.</p> <p>If you don't need concrete numbers but just a way to see whether a given number is in the range, you might consider parsing it to a Python expression you can eval into a lambda. For example <code>&lt;3, 5-10, 12</code> could be <code>func=(lambda x:x&lt;3 or (5 &lt;= x &lt;= 10) or x==12))</code>. Then you can just call the lambda, <code>func(11)</code> to see if 11 belongs in there.</p>
0
2009-04-03T08:34:30Z
[ "python", "numeric-ranges" ]
Using CSV as a mutable database?
712,510
<p>Yes, this is as stupid a situation as it sounds like. Due to some extremely annoying hosting restrictions and unresponsive tech support, I have to use a CSV file as a database. </p> <p>While I can use MySQL with PHP, I can't use it with the Python backend of my program because of install issues with the host. I can't use SQLite with PHP because of more install issues, but can use it as it's a Python builtin.</p> <p>Anyways, now, the question: is it possible to update values SQL-style in a CSV database? Or should I keep on calling the help desk?</p>
4
2009-04-03T04:02:50Z
712,512
<p>I'd keep calling help desk. You <strong>don't</strong> want to use CSV for data if it's relational at all. It's going to be nightmare. </p>
0
2009-04-03T04:06:31Z
[ "python", "csv" ]
Using CSV as a mutable database?
712,510
<p>Yes, this is as stupid a situation as it sounds like. Due to some extremely annoying hosting restrictions and unresponsive tech support, I have to use a CSV file as a database. </p> <p>While I can use MySQL with PHP, I can't use it with the Python backend of my program because of install issues with the host. I can't use SQLite with PHP because of more install issues, but can use it as it's a Python builtin.</p> <p>Anyways, now, the question: is it possible to update values SQL-style in a CSV database? Or should I keep on calling the help desk?</p>
4
2009-04-03T04:02:50Z
712,515
<p>Keep calling on the help desk.</p> <p>While you can use a CSV as a database, it's generally a bad idea. You would have to implement you own locking, searching, updating, and be very careful with how you write it out to make sure that it isn't erased in case of a power outage or other abnormal shutdown. There will be no transactions, no query language unless you write your own, etc.</p>
1
2009-04-03T04:07:01Z
[ "python", "csv" ]
Using CSV as a mutable database?
712,510
<p>Yes, this is as stupid a situation as it sounds like. Due to some extremely annoying hosting restrictions and unresponsive tech support, I have to use a CSV file as a database. </p> <p>While I can use MySQL with PHP, I can't use it with the Python backend of my program because of install issues with the host. I can't use SQLite with PHP because of more install issues, but can use it as it's a Python builtin.</p> <p>Anyways, now, the question: is it possible to update values SQL-style in a CSV database? Or should I keep on calling the help desk?</p>
4
2009-04-03T04:02:50Z
712,521
<p><strong>Don't walk, run to get a new host immediately</strong>. If your host won't even get you the most basic of free databases, it's time for a change. There are many fish in the sea.</p> <p>At the very least I'd recommend an xml data store rather than a csv. <a href="http://chrisballance.com" rel="nofollow">My blog</a> uses an xml data provider and I haven't had any issues with performance at all.</p>
15
2009-04-03T04:11:14Z
[ "python", "csv" ]
Using CSV as a mutable database?
712,510
<p>Yes, this is as stupid a situation as it sounds like. Due to some extremely annoying hosting restrictions and unresponsive tech support, I have to use a CSV file as a database. </p> <p>While I can use MySQL with PHP, I can't use it with the Python backend of my program because of install issues with the host. I can't use SQLite with PHP because of more install issues, but can use it as it's a Python builtin.</p> <p>Anyways, now, the question: is it possible to update values SQL-style in a CSV database? Or should I keep on calling the help desk?</p>
4
2009-04-03T04:02:50Z
712,522
<p>I couldn't imagine this ever being a good idea. The current mess I've inherited writes vital billing information to CSV and updates it after projects are complete. It runs horribly and thousands of dollars are missed a month. For the current restrictions that you have, I'd consider finding better hosting.</p>
1
2009-04-03T04:12:56Z
[ "python", "csv" ]
Using CSV as a mutable database?
712,510
<p>Yes, this is as stupid a situation as it sounds like. Due to some extremely annoying hosting restrictions and unresponsive tech support, I have to use a CSV file as a database. </p> <p>While I can use MySQL with PHP, I can't use it with the Python backend of my program because of install issues with the host. I can't use SQLite with PHP because of more install issues, but can use it as it's a Python builtin.</p> <p>Anyways, now, the question: is it possible to update values SQL-style in a CSV database? Or should I keep on calling the help desk?</p>
4
2009-04-03T04:02:50Z
712,565
<p>Take a look at this: <a href="http://www.netpromi.com/kirbybase_python.html" rel="nofollow">http://www.netpromi.com/kirbybase_python.html</a></p>
3
2009-04-03T04:37:43Z
[ "python", "csv" ]
Using CSV as a mutable database?
712,510
<p>Yes, this is as stupid a situation as it sounds like. Due to some extremely annoying hosting restrictions and unresponsive tech support, I have to use a CSV file as a database. </p> <p>While I can use MySQL with PHP, I can't use it with the Python backend of my program because of install issues with the host. I can't use SQLite with PHP because of more install issues, but can use it as it's a Python builtin.</p> <p>Anyways, now, the question: is it possible to update values SQL-style in a CSV database? Or should I keep on calling the help desk?</p>
4
2009-04-03T04:02:50Z
712,567
<p>I agree. Tell them that 5 random strangers agree that you being forced into a corner to use CSV is absurd and unacceptable.</p>
0
2009-04-03T04:39:41Z
[ "python", "csv" ]
Using CSV as a mutable database?
712,510
<p>Yes, this is as stupid a situation as it sounds like. Due to some extremely annoying hosting restrictions and unresponsive tech support, I have to use a CSV file as a database. </p> <p>While I can use MySQL with PHP, I can't use it with the Python backend of my program because of install issues with the host. I can't use SQLite with PHP because of more install issues, but can use it as it's a Python builtin.</p> <p>Anyways, now, the question: is it possible to update values SQL-style in a CSV database? Or should I keep on calling the help desk?</p>
4
2009-04-03T04:02:50Z
712,568
<p>You can probably used sqlite3 for more real database. It's hard to imagine hosting that won't allow you to install it as a python module.</p> <p>Don't even think of using CSV, your data will be corrupted and lost faster than you say "s#&amp;t"</p>
1
2009-04-03T04:40:30Z
[ "python", "csv" ]
Using CSV as a mutable database?
712,510
<p>Yes, this is as stupid a situation as it sounds like. Due to some extremely annoying hosting restrictions and unresponsive tech support, I have to use a CSV file as a database. </p> <p>While I can use MySQL with PHP, I can't use it with the Python backend of my program because of install issues with the host. I can't use SQLite with PHP because of more install issues, but can use it as it's a Python builtin.</p> <p>Anyways, now, the question: is it possible to update values SQL-style in a CSV database? Or should I keep on calling the help desk?</p>
4
2009-04-03T04:02:50Z
712,974
<p>If I understand you correctly: you need to access the same database from both python and php, and you're screwed because you can only use mysql from php, and only sqlite from python?</p> <p>Could you further explain this? Maybe you could use xml-rpc or plain http requests with xml/json/... to get the php program to communicate with the python program (or the other way around?), so that only one of them directly accesses the db.</p> <p>If this is not the case, I'm not really sure what the problem.</p>
0
2009-04-03T08:05:53Z
[ "python", "csv" ]
Using CSV as a mutable database?
712,510
<p>Yes, this is as stupid a situation as it sounds like. Due to some extremely annoying hosting restrictions and unresponsive tech support, I have to use a CSV file as a database. </p> <p>While I can use MySQL with PHP, I can't use it with the Python backend of my program because of install issues with the host. I can't use SQLite with PHP because of more install issues, but can use it as it's a Python builtin.</p> <p>Anyways, now, the question: is it possible to update values SQL-style in a CSV database? Or should I keep on calling the help desk?</p>
4
2009-04-03T04:02:50Z
713,396
<p><strong>"Anyways, now, the question: is it possible to update values SQL-style in a CSV database?"</strong></p> <p>Technically, it's possible. However, it can be hard.</p> <p>If both PHP and Python are writing the file, you'll need to use OS-level locking to assure that they don't overwrite each other. Each part of your system will have to lock the file, <strong>rewrite it from scratch with all the updates</strong>, and unlock the file.</p> <p>This means that PHP and Python must load the entire file into memory before rewriting it.</p> <p>There are a couple of ways to handle the OS locking.</p> <ol> <li><p>Use the same file and actually use some OS lock module. Both processes have the file open at all times.</p></li> <li><p>Write to a temp file and do a rename. This means each program must open and read the file for each transaction. Very safe and reliable. A little slow.</p></li> </ol> <p>Or.</p> <p>You can rearchitect it so that only Python writes the file. The front-end reads the file when it changes, and drops off little transaction files to create a work queue for Python. In this case, you don't have multiple writers -- you have one reader and one writer -- and life is much, much simpler.</p>
1
2009-04-03T10:26:04Z
[ "python", "csv" ]
Using CSV as a mutable database?
712,510
<p>Yes, this is as stupid a situation as it sounds like. Due to some extremely annoying hosting restrictions and unresponsive tech support, I have to use a CSV file as a database. </p> <p>While I can use MySQL with PHP, I can't use it with the Python backend of my program because of install issues with the host. I can't use SQLite with PHP because of more install issues, but can use it as it's a Python builtin.</p> <p>Anyways, now, the question: is it possible to update values SQL-style in a CSV database? Or should I keep on calling the help desk?</p>
4
2009-04-03T04:02:50Z
713,425
<p>It's technically possible. For example, Perl has <a href="http://search.cpan.org/~jzucker/DBD-CSV/lib/DBD/CSV.pm" rel="nofollow">DBD::CSV</a> that provides a driver that runs SQL queries on the CSV file.</p> <p><em>That being said</em>, why not run off a SQLite database on your server?</p>
0
2009-04-03T10:39:52Z
[ "python", "csv" ]
Using CSV as a mutable database?
712,510
<p>Yes, this is as stupid a situation as it sounds like. Due to some extremely annoying hosting restrictions and unresponsive tech support, I have to use a CSV file as a database. </p> <p>While I can use MySQL with PHP, I can't use it with the Python backend of my program because of install issues with the host. I can't use SQLite with PHP because of more install issues, but can use it as it's a Python builtin.</p> <p>Anyways, now, the question: is it possible to update values SQL-style in a CSV database? Or should I keep on calling the help desk?</p>
4
2009-04-03T04:02:50Z
713,531
<p>What about postgresql? I've found that quite nice to work with, and python supports it well.</p> <p>But I really would look for another provider unless it's really not an option.</p>
0
2009-04-03T11:15:46Z
[ "python", "csv" ]
Using CSV as a mutable database?
712,510
<p>Yes, this is as stupid a situation as it sounds like. Due to some extremely annoying hosting restrictions and unresponsive tech support, I have to use a CSV file as a database. </p> <p>While I can use MySQL with PHP, I can't use it with the Python backend of my program because of install issues with the host. I can't use SQLite with PHP because of more install issues, but can use it as it's a Python builtin.</p> <p>Anyways, now, the question: is it possible to update values SQL-style in a CSV database? Or should I keep on calling the help desk?</p>
4
2009-04-03T04:02:50Z
1,396,578
<p>Disagreeing with the noble colleagues, I often use DBD::CSV from Perl. There are good reasons to do it. Foremost is data update made simple using a spreadsheet. As a bonus, since I am using SQL queries, the application can be easily upgraded to a real database engine. Bear in mind these were extremely small database in a single user application. </p> <p>So rephrasing the question: Is there a python module equivalent to Perl's DBD:CSV</p>
0
2009-09-08T22:05:28Z
[ "python", "csv" ]
What are the differences between json and simplejson Python modules?
712,791
<p>I have seen many projects using <strong><code>simplejson</code></strong> module instead of <strong><code>json</code></strong> module from the Standard Library. Also, there are many different <code>simplejson</code> modules. Why would use these alternatives, instead of the one in the Standard Library?</p>
289
2009-04-03T06:56:13Z
712,795
<p>The builtin <code>json</code> module got included in Python 2.6. Any projects that support versions of Python &lt; 2.6 need to have a fallback. In many cases, that fallback is <code>simplejson</code>.</p>
5
2009-04-03T06:57:44Z
[ "python", "json", "simplejson" ]
What are the differences between json and simplejson Python modules?
712,791
<p>I have seen many projects using <strong><code>simplejson</code></strong> module instead of <strong><code>json</code></strong> module from the Standard Library. Also, there are many different <code>simplejson</code> modules. Why would use these alternatives, instead of the one in the Standard Library?</p>
289
2009-04-03T06:56:13Z
712,799
<p><code>json</code> <a href="http://docs.python.org/whatsnew/2.6.html#the-json-module-javascript-object-notation">is</a> <code>simplejson</code>, added to the stdlib. But since <code>json</code> was added in 2.6, <code>simplejson</code> has the advantage of working on more Python versions (2.4+). </p> <p><code>simplejson</code> is also updated more frequently than Python, so if you need (or want) the latest version, it's best to use <code>simplejson</code> itself, if possible.</p> <p>A good practice, in my opinion, is to use one or the other as a fallback.</p> <pre class="lang-python prettyprint-override"><code>try: import simplejson as json except ImportError: import json </code></pre>
305
2009-04-03T06:59:11Z
[ "python", "json", "simplejson" ]
What are the differences between json and simplejson Python modules?
712,791
<p>I have seen many projects using <strong><code>simplejson</code></strong> module instead of <strong><code>json</code></strong> module from the Standard Library. Also, there are many different <code>simplejson</code> modules. Why would use these alternatives, instead of the one in the Standard Library?</p>
289
2009-04-03T06:56:13Z
712,814
<p>Here's (a now outdated) comparison of Python json libraries:</p> <p><a href="http://deron.meranda.us/python/comparing_json_modules/" rel="nofollow">Comparing JSON modules for Python</a> (<a href="http://web.archive.org/web/20100814143114/http://deron.meranda.us/python/comparing_json_modules/" rel="nofollow">archive link</a>)</p> <p>Regardless of the results in this comparison you should use the standard library json if you are on Python 2.6. And.. might as well just use simplejson otherwise.</p>
4
2009-04-03T07:05:48Z
[ "python", "json", "simplejson" ]
What are the differences between json and simplejson Python modules?
712,791
<p>I have seen many projects using <strong><code>simplejson</code></strong> module instead of <strong><code>json</code></strong> module from the Standard Library. Also, there are many different <code>simplejson</code> modules. Why would use these alternatives, instead of the one in the Standard Library?</p>
289
2009-04-03T06:56:13Z
714,748
<p>Another reason projects use simplejson is that the builtin json did not originally include its C speedups, so the performance difference was noticeable.</p>
5
2009-04-03T16:42:58Z
[ "python", "json", "simplejson" ]
What are the differences between json and simplejson Python modules?
712,791
<p>I have seen many projects using <strong><code>simplejson</code></strong> module instead of <strong><code>json</code></strong> module from the Standard Library. Also, there are many different <code>simplejson</code> modules. Why would use these alternatives, instead of the one in the Standard Library?</p>
289
2009-04-03T06:56:13Z
3,544,125
<p>simplejson module is simply 1,5 times faster than json (On my computer, with simplejson 2.1.1 and Python 2.7 x86).</p> <p>If you want, you can try the benchmark: <a href="http://abral.altervista.org/jsonpickle-bench.zip" rel="nofollow">http://abral.altervista.org/jsonpickle-bench.zip</a> On my PC simplejson is faster than cPickle. I would like to know also your benchmarks!</p> <p>Probably, as said Coady, the difference between simplejson and json is that simplejson includes _speedups.c. So, why don't python developers use simplejson?</p>
2
2010-08-23T01:01:02Z
[ "python", "json", "simplejson" ]
What are the differences between json and simplejson Python modules?
712,791
<p>I have seen many projects using <strong><code>simplejson</code></strong> module instead of <strong><code>json</code></strong> module from the Standard Library. Also, there are many different <code>simplejson</code> modules. Why would use these alternatives, instead of the one in the Standard Library?</p>
289
2009-04-03T06:56:13Z
4,833,752
<p>I've been benchmarking json, simplejson and cjson.</p> <ul> <li>cjson is fastest</li> <li>simplejson is almost on par with cjson</li> <li>json is about 10x slower than simplejson</li> </ul> <p><a href="http://pastie.org/1507411" rel="nofollow">http://pastie.org/1507411</a>:</p> <pre><code>$ python test_serialization_speed.py -------------------- Encoding Tests -------------------- Encoding: 100000 x {'m': 'asdsasdqwqw', 't': 3} [ json] 1.12385 seconds for 100000 runs. avg: 0.011239ms [simplejson] 0.44356 seconds for 100000 runs. avg: 0.004436ms [ cjson] 0.09593 seconds for 100000 runs. avg: 0.000959ms Encoding: 10000 x {'m': [['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19]], 't': 3} [ json] 7.76628 seconds for 10000 runs. avg: 0.776628ms [simplejson] 0.51179 seconds for 10000 runs. avg: 0.051179ms [ cjson] 0.44362 seconds for 10000 runs. avg: 0.044362ms -------------------- Decoding Tests -------------------- Decoding: 100000 x {"m": "asdsasdqwqw", "t": 3} [ json] 3.32861 seconds for 100000 runs. avg: 0.033286ms [simplejson] 0.37164 seconds for 100000 runs. avg: 0.003716ms [ cjson] 0.03893 seconds for 100000 runs. avg: 0.000389ms Decoding: 10000 x {"m": [["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19]], "t": 3} [ json] 37.26270 seconds for 10000 runs. avg: 3.726270ms [simplejson] 0.56643 seconds for 10000 runs. avg: 0.056643ms [ cjson] 0.33007 seconds for 10000 runs. avg: 0.033007ms </code></pre>
18
2011-01-28T22:39:38Z
[ "python", "json", "simplejson" ]
What are the differences between json and simplejson Python modules?
712,791
<p>I have seen many projects using <strong><code>simplejson</code></strong> module instead of <strong><code>json</code></strong> module from the Standard Library. Also, there are many different <code>simplejson</code> modules. Why would use these alternatives, instead of the one in the Standard Library?</p>
289
2009-04-03T06:56:13Z
16,131,316
<p>I have to disagree with the other answers: the built in <strong><code>json</code></strong> library (in Python 2.7) is not necessarily slower than <strong><code>simplejson</code></strong>. It also doesn't have <a href="https://code.google.com/p/simplejson/issues/detail?id=40">this annoying unicode bug</a>.</p> <p>Here is a simple benchmark:</p> <pre><code>import json import simplejson from timeit import repeat NUMBER = 100000 REPEAT = 10 def compare_json_and_simplejson(data): """Compare json and simplejson - dumps and loads""" compare_json_and_simplejson.data = data compare_json_and_simplejson.dump = json.dumps(data) assert json.dumps(data) == simplejson.dumps(data) result = min(repeat("json.dumps(compare_json_and_simplejson.data)", "from __main__ import json, compare_json_and_simplejson", repeat = REPEAT, number = NUMBER)) print " json dumps {} seconds".format(result) result = min(repeat("simplejson.dumps(compare_json_and_simplejson.data)", "from __main__ import simplejson, compare_json_and_simplejson", repeat = REPEAT, number = NUMBER)) print "simplejson dumps {} seconds".format(result) assert json.loads(compare_json_and_simplejson.dump) == data result = min(repeat("json.loads(compare_json_and_simplejson.dump)", "from __main__ import json, compare_json_and_simplejson", repeat = REPEAT, number = NUMBER)) print " json loads {} seconds".format(result) result = min(repeat("simplejson.loads(compare_json_and_simplejson.dump)", "from __main__ import simplejson, compare_json_and_simplejson", repeat = REPEAT, number = NUMBER)) print "simplejson loads {} seconds".format(result) print "Complex real world data:" COMPLEX_DATA = {'status': 1, 'timestamp': 1362323499.23, 'site_code': 'testing123', 'remote_address': '212.179.220.18', 'input_text': u'ny monday for less than \u20aa123', 'locale_value': 'UK', 'eva_version': 'v1.0.3286', 'message': 'Successful Parse', 'muuid1': '11e2-8414-a5e9e0fd-95a6-12313913cc26', 'api_reply': {"api_reply": {"Money": {"Currency": "ILS", "Amount": "123", "Restriction": "Less"}, "ProcessedText": "ny monday for less than \\u20aa123", "Locations": [{"Index": 0, "Derived From": "Default", "Home": "Default", "Departure": {"Date": "2013-03-04"}, "Next": 10}, {"Arrival": {"Date": "2013-03-04", "Calculated": True}, "Index": 10, "All Airports Code": "NYC", "Airports": "EWR,JFK,LGA,PHL", "Name": "New York City, New York, United States (GID=5128581)", "Latitude": 40.71427, "Country": "US", "Type": "City", "Geoid": 5128581, "Longitude": -74.00597}]}}} compare_json_and_simplejson(COMPLEX_DATA) print "\nSimple data:" SIMPLE_DATA = [1, 2, 3, "asasd", {'a':'b'}] compare_json_and_simplejson(SIMPLE_DATA) </code></pre> <p>And the results on my system (Python 2.7.4, Linux 64-bit):</p> <blockquote> <p>Complex real world data:<br> json dumps 1.56666707993 seconds<br> simplejson dumps 2.25638604164 seconds<br> json loads 2.71256899834 seconds<br> simplejson loads 1.29233884811 seconds </p> <p>Simple data:<br> json dumps 0.370109081268 seconds<br> simplejson dumps 0.574181079865 seconds<br> json loads 0.422876119614 seconds<br> simplejson loads 0.270955085754 seconds </p> </blockquote> <p>For dumping, <code>json</code> is faster than <code>simplejson</code>. For loading, <code>simplejson</code> is faster.</p> <p>Since I am currently building a web service, <code>dumps()</code> is more important—and using a standard library is always preferred.</p> <p>Also, <code>cjson</code> was not updated in the past 4 years, so I wouldn't touch it.</p>
67
2013-04-21T12:53:31Z
[ "python", "json", "simplejson" ]
What are the differences between json and simplejson Python modules?
712,791
<p>I have seen many projects using <strong><code>simplejson</code></strong> module instead of <strong><code>json</code></strong> module from the Standard Library. Also, there are many different <code>simplejson</code> modules. Why would use these alternatives, instead of the one in the Standard Library?</p>
289
2009-04-03T06:56:13Z
17,823,905
<p>All of these answers aren't very helpful because they are <strong>time sensitive</strong>. </p> <p>After doing some research of my own I found that <code>simplejson</code> is indeed faster than the builtin, <strong>if</strong> you keep it updated to the latest version.</p> <p><code>pip/easy_install</code> wanted to install 2.3.2 on ubuntu 12.04, but after finding out the latest <code>simplejson</code> version is actually 3.3.0, so I updated it and reran the time tests. </p> <ul> <li><code>simplejson</code> is about 3x faster than the builtin <code>json</code> at loads</li> <li><code>simplejson</code> is about 30% faster than the builtin <code>json</code> at dumps</li> </ul> <h3>Disclaimer:</h3> <p>The above statements are in python-2.7.3 and simplejson 3.3.0 (with c speedups) And to make sure my answer also isn't time sensitive, you should <strong>run your own tests</strong> to check since it varies so much between versions; there's no easy answer that isn't time sensitive.</p> <h3>How to tell if C speedups are enabled in simplejson:</h3> <pre><code>import simplejson # If this is True, then c speedups are enabled. print bool(getattr(simplejson, '_speedups', False)) </code></pre> <p><strong>UPDATE:</strong> I recently came across a library called <a href="https://pypi.python.org/pypi/ujson">ujson</a> that is performing ~3x faster than <code>simplejson</code> with some basic tests. </p>
17
2013-07-24T01:48:06Z
[ "python", "json", "simplejson" ]
What are the differences between json and simplejson Python modules?
712,791
<p>I have seen many projects using <strong><code>simplejson</code></strong> module instead of <strong><code>json</code></strong> module from the Standard Library. Also, there are many different <code>simplejson</code> modules. Why would use these alternatives, instead of the one in the Standard Library?</p>
289
2009-04-03T06:56:13Z
19,366,580
<p>An API incompatibility I found, with Python 2.7 vs simplejson 3.3.1 is in whether output produces str or unicode objects. e.g.</p> <pre><code>&gt;&gt;&gt; from json import JSONDecoder &gt;&gt;&gt; jd = JSONDecoder() &gt;&gt;&gt; jd.decode("""{ "a":"b" }""") {u'a': u'b'} </code></pre> <p>vs</p> <pre><code>&gt;&gt;&gt; from simplejson import JSONDecoder &gt;&gt;&gt; jd = JSONDecoder() &gt;&gt;&gt; jd.decode("""{ "a":"b" }""") {'a': 'b'} </code></pre> <p>If the preference is to use simplejson, then this can be addressed by coercing the argument string to unicode, as in:</p> <pre><code>&gt;&gt;&gt; from simplejson import JSONDecoder &gt;&gt;&gt; jd = JSONDecoder() &gt;&gt;&gt; jd.decode(unicode("""{ "a":"b" }""", "utf-8")) {u'a': u'b'} </code></pre> <p>The coercion does require knowing the original charset, for example:</p> <pre><code>&gt;&gt;&gt; jd.decode(unicode("""{ "a": "ξηθννββωφρες" }""")) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in position 8: ordinal not in range(128) </code></pre> <p>This is the won't fix <a href="https://code.google.com/p/simplejson/issues/detail?id=40">issue 40</a></p>
6
2013-10-14T18:19:40Z
[ "python", "json", "simplejson" ]
What are the differences between json and simplejson Python modules?
712,791
<p>I have seen many projects using <strong><code>simplejson</code></strong> module instead of <strong><code>json</code></strong> module from the Standard Library. Also, there are many different <code>simplejson</code> modules. Why would use these alternatives, instead of the one in the Standard Library?</p>
289
2009-04-03T06:56:13Z
31,269,030
<p>I came across this question as I was looking to install simplejson for Python 2.6. I needed to use the 'object_pairs_hook' of json.load() in order to load a json file as an OrderedDict. Being familiar with more recent versions of Python I didn't realize that the json module for Python 2.6 doesn't include the 'object_pairs_hook' so I had to install simplejson for this purpose. From personal experience this is why i use simplejson as opposed to the standard json module.</p>
0
2015-07-07T12:51:06Z
[ "python", "json", "simplejson" ]
What are the differences between json and simplejson Python modules?
712,791
<p>I have seen many projects using <strong><code>simplejson</code></strong> module instead of <strong><code>json</code></strong> module from the Standard Library. Also, there are many different <code>simplejson</code> modules. Why would use these alternatives, instead of the one in the Standard Library?</p>
289
2009-04-03T06:56:13Z
36,091,411
<p>Some values are serialized differently between simplejson and json.</p> <p>Notably, instances of <code>collections.namedtuple</code> are serialized as arrays by <code>json</code> but as objects by <code>simplejson</code>. You can override this behaviour by passing <code>namedtuple_as_object=False</code> to <code>simplejson.dump</code>, but by default the behaviours do not match.</p> <pre><code>&gt;&gt;&gt; import collections, simplejson, json &gt;&gt;&gt; TupleClass = collections.namedtuple("TupleClass", ("a", "b")) &gt;&gt;&gt; value = TupleClass(1, 2) &gt;&gt;&gt; json.dumps(value) '[1, 2]' &gt;&gt;&gt; simplejson.dumps(value) '{"a": 1, "b": 2}' &gt;&gt;&gt; simplejson.dumps(value, namedtuple_as_object=False) '[1, 2]' </code></pre>
1
2016-03-18T18:07:05Z
[ "python", "json", "simplejson" ]
What are the differences between json and simplejson Python modules?
712,791
<p>I have seen many projects using <strong><code>simplejson</code></strong> module instead of <strong><code>json</code></strong> module from the Standard Library. Also, there are many different <code>simplejson</code> modules. Why would use these alternatives, instead of the one in the Standard Library?</p>
289
2009-04-03T06:56:13Z
38,016,773
<p>In python3, if you a string of <code>b'bytes'</code>, with <code>json</code> you have to <code>.decode()</code> the content before you can load it. <code>simplejson</code> takes care of this so you can just do <code>simplejson.loads(byte_string)</code>.</p>
0
2016-06-24T15:16:53Z
[ "python", "json", "simplejson" ]
Getting the docstring from a function
713,138
<p>I have the following function:</p> <pre><code>def my_func(): """My docstring is both funny and informative""" pass </code></pre> <p>How do I get access to the docstring?</p>
75
2009-04-03T09:04:09Z
713,143
<p>Interactively, you can display it with</p> <pre><code>help(my_func) </code></pre> <p>Or from code you can retrieve it with</p> <pre><code>my_func.__doc__ </code></pre>
108
2009-04-03T09:05:57Z
[ "python" ]
Getting the docstring from a function
713,138
<p>I have the following function:</p> <pre><code>def my_func(): """My docstring is both funny and informative""" pass </code></pre> <p>How do I get access to the docstring?</p>
75
2009-04-03T09:04:09Z
5,915,733
<p>You can also use <a href="http://docs.python.org/library/inspect.html#inspect.getdoc">inspect.getdoc</a>. It cleans up the __doc__ by normalizing tabs to spaces and left shifting the doc body to remove common leading spaces. </p>
40
2011-05-06T18:47:14Z
[ "python" ]
How to disable v1 tag in a Web service request with SoapPy?
713,522
<p>I'm trying to use SOAPpy to write a web service client. However after defining WSDL object, a call to a web-service method is wrapped in a </p> <pre><code> &lt;v1&gt; .. actual parameters .. &lt;/v1&gt; </code></pre> <p>How can I disable this v1 tag?</p>
0
2009-04-03T11:14:07Z
713,754
<p>Answering my own question, you can give the name of tag by providing name in the parameter call list, ie:</p> <p>server.GetList(GetListRequest = { "order" : "asc" })</p> <p>then v1 is replaced by GetListRequest as I originally wanted.</p>
0
2009-04-03T12:45:29Z
[ "python", "web-services", "soappy" ]
Preserving the Java-type of an object when passing it from Java to Jython
713,675
<p>I wonder if it possible to <strong>not</strong> have jython automagicaly transform java objects to python types when you put them in a Java ArrayList.</p> <p>Example copied from a jython-console:</p> <pre><code>&gt;&gt;&gt; b = java.lang.Boolean("True"); &gt;&gt;&gt; type(b) &lt;type 'javainstance'&gt; &gt;&gt;&gt; isinstance(b, java.lang.Boolean); 1 </code></pre> <p>So far, everything is fine but if I put the object in an ArrayList</p> <pre><code>&gt;&gt;&gt; l = java.util.ArrayList(); &gt;&gt;&gt; l.add(b) 1 &gt;&gt;&gt; type(l.get(0)) &lt;type 'int'&gt; </code></pre> <p>the object is transformed into a python-like boolean (i.e. an int) and... </p> <pre><code>&gt;&gt;&gt; isinstance(l.get(0), java.lang.Boolean) 0 </code></pre> <p>which means that I can no longer see that this was once a java.lang.Boolean.</p> <p><strong>Clarification</strong></p> <p>I guess what really want to achieve is to get rid of the implicit conversion from Java-types to Python-types when passing objects from Java to Python. I will give another example for clarification.</p> <p>A Python module:</p> <pre><code>import java import IPythonModule class PythonModule(IPythonModule): def method(self, data): print type(data); </code></pre> <p>And a Java-Class that uses this module:</p> <pre><code>import java.util.ArrayList; import org.python.core.PyList; import org.testng.annotations.*; import static org.testng.AssertJUnit.*; public class Test1 { IPythonModule m; @BeforeClass public void setUp() { JythonFactory jf = JythonFactory.getInstance(); m = (IPythonModule) jf.getJythonObject( "IPythonModule", "/Users/sg/workspace/JythonTests/src/PythonModule.py"); } @Test public void testFirst() { m.method(new Boolean("true")); } } </code></pre> <p>Here I will see the output 'bool' because of the implicit conversion, but what I would really like is to see 'javainstance' or 'java.lang.Boolean'. If you want to run this code you will also need the JythonFactory-class that can be found <a href="http://wiki.python.org/jython/JythonMonthly/Articles/September2006/1" rel="nofollow">here</a>.</p>
5
2009-04-03T12:13:18Z
713,932
<p>You appear to be using an old version of Jython. In current Jython versions, the Python <code>bool</code> type corresponds to a Java <code>Boolean</code>.</p> <p>Jython is not transforming the Java type to a Python type on the way into the <code>ArrayList</code> - on the contrary, it will transform a primitive Python type to a primitive or wrapper Java type when passing it to a Java method, and a Java type to a Python type on the way out.</p> <p>You can observe this by printing the contents of the array. Note that the Python <code>bool</code> is capitalized (<code>True</code>); the Java <code>Boolean</code> is not. </p> <pre><code>&gt;&gt;&gt; from java.lang import Boolean &gt;&gt;&gt; b = Boolean('True') &gt;&gt;&gt; b true &gt;&gt;&gt; from java.util import ArrayList &gt;&gt;&gt; l = ArrayList() &gt;&gt;&gt; l.add(b) True &gt;&gt;&gt; l [true] &gt;&gt;&gt; l.add(True) True &gt;&gt;&gt; l [true, true] &gt;&gt;&gt; list(l) [True, True] </code></pre> <p>If this still doesn't do what you want, consider writing a small Java helper function that examines the array for you without conversion. It's arguably a bug that Jython doesn't automatically convert the <code>Boolean</code> you constructed into a Python <code>bool</code>, and in this case it gives you no advantage over using <code>Boolean.TRUE</code> or the Python <code>True</code>.</p>
1
2009-04-03T13:35:01Z
[ "java", "python", "jython" ]
Catching an exception while using a Python 'with' statement
713,794
<p>To my shame, I can't figure out how to handle exception for python 'with' statement. If I have a code:</p> <pre><code>with open("a.txt") as f: print f.readlines() </code></pre> <p>I really want to handle 'file not found exception' in order to do somehing. But I can't write</p> <pre><code>with open("a.txt") as f: print f.readlines() except: print 'oops' </code></pre> <p>and can't write</p> <pre><code>with open("a.txt") as f: print f.readlines() else: print 'oops' </code></pre> <p>enclosing 'with' in a try/except statement doesn't work else: exception is not raised. What can I do in order to process failure inside 'with' statement in a Pythonic way?</p>
129
2009-04-03T13:00:25Z
713,814
<pre><code>from __future__ import with_statement try: with open( "a.txt" ) as f : print f.readlines() except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available print 'oops' </code></pre> <p>If you want different handling for errors from the open call vs the working code you could do:</p> <pre><code>try: f = open('foo.txt') except IOError: print('error') else: with f: print f.readlines() </code></pre>
126
2009-04-03T13:04:32Z
[ "python", "exception-handling" ]
Catching an exception while using a Python 'with' statement
713,794
<p>To my shame, I can't figure out how to handle exception for python 'with' statement. If I have a code:</p> <pre><code>with open("a.txt") as f: print f.readlines() </code></pre> <p>I really want to handle 'file not found exception' in order to do somehing. But I can't write</p> <pre><code>with open("a.txt") as f: print f.readlines() except: print 'oops' </code></pre> <p>and can't write</p> <pre><code>with open("a.txt") as f: print f.readlines() else: print 'oops' </code></pre> <p>enclosing 'with' in a try/except statement doesn't work else: exception is not raised. What can I do in order to process failure inside 'with' statement in a Pythonic way?</p>
129
2009-04-03T13:00:25Z
713,819
<p>I just tried, enclosing the with in a try/except works fine.</p> <pre><code>try: with open("dummy.txt", "r") as f: print(f.readlines()) except: print("oops") </code></pre>
-4
2009-04-03T13:05:46Z
[ "python", "exception-handling" ]
Catching an exception while using a Python 'with' statement
713,794
<p>To my shame, I can't figure out how to handle exception for python 'with' statement. If I have a code:</p> <pre><code>with open("a.txt") as f: print f.readlines() </code></pre> <p>I really want to handle 'file not found exception' in order to do somehing. But I can't write</p> <pre><code>with open("a.txt") as f: print f.readlines() except: print 'oops' </code></pre> <p>and can't write</p> <pre><code>with open("a.txt") as f: print f.readlines() else: print 'oops' </code></pre> <p>enclosing 'with' in a try/except statement doesn't work else: exception is not raised. What can I do in order to process failure inside 'with' statement in a Pythonic way?</p>
129
2009-04-03T13:00:25Z
713,831
<p>This code works fine in python 2.5.1:</p> <pre><code>from __future__ import with_statement try: with open('non-existent.txt') as f: print f.readlines() except: print "Exception" </code></pre>
-4
2009-04-03T13:09:12Z
[ "python", "exception-handling" ]
Catching an exception while using a Python 'with' statement
713,794
<p>To my shame, I can't figure out how to handle exception for python 'with' statement. If I have a code:</p> <pre><code>with open("a.txt") as f: print f.readlines() </code></pre> <p>I really want to handle 'file not found exception' in order to do somehing. But I can't write</p> <pre><code>with open("a.txt") as f: print f.readlines() except: print 'oops' </code></pre> <p>and can't write</p> <pre><code>with open("a.txt") as f: print f.readlines() else: print 'oops' </code></pre> <p>enclosing 'with' in a try/except statement doesn't work else: exception is not raised. What can I do in order to process failure inside 'with' statement in a Pythonic way?</p>
129
2009-04-03T13:00:25Z
6,090,497
<p>The best "Pythonic" way to do this, exploiting the <code>with</code> statement, is listed as Example #6 in <a href="http://www.python.org/dev/peps/pep-0343/">PEP 343</a>, which gives the background of the statement.</p> <pre><code>@contextmanager def opened_w_error(filename, mode="r"): try: f = open(filename, mode) except IOError, err: yield None, err else: try: yield f, None finally: f.close() </code></pre> <p>Used as follows:</p> <pre><code>with opened_w_error("/etc/passwd", "a") as (f, err): if err: print "IOError:", err else: f.write("guido::0:0::/:/bin/sh\n") </code></pre>
38
2011-05-22T20:13:04Z
[ "python", "exception-handling" ]
Catching an exception while using a Python 'with' statement
713,794
<p>To my shame, I can't figure out how to handle exception for python 'with' statement. If I have a code:</p> <pre><code>with open("a.txt") as f: print f.readlines() </code></pre> <p>I really want to handle 'file not found exception' in order to do somehing. But I can't write</p> <pre><code>with open("a.txt") as f: print f.readlines() except: print 'oops' </code></pre> <p>and can't write</p> <pre><code>with open("a.txt") as f: print f.readlines() else: print 'oops' </code></pre> <p>enclosing 'with' in a try/except statement doesn't work else: exception is not raised. What can I do in order to process failure inside 'with' statement in a Pythonic way?</p>
129
2009-04-03T13:00:25Z
31,623,217
<blockquote> <p><strong>Catching an exception while using a Python 'with' statement</strong></p> </blockquote> <p>Here's the closest thing to correct that you have. You're almost there:</p> <pre><code>with open("a.txt") as f: print f.readlines() except: print 'oops' </code></pre> <p>A context manager's <code>__exit__</code> method, if it returns <code>False</code> will reraise the error when it finishes. If it returns <code>True</code>, it will suppress it. The <code>open</code> builtin's <code>__exit__</code> doesn't return <code>True</code>, so you just need to nest it in a try, except block:</p> <pre><code>try: with open("a.txt") as f: print(f.readlines()) except Exception as error: print 'oops' </code></pre> <p>And standard boilerplate: don't use a bare <code>except:</code> which catches <code>BaseException</code> and every other possible exception and warning. Be at least as specific as <code>Exception</code>, and for this error, perhaps catch <code>IOError</code>. Only catch errors you're prepared to handle.</p>
6
2015-07-25T05:15:57Z
[ "python", "exception-handling" ]
How can I generate a screenshot of a webpage using a server-side script?
713,938
<p>I need a server-side script (PHP, Python) to capture a webpage to a PNG, JPG, Tiff, GIF image and resize them to a thumbnail.</p> <p>What is the best way to accomplish this?</p> <h3>See also:</h3> <blockquote> <ul> <li><a href="http://stackoverflow.com/questions/686858/web-page-screenshots-with-php">Web Page Screenshots with PHP?</a></li> <li><a href="http://stackoverflow.com/questions/627301/how-can-i-take-a-screenshot-of-a-website-with-php-and-gd">How can I take a screenshot of a website with PHP and GD?</a></li> <li><a href="http://stackoverflow.com/questions/443837">How might I obtain a Snapshot or Thumbnail of a web page using PHP?</a></li> </ul> </blockquote>
18
2009-04-03T13:35:52Z
713,952
<p>What needs to happen is for a program to render the page and then take an image of the page. This is a very slow and heavy process but it <a href="http://is.php.net/manual/en/function.imagegrabscreen.php">can be done in PHP on Windows.</a></p> <p>Also check the comments in the documentation article.</p> <p>For python <a href="http://www.blogs.uni-osnabrueck.de/rotapken/2008/12/03/create-screenshots-of-a-web-page-using-python-and-qtwebkit/">I'd recommend reading this article</a>. It highlights some of the solutions.</p> <p>There are services you can also call (via some API) that will return you an image. But usually they cost (<a href="http://webshotspro.com/">WebShots</a> for example)</p>
7
2009-04-03T13:39:42Z
[ "php", "python", "screenshot", "server-side-scripting" ]
How can I generate a screenshot of a webpage using a server-side script?
713,938
<p>I need a server-side script (PHP, Python) to capture a webpage to a PNG, JPG, Tiff, GIF image and resize them to a thumbnail.</p> <p>What is the best way to accomplish this?</p> <h3>See also:</h3> <blockquote> <ul> <li><a href="http://stackoverflow.com/questions/686858/web-page-screenshots-with-php">Web Page Screenshots with PHP?</a></li> <li><a href="http://stackoverflow.com/questions/627301/how-can-i-take-a-screenshot-of-a-website-with-php-and-gd">How can I take a screenshot of a website with PHP and GD?</a></li> <li><a href="http://stackoverflow.com/questions/443837">How might I obtain a Snapshot or Thumbnail of a web page using PHP?</a></li> </ul> </blockquote>
18
2009-04-03T13:35:52Z
713,959
<p>You'll need to:</p> <ul> <li>read the webpage and all the its multimedia content (images, flash, etc)</li> <li>utilize a browser rendering engine to render the webpage</li> <li>take a screenshot and save it as image</li> </ul> <p>first and third steps are easy, the second step is more challenging ;)</p>
1
2009-04-03T13:41:55Z
[ "php", "python", "screenshot", "server-side-scripting" ]
How can I generate a screenshot of a webpage using a server-side script?
713,938
<p>I need a server-side script (PHP, Python) to capture a webpage to a PNG, JPG, Tiff, GIF image and resize them to a thumbnail.</p> <p>What is the best way to accomplish this?</p> <h3>See also:</h3> <blockquote> <ul> <li><a href="http://stackoverflow.com/questions/686858/web-page-screenshots-with-php">Web Page Screenshots with PHP?</a></li> <li><a href="http://stackoverflow.com/questions/627301/how-can-i-take-a-screenshot-of-a-website-with-php-and-gd">How can I take a screenshot of a website with PHP and GD?</a></li> <li><a href="http://stackoverflow.com/questions/443837">How might I obtain a Snapshot or Thumbnail of a web page using PHP?</a></li> </ul> </blockquote>
18
2009-04-03T13:35:52Z
713,975
<p>You can probably write something similar to <a href="http://www.paulhammond.org/webkit2png/">webkit2png</a>, unless your server already runs Mac OS X.</p> <p><strong>UPDATE:</strong> I just saw the link to its Linux equivalent: <a href="http://khtml2png.sourceforge.net/">khtml2png</a></p> <p>See also:</p> <ul> <li><a href="http://www.blogs.uni-osnabrueck.de/rotapken/2008/12/03/create-screenshots-of-a-web-page-using-python-and-qtwebkit/">Create screenshots of a web page using Python and QtWebKit</a></li> <li><a href="http://www.hackdiary.com/2004/06/13/taking-automated-webpage-screenshots-with-embedded-mozilla/">Taking automated webpage screenshots with embedded Mozilla</a></li> </ul>
13
2009-04-03T13:46:41Z
[ "php", "python", "screenshot", "server-side-scripting" ]
How can I generate a screenshot of a webpage using a server-side script?
713,938
<p>I need a server-side script (PHP, Python) to capture a webpage to a PNG, JPG, Tiff, GIF image and resize them to a thumbnail.</p> <p>What is the best way to accomplish this?</p> <h3>See also:</h3> <blockquote> <ul> <li><a href="http://stackoverflow.com/questions/686858/web-page-screenshots-with-php">Web Page Screenshots with PHP?</a></li> <li><a href="http://stackoverflow.com/questions/627301/how-can-i-take-a-screenshot-of-a-website-with-php-and-gd">How can I take a screenshot of a website with PHP and GD?</a></li> <li><a href="http://stackoverflow.com/questions/443837">How might I obtain a Snapshot or Thumbnail of a web page using PHP?</a></li> </ul> </blockquote>
18
2009-04-03T13:35:52Z
1,658,867
<p>If you are using php, you could use imagegrabscreen (PHP 5 >= 5.2.2). Imagegrabscreen: captures the whole screen.</p> <p></p>
1
2009-11-02T00:10:04Z
[ "php", "python", "screenshot", "server-side-scripting" ]
Importing modules from parent folder
714,063
<p>I am running Python 2.5.</p> <p>This is my folder tree:</p> <pre><code>ptdraft/ nib.py simulations/ life/ life.py </code></pre> <p>(I also have <code>__init__.py</code> in each folder, omitted here for readability)</p> <p>How do I import the <code>nib</code> module from inside the <code>life</code> module? I am hoping it is possible to do without tinkering with sys.path.</p> <p>Note: The main module being run is in the <code>ptdraft</code> folder.</p>
197
2009-04-03T14:08:02Z
714,070
<p>What's wrong with just <code>import ptdraft.nib</code></p> <h3>Update:</h3> <p>It seems that the problem is not related to the module being in a parent directory or anything like that.</p> <p>You need to add the directory that contains <code>ptdraft</code> to PYTHONPATH</p> <p>You said that <code>import nib</code> worked with you, that probably means that you added <code>ptdraft</code> itself (not its parent) to PYTHONPATH.</p>
40
2009-04-03T14:09:23Z
[ "python", "module", "folders", "python-import" ]
Importing modules from parent folder
714,063
<p>I am running Python 2.5.</p> <p>This is my folder tree:</p> <pre><code>ptdraft/ nib.py simulations/ life/ life.py </code></pre> <p>(I also have <code>__init__.py</code> in each folder, omitted here for readability)</p> <p>How do I import the <code>nib</code> module from inside the <code>life</code> module? I am hoping it is possible to do without tinkering with sys.path.</p> <p>Note: The main module being run is in the <code>ptdraft</code> folder.</p>
197
2009-04-03T14:08:02Z
714,647
<p>You could use relative imports (python >= 2.5):</p> <pre><code>from ... import nib </code></pre> <p><a href="http://docs.python.org/2/whatsnew/2.5.html#pep-328-absolute-and-relative-imports">(What’s New in Python 2.5) PEP 328: Absolute and Relative Imports</a></p> <p><strong>EDIT</strong>: added another dot '.' to go up two packages</p>
359
2009-04-03T16:17:27Z
[ "python", "module", "folders", "python-import" ]
Importing modules from parent folder
714,063
<p>I am running Python 2.5.</p> <p>This is my folder tree:</p> <pre><code>ptdraft/ nib.py simulations/ life/ life.py </code></pre> <p>(I also have <code>__init__.py</code> in each folder, omitted here for readability)</p> <p>How do I import the <code>nib</code> module from inside the <code>life</code> module? I am hoping it is possible to do without tinkering with sys.path.</p> <p>Note: The main module being run is in the <code>ptdraft</code> folder.</p>
197
2009-04-03T14:08:02Z
9,331,002
<p>If adding your module folder to the PYTHONPATH didn't work, You can modify the <strong>sys.path</strong> list in your program where the Python interpreter searches for the modules to import, the <a href="http://docs.python.org/tutorial/modules.html#the-module-search-path" rel="nofollow">python documentation</a> says:</p> <blockquote> <p>When a module named <strong>spam</strong> is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named <strong>spam.py</strong> in a list of directories given by the variable sys.path. sys.path is initialized from these locations:</p> <blockquote> <ul> <li>the directory containing the input script (or the current directory).</li> <li>PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).</li> <li>the installation-dependent default.</li> </ul> <p>After initialization, Python programs can modify <strong>sys.path</strong>. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended. </p> </blockquote> </blockquote> <p>Knowing this, you can do the following in your program:</p> <pre><code>import sys # Add the ptdraft folder path to the sys.path list sys.path.append('/path/to/ptdraft/') # Now you can import your module from ptdraft import nib # Or just import ptdraft </code></pre>
18
2012-02-17T15:30:55Z
[ "python", "module", "folders", "python-import" ]
Importing modules from parent folder
714,063
<p>I am running Python 2.5.</p> <p>This is my folder tree:</p> <pre><code>ptdraft/ nib.py simulations/ life/ life.py </code></pre> <p>(I also have <code>__init__.py</code> in each folder, omitted here for readability)</p> <p>How do I import the <code>nib</code> module from inside the <code>life</code> module? I am hoping it is possible to do without tinkering with sys.path.</p> <p>Note: The main module being run is in the <code>ptdraft</code> folder.</p>
197
2009-04-03T14:08:02Z
11,158,224
<p>Relative imports (as in <code>from .. import mymodule</code>) only work in a package. To import 'mymodule' that is in the parent directory of your current module:</p> <pre><code>import os,sys,inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0,parentdir) import mymodule </code></pre> <p><strong>edit</strong>: the <code>__file__</code> attribute is not allways given. Instead of using <code>os.path.abspath(__file__)</code> I now suggested using the inspect module to retrieve the filename (and path) of the current file</p>
90
2012-06-22T14:30:07Z
[ "python", "module", "folders", "python-import" ]
Importing modules from parent folder
714,063
<p>I am running Python 2.5.</p> <p>This is my folder tree:</p> <pre><code>ptdraft/ nib.py simulations/ life/ life.py </code></pre> <p>(I also have <code>__init__.py</code> in each folder, omitted here for readability)</p> <p>How do I import the <code>nib</code> module from inside the <code>life</code> module? I am hoping it is possible to do without tinkering with sys.path.</p> <p>Note: The main module being run is in the <code>ptdraft</code> folder.</p>
197
2009-04-03T14:08:02Z
19,409,830
<p>same sort of style as the past answer - but in fewer lines :P</p> <pre><code>import os,sys parentdir = os.path.dirname(__file__) sys.path.insert(0,parentdir) </code></pre> <p>file returns the location you are working in</p>
2
2013-10-16T17:25:20Z
[ "python", "module", "folders", "python-import" ]
Importing modules from parent folder
714,063
<p>I am running Python 2.5.</p> <p>This is my folder tree:</p> <pre><code>ptdraft/ nib.py simulations/ life/ life.py </code></pre> <p>(I also have <code>__init__.py</code> in each folder, omitted here for readability)</p> <p>How do I import the <code>nib</code> module from inside the <code>life</code> module? I am hoping it is possible to do without tinkering with sys.path.</p> <p>Note: The main module being run is in the <code>ptdraft</code> folder.</p>
197
2009-04-03T14:08:02Z
21,784,070
<p>Here is more generic solution that includes the parent directory into sys.path (works for me):</p> <pre><code>import os.path, sys sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)) </code></pre>
15
2014-02-14T16:09:22Z
[ "python", "module", "folders", "python-import" ]
Importing modules from parent folder
714,063
<p>I am running Python 2.5.</p> <p>This is my folder tree:</p> <pre><code>ptdraft/ nib.py simulations/ life/ life.py </code></pre> <p>(I also have <code>__init__.py</code> in each folder, omitted here for readability)</p> <p>How do I import the <code>nib</code> module from inside the <code>life</code> module? I am hoping it is possible to do without tinkering with sys.path.</p> <p>Note: The main module being run is in the <code>ptdraft</code> folder.</p>
197
2009-04-03T14:08:02Z
28,712,742
<p>You can use OS depending path in "module search path" which is listed in <strong>sys.path</strong> . So you can easily add parent directory like following </p> <pre><code>import sys sys.path.insert(0,'..') </code></pre> <p>If you want to add parent-parent directory,</p> <pre><code>sys.path.insert(0,'../..') </code></pre>
14
2015-02-25T06:37:47Z
[ "python", "module", "folders", "python-import" ]
Importing modules from parent folder
714,063
<p>I am running Python 2.5.</p> <p>This is my folder tree:</p> <pre><code>ptdraft/ nib.py simulations/ life/ life.py </code></pre> <p>(I also have <code>__init__.py</code> in each folder, omitted here for readability)</p> <p>How do I import the <code>nib</code> module from inside the <code>life</code> module? I am hoping it is possible to do without tinkering with sys.path.</p> <p>Note: The main module being run is in the <code>ptdraft</code> folder.</p>
197
2009-04-03T14:08:02Z
32,770,757
<p>Work with libraries. Make a library called nib, install it using setup.py, let it reside in site-packages and your problems are solved. You don't have to stuff everything you make in a single package. Break it up to pieces.</p>
1
2015-09-24T20:56:22Z
[ "python", "module", "folders", "python-import" ]
Importing modules from parent folder
714,063
<p>I am running Python 2.5.</p> <p>This is my folder tree:</p> <pre><code>ptdraft/ nib.py simulations/ life/ life.py </code></pre> <p>(I also have <code>__init__.py</code> in each folder, omitted here for readability)</p> <p>How do I import the <code>nib</code> module from inside the <code>life</code> module? I am hoping it is possible to do without tinkering with sys.path.</p> <p>Note: The main module being run is in the <code>ptdraft</code> folder.</p>
197
2009-04-03T14:08:02Z
33,532,002
<p>Using information from this Stack Overflow answer, "<a href="http://stackoverflow.com/questions/2632199/how-do-i-get-the-path-of-the-current-executed-file-in-python/18489147#18489147">How do I get the path of the current executed file in python?</a>", here is a short, simple, hopefully easy to understand answer. It is also quite cross-compatible with different operating systems too as the modules <code>os</code>, <code>sys</code> and <code>inspect</code> come as part of Python, which is built for many OS-es, so they are designed to be.</p> <blockquote> <pre><code>from inspect import getsourcefile from os.path import abspath </code></pre> <p>Next, wherever you want to find the source file from you just use:</p> <pre><code>abspath(getsourcefile(lambda:0)) </code></pre> </blockquote> <p>Also, I never use the <code>__file__</code> variable and use <code>getsourcefile(lambda:0)</code> because (Stackoverflow) users have often mentioned that it can be unreliable and doesn't work on every <em>O.S.</em>. The <code>__file__</code> attribute <a href="http://stackoverflow.com/a/11158224/3787376">is not always available</a> and <a href="http://stackoverflow.com/questions/714063/importing-modules-from-parent-folder/33532002?noredirect=1#comment33997203_19409830">doesn't always contain the full file path</a>. Of course you can use <code>__file__</code> in your own code if you really care about reducing the code size slightly or don't care about the problems caused. <hr></p> <h3>So my answer is:</h3> <pre><code>from inspect import getsourcefile import os.path import sys current_path = os.path.abspath(getsourcefile(lambda:0)) current_dir = os.path.dirname(current_path) parent_dir = current_dir[:current_dir.rfind(os.path.sep)] sys.path.insert(0, parent_dir) import my_module # Change name here to your module! </code></pre> <p>And <strong>if you don't want the <code>sys.path</code> python path list to become cluttered</strong> <br>with the file directories your own modules are stored in, you can use the lines below:</p> <pre><code>import my_module # Change name here to your module! sys.path.pop(0) # Make sure you remove the same item as the one # created above, otherwise you may get problems # when importing other modules in Python. </code></pre> <p>Although actually, I have discovered that any edits made to <code>sys.path</code> in a program are not permanent (when you restart the Python shell they disappear from <code>sys.path</code>).<br> So the lines above may not be necessary. <hr></p> <h3>You can even shorten this code further:</h3> <pre><code>from inspect import getsourcefile import os.path as path, sys current_dir = path.dirname(path.abspath(getsourcefile(lambda:0))) sys.path.insert(0, current_dir[:current_dir.rfind(path.sep)]) import my_module # Change name here to your module! sys.path.pop(0) </code></pre>
7
2015-11-04T21:06:30Z
[ "python", "module", "folders", "python-import" ]
Importing modules from parent folder
714,063
<p>I am running Python 2.5.</p> <p>This is my folder tree:</p> <pre><code>ptdraft/ nib.py simulations/ life/ life.py </code></pre> <p>(I also have <code>__init__.py</code> in each folder, omitted here for readability)</p> <p>How do I import the <code>nib</code> module from inside the <code>life</code> module? I am hoping it is possible to do without tinkering with sys.path.</p> <p>Note: The main module being run is in the <code>ptdraft</code> folder.</p>
197
2009-04-03T14:08:02Z
36,334,426
<p>When not being in a package environment with <code>__init__.py</code> files the pathlib library (included with >= Python 3.4) makes it very concise and intuitive to append the path of the parent directory to the PYTHONPATH:</p> <pre><code>import sys from pathlib import Path sys.path.append(str(Path('.').absolute().parent)) </code></pre>
2
2016-03-31T13:08:47Z
[ "python", "module", "folders", "python-import" ]
Importing modules from parent folder
714,063
<p>I am running Python 2.5.</p> <p>This is my folder tree:</p> <pre><code>ptdraft/ nib.py simulations/ life/ life.py </code></pre> <p>(I also have <code>__init__.py</code> in each folder, omitted here for readability)</p> <p>How do I import the <code>nib</code> module from inside the <code>life</code> module? I am hoping it is possible to do without tinkering with sys.path.</p> <p>Note: The main module being run is in the <code>ptdraft</code> folder.</p>
197
2009-04-03T14:08:02Z
38,519,139
<p>you can append your directory path to sys</p> <pre><code>import sys import os sys.path.append(os.path.__file__) </code></pre>
0
2016-07-22T05:54:26Z
[ "python", "module", "folders", "python-import" ]
Importing modules from parent folder
714,063
<p>I am running Python 2.5.</p> <p>This is my folder tree:</p> <pre><code>ptdraft/ nib.py simulations/ life/ life.py </code></pre> <p>(I also have <code>__init__.py</code> in each folder, omitted here for readability)</p> <p>How do I import the <code>nib</code> module from inside the <code>life</code> module? I am hoping it is possible to do without tinkering with sys.path.</p> <p>Note: The main module being run is in the <code>ptdraft</code> folder.</p>
197
2009-04-03T14:08:02Z
39,338,640
<p><code> import sys sys.path.append('../') </code></p>
2
2016-09-05T23:07:57Z
[ "python", "module", "folders", "python-import" ]
How to execute an arbitrary shell script and pass multiple variables via Python?
714,360
<p>I am building an application plugin in Python which allows users to arbitrarily extend the application with simple scripts (working under Mac OS X). Executing Python scripts is easy, but some users are more comfortable with languages like Ruby.</p> <p>From what I've read, I can easily execute Ruby scripts (or other arbitrary shell scripts) using <code>subprocess</code> and capture their output with a pipe; that's not a problem, and there's lots of examples online. However, I need to provide the script with multiple variables (say a chunk of text along with some simple boolean information about the text the script is modifying) and I'm having trouble figuring out the best way to do this.</p> <p>Does anyone have a suggestion for the best way to accomplish this? My goal is to provide scripts with the information they need with the least required code needed for accessing that information within the script.</p> <p>Thanks in advance!</p>
2
2009-04-03T15:10:32Z
714,397
<p>See <a href="http://docs.python.org/library/subprocess.html#using-the-subprocess-module" rel="nofollow">http://docs.python.org/library/subprocess.html#using-the-subprocess-module</a></p> <blockquote> <p>args should be a string, or a sequence of program arguments. The program to execute is normally the first item in the args sequence or the string if a string is given, but can be explicitly set by using the executable argument.</p> </blockquote> <p>So, your call can look like this</p> <pre><code>p = subprocess.Popen( args=["script.sh", "-p", p_opt, "-v", v_opt, arg1, arg2] ) </code></pre> <p>You've put arbitrary Python values into the args of <code>subprocess.Popen</code>.</p>
4
2009-04-03T15:16:32Z
[ "python", "ruby", "osx", "shell", "environment-variables" ]
How to execute an arbitrary shell script and pass multiple variables via Python?
714,360
<p>I am building an application plugin in Python which allows users to arbitrarily extend the application with simple scripts (working under Mac OS X). Executing Python scripts is easy, but some users are more comfortable with languages like Ruby.</p> <p>From what I've read, I can easily execute Ruby scripts (or other arbitrary shell scripts) using <code>subprocess</code> and capture their output with a pipe; that's not a problem, and there's lots of examples online. However, I need to provide the script with multiple variables (say a chunk of text along with some simple boolean information about the text the script is modifying) and I'm having trouble figuring out the best way to do this.</p> <p>Does anyone have a suggestion for the best way to accomplish this? My goal is to provide scripts with the information they need with the least required code needed for accessing that information within the script.</p> <p>Thanks in advance!</p>
2
2009-04-03T15:10:32Z
714,499
<p>If you are going to be launching multiple scripts and need to pass the same information to each of them, you might consider using the environment (warning, I don't know Python, so the following code most likely sucks):</p> <pre><code>#!/usr/bin/python import os try: #if environment is set if os.environ["child"] == "1": print os.environ["string"] except: #set environment os.environ["child"] = "1" os.environ["string"] = "hello world" #run this program 5 times as a child process for n in range(1, 5): os.system(__file__) </code></pre>
1
2009-04-03T15:37:09Z
[ "python", "ruby", "osx", "shell", "environment-variables" ]
How to execute an arbitrary shell script and pass multiple variables via Python?
714,360
<p>I am building an application plugin in Python which allows users to arbitrarily extend the application with simple scripts (working under Mac OS X). Executing Python scripts is easy, but some users are more comfortable with languages like Ruby.</p> <p>From what I've read, I can easily execute Ruby scripts (or other arbitrary shell scripts) using <code>subprocess</code> and capture their output with a pipe; that's not a problem, and there's lots of examples online. However, I need to provide the script with multiple variables (say a chunk of text along with some simple boolean information about the text the script is modifying) and I'm having trouble figuring out the best way to do this.</p> <p>Does anyone have a suggestion for the best way to accomplish this? My goal is to provide scripts with the information they need with the least required code needed for accessing that information within the script.</p> <p>Thanks in advance!</p>
2
2009-04-03T15:10:32Z
718,545
<p>One approach you could take would be to use json as a protocol between parent and child scripts, since json support is readily available in many languages, and is fairly expressive. You could also use a pipe to send an arbitrary amount of data down to the child process, assuming your requirements allow you to have the child scripts read from standard input. For example, the parent could do something like (Python 2.6 shown):</p> <pre><code>#!/usr/bin/env python import json import subprocess data_for_child = { 'text' : 'Twas brillig...', 'flag1' : False, 'flag2' : True } child = subprocess.Popen(["./childscript"], stdin=subprocess.PIPE) json.dump(data_for_child, child.stdin) </code></pre> <p>And here is a sketch of a child script:</p> <pre><code>#!/usr/bin/env python # Imagine this were written in a different language. import json import sys d = json.load(sys.stdin) print d </code></pre> <p>In this trivial example, the output is:</p> <pre> $ ./foo12.py {u'text': u'Twas brillig...', u'flag2': True, u'flag1': False} </pre>
0
2009-04-05T07:48:15Z
[ "python", "ruby", "osx", "shell", "environment-variables" ]
Turning ctypes data into python string as quickly as possible
714,367
<p>I'm trying to write a video application in PyQt4 and I've used Python ctypes to hook into an old legacy video decoder library. The library gives me 32-bit ARGB data and I need to turn that into a QImage. I've got it working as follows:</p> <pre><code> # Copy the rgb image data from the pointer into the buffer memmove(self.rgb_buffer, self.rgb_buffer_ptr, self.buffer_size) # Copy the buffer to a python string imgdata = "" for a in self.rgb_buffer: imgdata = imgdata + a # Create a QImage from the string data img = QImage(imgdata, 720, 288, QImage.Format_ARGB32) </code></pre> <p>The problem is that ctypes outputs the data as type "<code>ctypes.c_char_Array_829440</code>" and I need to turn it into a python string so that I can construct a QImage. My copying mechanism is currently taking almost 300ms per image so it's painfully slow. The decode and display part of the process is only taking about 50ms.</p> <p>Can anyone think of any cunning shortcuts I can take to speed up this process and avoid the need to copy the buffer twice as I'm currently doing?</p>
3
2009-04-03T15:11:15Z
714,735
<p>The <code>ctypes.c_char_Array_829400</code> instance has the property <code>.raw</code> which returns a string possibly containing NUL bytes, and the property <code>.value</code> which returns the string up to the first NUL byte if it contains one or more.</p> <p>However, you can also use ctypes the access the string at <code>self.rgb_buffer_ptr</code>, like this: <code>ctypes.string_at(self.rgb_buffer_ptr, self.buffer_size)</code>; this would avoid the need for the memmove call.</p>
6
2009-04-03T16:38:18Z
[ "python", "pyqt4", "ctypes" ]
What is a maximum number of arguments in a Python function?
714,475
<p>It's somewhat common knowledge that Python functions can have a maximum of 256 arguments. What I'm curious to know is if this limit applies to <code>*args</code> and <code>**kwargs</code> when they're unrolled in the following manner:</p> <pre><code>items = [1,2,3,4,5,6] def do_something(*items): pass </code></pre> <p>I ask because, hypothetically, there might be cases where a list larger than 256 items gets unrolled as a set of <code>*args</code> or <code>**kwargs</code>.</p>
21
2009-04-03T15:32:14Z
714,491
<p>I tried for a list of 4000 items, and it worked. So I'm guessing it will work for larger values as well.</p>
2
2009-04-03T15:35:43Z
[ "python", "function", "arguments", "language-features", "limit" ]
What is a maximum number of arguments in a Python function?
714,475
<p>It's somewhat common knowledge that Python functions can have a maximum of 256 arguments. What I'm curious to know is if this limit applies to <code>*args</code> and <code>**kwargs</code> when they're unrolled in the following manner:</p> <pre><code>items = [1,2,3,4,5,6] def do_something(*items): pass </code></pre> <p>I ask because, hypothetically, there might be cases where a list larger than 256 items gets unrolled as a set of <code>*args</code> or <code>**kwargs</code>.</p>
21
2009-04-03T15:32:14Z
714,518
<p>WFM</p> <pre><code>&gt;&gt;&gt; fstr = 'def f(%s): pass'%(', '.join(['arg%d'%i for i in range(5000)])) &gt;&gt;&gt; exec(fstr) &gt;&gt;&gt; f &lt;function f at 0x829bae4&gt; </code></pre> <p><strong>Update:</strong> as Brian noticed, the limit is on the calling side:</p> <pre><code>&gt;&gt;&gt; exec 'f(' + ','.join(str(i) for i in range(5000)) + ')' Traceback (most recent call last): File "&lt;pyshell#63&gt;", line 1, in &lt;module&gt; exec 'f(' + ','.join(str(i) for i in range(5000)) + ')' File "&lt;string&gt;", line 1 SyntaxError: more than 255 arguments (&lt;string&gt;, line 1) </code></pre> <p>on the other hand this works:</p> <pre><code>&gt;&gt;&gt; f(*range(5000)) &gt;&gt;&gt; </code></pre> <p><strong>Conclusion:</strong> no, it does not apply to unrolled arguments.</p>
17
2009-04-03T15:44:51Z
[ "python", "function", "arguments", "language-features", "limit" ]
What is a maximum number of arguments in a Python function?
714,475
<p>It's somewhat common knowledge that Python functions can have a maximum of 256 arguments. What I'm curious to know is if this limit applies to <code>*args</code> and <code>**kwargs</code> when they're unrolled in the following manner:</p> <pre><code>items = [1,2,3,4,5,6] def do_something(*items): pass </code></pre> <p>I ask because, hypothetically, there might be cases where a list larger than 256 items gets unrolled as a set of <code>*args</code> or <code>**kwargs</code>.</p>
21
2009-04-03T15:32:14Z
714,524
<p>for **kwargs, If I remember well, this is a dictionary. It therefore has about no limits.</p> <p>for *args, I am not so sure, but I think it is a tuple or a list, so it also has about no limits.</p> <p>By no limits, I mean except maybe the memory limit.</p>
2
2009-04-03T15:46:26Z
[ "python", "function", "arguments", "language-features", "limit" ]
What is a maximum number of arguments in a Python function?
714,475
<p>It's somewhat common knowledge that Python functions can have a maximum of 256 arguments. What I'm curious to know is if this limit applies to <code>*args</code> and <code>**kwargs</code> when they're unrolled in the following manner:</p> <pre><code>items = [1,2,3,4,5,6] def do_something(*items): pass </code></pre> <p>I ask because, hypothetically, there might be cases where a list larger than 256 items gets unrolled as a set of <code>*args</code> or <code>**kwargs</code>.</p>
21
2009-04-03T15:32:14Z
714,755
<p>This appears to be a restriction in compiling the source, so will probably exist only for arguments being passed directly, not in *args or **kwargs.</p> <p>The relevant code can be found in <a href="http://svn.python.org/view/python/trunk/Python/ast.c?view=markup" rel="nofollow">ast.c</a>:</p> <pre><code>if (nargs + nkeywords + ngens &gt; 255) { ast_error(n, "more than 255 arguments"); return NULL; } </code></pre> <p>But note that this is in ast_for_call, and so only applys to the calling side. ie <code>f(a,b,c,d,e...)</code>, rather than the definition, though it will count both positional <code>(a,b,c,d)</code> and <code> keyword (a=1, b=2, c=3)</code> style parameters . Actual <code>*args</code> and <code>**kwargs</code> parameters look like they should only count as one argument for these purposes on the calling side.</p>
4
2009-04-03T16:45:42Z
[ "python", "function", "arguments", "language-features", "limit" ]
What is a maximum number of arguments in a Python function?
714,475
<p>It's somewhat common knowledge that Python functions can have a maximum of 256 arguments. What I'm curious to know is if this limit applies to <code>*args</code> and <code>**kwargs</code> when they're unrolled in the following manner:</p> <pre><code>items = [1,2,3,4,5,6] def do_something(*items): pass </code></pre> <p>I ask because, hypothetically, there might be cases where a list larger than 256 items gets unrolled as a set of <code>*args</code> or <code>**kwargs</code>.</p>
21
2009-04-03T15:32:14Z
8,932,175
<p>The limit is due to how the compiled bytecode treats calling a function with position arguments and/or keyword arguments.</p> <p>The bytecode op of concern is CALL_FUNCTION which carries an op_arg that is 4 bytes in length, but on the two least significant bytes are used. Of those, the most significant byte represent the number of keyword arguments on the stack and the least significant byte the number of positional arguments on the stack. Therefore, you can have at most 0xFF == 255 keyword arguments or 0xFF == 255 positional arguments. </p> <p>This limit does not apply to *args and **kwargs because calls with that grammar use the bytecode ops CALL_FUNCTION_VAR, CALL_FUNCTION_KW, and CALL_FUNCTION_VAR_KW depending on the signature. For these opcodes, the stack consists of an iterable for the *args and a dict for the **kwargs. These items get passed directly to the receiver which unrolls them as needed.</p>
18
2012-01-19T19:36:03Z
[ "python", "function", "arguments", "language-features", "limit" ]
How do I print outputs from calls to subprocess.Popen(...) in a loop?
714,879
<p>I wrote a script to run a command-line program with different input arguments and grab a certain line from the output. I have the following running in a loop:</p> <pre><code>p1 = subprocess.Popen(["program", args], stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=False) p2 = subprocess.Popen(["grep", phrase], stdin=p1.stdout, stdout=subprocess.PIPE, shell=False) p1.wait() p2.wait() p = str(p2.stdout.readlines()) print 'p is ', p </code></pre> <p>One problem is that there is only output after the loop is finished running. I want to print something each time a process is finished. How can I do that?</p> <p>Also, I want to have the option of displaying the output of p1. But I can't grab it with p1.stdout.readlines() without breaking p2. How can I do this?</p> <p>I was thinking that I could just not make the call to grep, store the output of p1 and search for the phrase, but there's a lot of output, so this way seems pretty inefficient.</p> <p>Any suggestions would be greatly appreciated. Thanks!</p>
4
2009-04-03T17:20:33Z
714,902
<p>Try calling sys.stdout.flush() after each print statement.</p>
1
2009-04-03T17:29:50Z
[ "python", "subprocess" ]
How do I print outputs from calls to subprocess.Popen(...) in a loop?
714,879
<p>I wrote a script to run a command-line program with different input arguments and grab a certain line from the output. I have the following running in a loop:</p> <pre><code>p1 = subprocess.Popen(["program", args], stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=False) p2 = subprocess.Popen(["grep", phrase], stdin=p1.stdout, stdout=subprocess.PIPE, shell=False) p1.wait() p2.wait() p = str(p2.stdout.readlines()) print 'p is ', p </code></pre> <p>One problem is that there is only output after the loop is finished running. I want to print something each time a process is finished. How can I do that?</p> <p>Also, I want to have the option of displaying the output of p1. But I can't grab it with p1.stdout.readlines() without breaking p2. How can I do this?</p> <p>I was thinking that I could just not make the call to grep, store the output of p1 and search for the phrase, but there's a lot of output, so this way seems pretty inefficient.</p> <p>Any suggestions would be greatly appreciated. Thanks!</p>
4
2009-04-03T17:20:33Z
718,569
<p>Here's a quick hack that worked for me on Linux. It might work for you, depending on your requirements. It uses <a href="http://unixhelp.ed.ac.uk/CGI/man-cgi?tee" rel="nofollow">tee</a> as a filter that, if you pass <code>print_all</code> to your script, will duplicate an extra copy to <a href="http://linux.die.net/man/4/tty" rel="nofollow">/dev/tty</a> (hey, I said it was a hack):</p> <pre><code>#!/usr/bin/env python import subprocess import sys phrase = "bar" if len(sys.argv) &gt; 1 and sys.argv[1] == 'print_all': tee_args = ['tee', '/dev/tty'] else: tee_args = ['tee'] p1 = subprocess.Popen(["./program"], stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=False) p2 = subprocess.Popen(tee_args, stdin=p1.stdout, stdout=subprocess.PIPE, shell=False) p3 = subprocess.Popen(["grep", phrase], stdin=p2.stdout, stdout=subprocess.PIPE, shell=False) p1.wait() p2.wait() p3.wait() p = str(p3.stdout.readlines()) print 'p is ', p </code></pre> <p>With the following as contents for <code>program</code>:</p> <pre><code>#!/bin/sh echo foo echo bar echo baz </code></pre> <p>Example output:</p> <pre> $ ./foo13.py p is ['bar\n'] $ ./foo13.py print_all foo bar baz p is ['bar\n'] </pre>
2
2009-04-05T08:11:14Z
[ "python", "subprocess" ]
How to include external Python code to use in other files?
714,881
<p>If you have a collection of methods in a file, is there a way to include those files in another file, but call them without any prefix (i.e. file prefix)?</p> <p>So if I have:</p> <pre><code>[Math.py] def Calculate ( num ) </code></pre> <p>How do I call it like this:</p> <pre><code>[Tool.py] using Math.py for i in range ( 5 ) : Calculate ( i ) </code></pre>
86
2009-04-03T17:21:58Z
714,889
<p>If you use:</p> <pre><code>import Math </code></pre> <p>then that will allow you to use Math's functions, but you must do Math.Calculate, so that is obviously what you don't want.</p> <p>If you want to import a module's functions without having to prefix them, you must explicitly name them, like:</p> <pre><code>from Math import Calculate, Add, Subtract </code></pre> <p>Now, you can reference Calculate, Add, and Subtract just by their names. If you wanted to import ALL functions from Math, do:</p> <pre><code>from Math import * </code></pre> <p>However, you should be very careful when doing this with modules whose contents you are unsure of. <strong>If you import two modules who contain definitions for the same function name, one function will overwrite the other, with you none the wiser.</strong></p>
30
2009-04-03T17:24:10Z
[ "python" ]