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
Unittesting Corba in Python
1,660,049
<p>I am interested in your opinions on unittesting code that uses Corba to communicate with a server.</p> <p>Would you mock the Corba objects? In Python that's sort of a pain in the ass because all the methods of Corba objects are loaded dynamically. So you're basically stuck with "mock anything".</p> <p>Thanks!</p> ...
2
2009-11-02T08:38:34Z
1,660,187
<p>I would set up a test server, and do live tests on that. Unittesting can be tricky with network stuff, so it's best to keep it as real as possible. Any mocking would be done on the test server, for instance if you need to communicate to three different servers, it could be set up with three different IP addresses to...
1
2009-11-02T09:19:57Z
[ "python", "unit-testing", "mocking", "corba" ]
read string backwards and terminate at first '/'
1,660,059
<p>I want to extract just the file name portion of a path. My code below works, but I'd like to know what the better (pythonic) way of doing this is.</p> <pre><code>filename = '' tmppath = '/dir1/dir2/dir3/file.exe' for i in reversed(tmppath): if i != '/': filename += str(i) else: ...
3
2009-11-02T08:42:14Z
1,660,081
<p>Try:</p> <pre><code>#!/usr/bin/python import os.path path = '/dir1/dir2/dir3/file.exe' name = os.path.basename(path) print name </code></pre>
12
2009-11-02T08:47:47Z
[ "python", "path" ]
read string backwards and terminate at first '/'
1,660,059
<p>I want to extract just the file name portion of a path. My code below works, but I'd like to know what the better (pythonic) way of doing this is.</p> <pre><code>filename = '' tmppath = '/dir1/dir2/dir3/file.exe' for i in reversed(tmppath): if i != '/': filename += str(i) else: ...
3
2009-11-02T08:42:14Z
1,660,084
<p>you'd be better off using standard library for this:</p> <pre><code>&gt;&gt;&gt; tmppath = '/dir1/dir2/dir3/file.exe' &gt;&gt;&gt; import os.path &gt;&gt;&gt; os.path.basename(tmppath) 'file.exe' </code></pre>
4
2009-11-02T08:48:14Z
[ "python", "path" ]
read string backwards and terminate at first '/'
1,660,059
<p>I want to extract just the file name portion of a path. My code below works, but I'd like to know what the better (pythonic) way of doing this is.</p> <pre><code>filename = '' tmppath = '/dir1/dir2/dir3/file.exe' for i in reversed(tmppath): if i != '/': filename += str(i) else: ...
3
2009-11-02T08:42:14Z
1,660,090
<p>Use <a href="http://docs.python.org/library/os.path.html" rel="nofollow">os.path.basename(..)</a> function.</p>
2
2009-11-02T08:49:50Z
[ "python", "path" ]
read string backwards and terminate at first '/'
1,660,059
<p>I want to extract just the file name portion of a path. My code below works, but I'd like to know what the better (pythonic) way of doing this is.</p> <pre><code>filename = '' tmppath = '/dir1/dir2/dir3/file.exe' for i in reversed(tmppath): if i != '/': filename += str(i) else: ...
3
2009-11-02T08:42:14Z
1,660,092
<pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; path = '/dir1/dir2/dir3/file.exe' &gt;&gt;&gt; path.split(os.sep) ['', 'dir1', 'dir2', 'dir3', 'file.exe'] &gt;&gt;&gt; path.split(os.sep)[-1] 'file.exe' &gt;&gt;&gt; </code></pre>
1
2009-11-02T08:50:06Z
[ "python", "path" ]
read string backwards and terminate at first '/'
1,660,059
<p>I want to extract just the file name portion of a path. My code below works, but I'd like to know what the better (pythonic) way of doing this is.</p> <pre><code>filename = '' tmppath = '/dir1/dir2/dir3/file.exe' for i in reversed(tmppath): if i != '/': filename += str(i) else: ...
3
2009-11-02T08:42:14Z
1,662,836
<p>The existing answers are correct for your "real underlying question" (path manipulation). For the question in your title (generalizable to other characters of course), what helps there is the <code>rsplit</code> method of strings:</p> <pre><code>&gt;&gt;&gt; s='some/stuff/with/many/slashes' &gt;&gt;&gt; s.rsplit('...
0
2009-11-02T18:21:34Z
[ "python", "path" ]
Python fetching <title>
1,660,302
<p>I want to fetch the title of a webpage which I open using urllib2. What is the best way to do this, to parse the html and find what I need (for now only the -tag but might need more in the future).</p> <p>Is there a good parsing lib for this purpose?</p>
3
2009-11-02T09:48:59Z
1,660,327
<p>Use <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a>.</p> <pre><code>html = urllib2.urlopen("...").read() from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(html) print soup.title.string </code></pre>
0
2009-11-02T09:54:09Z
[ "python", "urllib2" ]
Python fetching <title>
1,660,302
<p>I want to fetch the title of a webpage which I open using urllib2. What is the best way to do this, to parse the html and find what I need (for now only the -tag but might need more in the future).</p> <p>Is there a good parsing lib for this purpose?</p>
3
2009-11-02T09:48:59Z
1,660,335
<p>Try <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a>:</p> <pre><code>url = 'http://www.example.com' response = urllib2.urlopen(url) html = response.read() soup = BeautifulSoup(html) title = soup.html.head.title print title.contents </code></pre>
4
2009-11-02T09:55:06Z
[ "python", "urllib2" ]
Python fetching <title>
1,660,302
<p>I want to fetch the title of a webpage which I open using urllib2. What is the best way to do this, to parse the html and find what I need (for now only the -tag but might need more in the future).</p> <p>Is there a good parsing lib for this purpose?</p>
3
2009-11-02T09:48:59Z
1,660,336
<p>Yes I would recommend <a href="http://www.crummy.com/software/BeautifulSoup/">BeautifulSoup</a></p> <p>If you're getting the title it's simply:</p> <pre><code>soup = BeautifulSoup(html) myTitle = soup.html.head.title </code></pre> <p>or</p> <pre><code>myTitle = soup('title') </code></pre> <p>Taken from <a href=...
7
2009-11-02T09:55:11Z
[ "python", "urllib2" ]
Python fetching <title>
1,660,302
<p>I want to fetch the title of a webpage which I open using urllib2. What is the best way to do this, to parse the html and find what I need (for now only the -tag but might need more in the future).</p> <p>Is there a good parsing lib for this purpose?</p>
3
2009-11-02T09:48:59Z
27,229,974
<p>Why are you guys importing a whole extra library for one task. No regular expressions? wasn't the request for urllib not bs4 or mech which are third party? to do with standard libraries parse the html and match the string then split the <code>'&gt;'</code> <code>'&lt;'</code> with re or whateves.</p> <pre><code>...
1
2014-12-01T13:58:17Z
[ "python", "urllib2" ]
How can I pass a function's name to a function, and then call it?
1,660,351
<ol> <li><p>How can I pass a functions name to a function and then call it? Is it possible to do this without using <code>getattribute</code>?</p></li> <li><p>How can I pass a class name to a function and then instantiate the class? I know I just could pass the instance of the class directly to the function but it is i...
1
2009-11-02T10:00:22Z
1,660,355
<pre><code>def outer(f): # any name: function, class, any callable return f() # class will be instantiated within the scope of the function </code></pre>
5
2009-11-02T10:02:13Z
[ "python" ]
How can I pass a function's name to a function, and then call it?
1,660,351
<ol> <li><p>How can I pass a functions name to a function and then call it? Is it possible to do this without using <code>getattribute</code>?</p></li> <li><p>How can I pass a class name to a function and then instantiate the class? I know I just could pass the instance of the class directly to the function but it is i...
1
2009-11-02T10:00:22Z
1,660,361
<p>If you have a limited number of options your planning to use, you could set up a dictionary with string keys and values of the functions/classes.</p>
0
2009-11-02T10:03:20Z
[ "python" ]
How can I pass a function's name to a function, and then call it?
1,660,351
<ol> <li><p>How can I pass a functions name to a function and then call it? Is it possible to do this without using <code>getattribute</code>?</p></li> <li><p>How can I pass a class name to a function and then instantiate the class? I know I just could pass the instance of the class directly to the function but it is i...
1
2009-11-02T10:00:22Z
1,660,372
<p>Why not use the function and the class directly?</p> <pre><code>class A(object): pass def f(): pass def g(func, cls): func() x = cls() g(f, A) </code></pre>
0
2009-11-02T10:05:44Z
[ "python" ]
How can I pass a function's name to a function, and then call it?
1,660,351
<ol> <li><p>How can I pass a functions name to a function and then call it? Is it possible to do this without using <code>getattribute</code>?</p></li> <li><p>How can I pass a class name to a function and then instantiate the class? I know I just could pass the instance of the class directly to the function but it is i...
1
2009-11-02T10:00:22Z
1,660,394
<pre><code>namespace = globals() result = namespace[func_name]() instance = namespace[class_name](*some_args) </code></pre> <p>You can use your own dictionary (namespace) instead of <code>globals</code>.</p> <p>It is unclear why do you need artificial constrains such as not passing directly function/class objects, no...
2
2009-11-02T10:08:43Z
[ "python" ]
PyQt and MVC-pattern
1,660,474
<p>Please, help me with designing MVC-pattern with PyQt. I want to split all program at 3 parts:</p> <ol> <li>some class that is abstracted from all Qt classes(model)</li> <li>some class that provides data from model to qt-app(controller)</li> <li>Qt-app itself with defined method SignalsToSlots that connect signals w...
16
2009-11-02T10:27:34Z
1,690,593
<p>One of the first things you should do is use Qt4 designer to design your gui and use pyuic4 to generate your python GUI. This will be your view, you NEVER edit these python files by hand. Always make changes using designer, this ensures your View is separate from your model and control.</p> <p>For the control eleme...
26
2009-11-06T21:29:45Z
[ "python", "design", "qt", "pyqt" ]
PyQt and MVC-pattern
1,660,474
<p>Please, help me with designing MVC-pattern with PyQt. I want to split all program at 3 parts:</p> <ol> <li>some class that is abstracted from all Qt classes(model)</li> <li>some class that provides data from model to qt-app(controller)</li> <li>Qt-app itself with defined method SignalsToSlots that connect signals w...
16
2009-11-02T10:27:34Z
1,692,893
<p>Yes, PyQt uses Model/View concept (officially without the "Controller" part), but may be you have a somewhat distorted picture what does it mean in PyQt.</p> <p>There are two parts:</p> <ol> <li>Models, subclassed from appropriate PyQt base abstract model classes (<code>QAbstractItemModel</code>, <code>QAbstractTa...
5
2009-11-07T12:33:25Z
[ "python", "design", "qt", "pyqt" ]
PyQt and MVC-pattern
1,660,474
<p>Please, help me with designing MVC-pattern with PyQt. I want to split all program at 3 parts:</p> <ol> <li>some class that is abstracted from all Qt classes(model)</li> <li>some class that provides data from model to qt-app(controller)</li> <li>Qt-app itself with defined method SignalsToSlots that connect signals w...
16
2009-11-02T10:27:34Z
31,036,012
<p>Here's a link to the official and detailed guide on how Qt architecture offers Model-View design to an application</p> <p><a href="http://doc.qt.io/qt-5/model-view-programming.html" rel="nofollow">http://doc.qt.io/qt-5/model-view-programming.html</a></p> <p>In Qt, view and controller are combined, therefore an app...
1
2015-06-24T20:07:38Z
[ "python", "design", "qt", "pyqt" ]
Nose test script with command line arguments
1,660,520
<p>I would like to be able to run a nose test script which accepts command line arguments. For example, something along the lines:</p> <p>test.py</p> <pre><code>import nose, sys def test(): # do something with the command line arguments print sys.argv if __name__ == '__main__': nose.runmodule() </code><...
10
2009-11-02T10:41:57Z
1,661,073
<p>Just running nose and passing in parameters will not work as nose will attempt to interpret the arguments as nose parameters so you get the problems you are seeing.</p> <p>I do not think nose support parameter passing directly yet but this nose plug-in <a href="http://pypi.python.org/pypi/nose-testconfig/" rel="nof...
2
2009-11-02T12:39:39Z
[ "python", "command-line-arguments", "nose" ]
Nose test script with command line arguments
1,660,520
<p>I would like to be able to run a nose test script which accepts command line arguments. For example, something along the lines:</p> <p>test.py</p> <pre><code>import nose, sys def test(): # do something with the command line arguments print sys.argv if __name__ == '__main__': nose.runmodule() </code><...
10
2009-11-02T10:41:57Z
1,661,171
<p>Alright, I hate "why would you want to do that?" answers just as much as anyone, but I'm going to have to make one here. I hope you don't mind.</p> <p>I'd argue that doing whatever you're wanting to do isn't within the scope of the framework nose. Nose is intended for <em>automated</em> tests. If you have to pas...
12
2009-11-02T12:58:25Z
[ "python", "command-line-arguments", "nose" ]
Nose test script with command line arguments
1,660,520
<p>I would like to be able to run a nose test script which accepts command line arguments. For example, something along the lines:</p> <p>test.py</p> <pre><code>import nose, sys def test(): # do something with the command line arguments print sys.argv if __name__ == '__main__': nose.runmodule() </code><...
10
2009-11-02T10:41:57Z
1,718,407
<p>For now I am using the following hack</p> <pre><code>args = sys.argv[1:] sys.argv = sys.argv[0:1] </code></pre> <p>which just reads the argument into a local variable, and then deletes all the additional arguments in sys.argv so that nose doesn't get confused by them.</p>
3
2009-11-11T22:09:39Z
[ "python", "command-line-arguments", "nose" ]
Nose test script with command line arguments
1,660,520
<p>I would like to be able to run a nose test script which accepts command line arguments. For example, something along the lines:</p> <p>test.py</p> <pre><code>import nose, sys def test(): # do something with the command line arguments print sys.argv if __name__ == '__main__': nose.runmodule() </code><...
10
2009-11-02T10:41:57Z
16,290,369
<p>You could use another means of getting stuff into your code:</p> <pre><code>import os print os.getenv('KEY_THAT_MIGHT_EXIST', default_value) </code></pre> <p>Then just remember to set your environment before running nose.</p>
9
2013-04-30T00:26:25Z
[ "python", "command-line-arguments", "nose" ]
Nose test script with command line arguments
1,660,520
<p>I would like to be able to run a nose test script which accepts command line arguments. For example, something along the lines:</p> <p>test.py</p> <pre><code>import nose, sys def test(): # do something with the command line arguments print sys.argv if __name__ == '__main__': nose.runmodule() </code><...
10
2009-11-02T10:41:57Z
29,386,386
<p>I think that is a perfectly acceptable scenario. I also needed to do something similar in order to run the tests against different scenarios (dev, qa, prod, etc) and there I needed the right URLS and configurations for each environment.</p> <p>The solution I found was to use the <strong>nose-testconfig</strong> plu...
2
2015-04-01T08:44:08Z
[ "python", "command-line-arguments", "nose" ]
Unable to get results when passing a string via parameter substitution in gql query
1,660,640
<p>I am able to properly pass a string variable to the gqlquery through parameter substitution, here's the code i've tried to use;</p> <pre><code>user_name = self.request.get('username') #retrieved from UI p = models.UserDetails.all().filter('user_name = ', user_name).fetch(1) </code></pre> <p>I don't get any results...
0
2009-11-02T11:09:37Z
1,660,654
<p>Have you tried <code>filter('user_name = ', str(user_name))</code> ?<br /> I supose you are sure user_name has the expected content.</p>
0
2009-11-02T11:12:25Z
[ "python", "google-app-engine", "gql", "gqlquery", "string-substitution" ]
Unable to get results when passing a string via parameter substitution in gql query
1,660,640
<p>I am able to properly pass a string variable to the gqlquery through parameter substitution, here's the code i've tried to use;</p> <pre><code>user_name = self.request.get('username') #retrieved from UI p = models.UserDetails.all().filter('user_name = ', user_name).fetch(1) </code></pre> <p>I don't get any results...
0
2009-11-02T11:09:37Z
1,660,738
<p>I think I've got it, I tried using this,</p> <pre><code>p = models.UserDetails.gql('WHERE user_name = :uname', uname = user_name).fetch(1) </code></pre> <p>and I got the expected resultset. I wonder why other formats have the problem in string substitution.</p>
0
2009-11-02T11:31:34Z
[ "python", "google-app-engine", "gql", "gqlquery", "string-substitution" ]
Unable to get results when passing a string via parameter substitution in gql query
1,660,640
<p>I am able to properly pass a string variable to the gqlquery through parameter substitution, here's the code i've tried to use;</p> <pre><code>user_name = self.request.get('username') #retrieved from UI p = models.UserDetails.all().filter('user_name = ', user_name).fetch(1) </code></pre> <p>I don't get any results...
0
2009-11-02T11:09:37Z
1,662,930
<p>Try logging <code>repr(user_name)</code> to verify that the string is exactly the same as what you're expecting (and that it's not unicode rather than raw). Also try logging the expression <code>user_name == "peter rice"</code>. Other than that, I can't see any reason why it would not work - there's literally no way...
0
2009-11-02T18:44:19Z
[ "python", "google-app-engine", "gql", "gqlquery", "string-substitution" ]
Python alternative of ruby watirrecorder?
1,660,643
<p>I'm looking for a tool to record scripts for web application testing in python, similar to ruby watirrecorder. The latter is basically a tool that generates the script for watir (web application testing in ruby) which uses IE to test web applications. </p>
4
2009-11-02T11:10:19Z
1,660,649
<p>Try Selenium, <a href="http://jimmyg.org/blog/2009/getting-started-with-selenium-and-python.html">http://jimmyg.org/blog/2009/getting-started-with-selenium-and-python.html</a></p>
5
2009-11-02T11:11:25Z
[ "python", "ruby", "watir" ]
Python alternative of ruby watirrecorder?
1,660,643
<p>I'm looking for a tool to record scripts for web application testing in python, similar to ruby watirrecorder. The latter is basically a tool that generates the script for watir (web application testing in ruby) which uses IE to test web applications. </p>
4
2009-11-02T11:10:19Z
6,268,974
<p>Another alternative may be Pamie, but not sure it is as mature as Selenium. <a href="http://sourceforge.net/projects/pamie/" rel="nofollow">http://sourceforge.net/projects/pamie/</a></p>
1
2011-06-07T17:06:54Z
[ "python", "ruby", "watir" ]
TypeError: cannot concatenate 'str' and 'instance' objects (python urllib)
1,660,954
<p>Writing a python program, and I came up with this error while using the <code>urllib.urlopen</code> function.</p> <pre><code>Traceback (most recent call last): File "ChurchScraper.py", line 58, in &lt;module&gt; html = GetAllChurchPages() File "ChurchScraper.py", line 48, in GetAllChurchPages CPs = CPs + urllib.url...
2
2009-11-02T12:14:58Z
1,660,978
<p>urlopen(url) returns a file-like object. To obtain the string contents, try</p> <pre><code>CPs = CPs + urllib.urlopen(url).read() </code></pre>
5
2009-11-02T12:18:54Z
[ "python", "urllib" ]
TypeError: cannot concatenate 'str' and 'instance' objects (python urllib)
1,660,954
<p>Writing a python program, and I came up with this error while using the <code>urllib.urlopen</code> function.</p> <pre><code>Traceback (most recent call last): File "ChurchScraper.py", line 58, in &lt;module&gt; html = GetAllChurchPages() File "ChurchScraper.py", line 48, in GetAllChurchPages CPs = CPs + urllib.url...
2
2009-11-02T12:14:58Z
1,660,980
<p>urllib.urllopen doesn't return a string, it returns an object<br /> <a href="http://docs.python.org/library/urllib.html#urllib.urlopen" rel="nofollow">doc</a></p> <pre><code>If all went well, a file-like object is returned. </code></pre>
2
2009-11-02T12:19:08Z
[ "python", "urllib" ]
TypeError: cannot concatenate 'str' and 'instance' objects (python urllib)
1,660,954
<p>Writing a python program, and I came up with this error while using the <code>urllib.urlopen</code> function.</p> <pre><code>Traceback (most recent call last): File "ChurchScraper.py", line 58, in &lt;module&gt; html = GetAllChurchPages() File "ChurchScraper.py", line 48, in GetAllChurchPages CPs = CPs + urllib.url...
2
2009-11-02T12:14:58Z
1,660,991
<p>The problem is in this line: <code>CPs = CPs + urllib.urlopen(url)</code> I assume <code>CPs</code> is a string however <code>urllib.urlopen(url)</code> returns a file like object.</p> <p>If you want to join the contents of the file at <code>url</code> with <code>CPs</code> then you need to do something like this: ...
1
2009-11-02T12:21:41Z
[ "python", "urllib" ]
TypeError: cannot concatenate 'str' and 'instance' objects (python urllib)
1,660,954
<p>Writing a python program, and I came up with this error while using the <code>urllib.urlopen</code> function.</p> <pre><code>Traceback (most recent call last): File "ChurchScraper.py", line 58, in &lt;module&gt; html = GetAllChurchPages() File "ChurchScraper.py", line 48, in GetAllChurchPages CPs = CPs + urllib.url...
2
2009-11-02T12:14:58Z
1,661,000
<p>What is CPs? It looks like it is a string. urlopen will return an instance of a file-like object, not a string. See - <a href="http://docs.python.org/library/urllib.html" rel="nofollow">http://docs.python.org/library/urllib.html</a>.</p> <p>The error is not thrown from the urlopen, but because you are trying to con...
0
2009-11-02T12:23:45Z
[ "python", "urllib" ]
How to click a link in win32com.client IE?
1,661,107
<p>I'm using win32com.client to control an IE instance in Python. How can I click a link on a certain page (e.g. using navigate to link href isn't acceptable since it won't trigger referer sending)? Here is the base:</p> <pre><code>import random import time from win32com.client import Dispatch ie = Dispatch("Internet...
1
2009-11-02T12:44:23Z
1,661,290
<p>Have you tried using the <code>Headers</code> parameter of the <code>navigate</code> method to manually set the Referrer header to this "Referer: <a href="http://digg.com" rel="nofollow">http://digg.com</a>".</p>
1
2009-11-02T13:18:55Z
[ "python", "internet-explorer" ]
How to click a link in win32com.client IE?
1,661,107
<p>I'm using win32com.client to control an IE instance in Python. How can I click a link on a certain page (e.g. using navigate to link href isn't acceptable since it won't trigger referer sending)? Here is the base:</p> <pre><code>import random import time from win32com.client import Dispatch ie = Dispatch("Internet...
1
2009-11-02T12:44:23Z
1,772,699
<p>Turns out it has .click() method. Where is Captain Obvious when I need him?!</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms535173%28VS.85%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms535173%28VS.85%29.aspx</a></p>
1
2009-11-20T19:21:59Z
[ "python", "internet-explorer" ]
Why does my Python daemon hog all my CPU while sleeping?
1,661,210
<p>I'm using this recipe: <a href="http://code.activestate.com/recipes/278731/" rel="nofollow">http://code.activestate.com/recipes/278731/</a> on an Ubuntu server.</p> <p>I make a daemon instance like this:</p> <pre><code>class MyDaemon(Daemon): def run(self): while True: try: ...
0
2009-11-02T13:05:51Z
1,661,324
<p>The posted code looks correct. Your error must be somewhere else. Put a <code>print</code> statement into the loop to make sure that it does sleep.</p>
3
2009-11-02T13:24:55Z
[ "python", "cpu", "daemon" ]
Why does my Python daemon hog all my CPU while sleeping?
1,661,210
<p>I'm using this recipe: <a href="http://code.activestate.com/recipes/278731/" rel="nofollow">http://code.activestate.com/recipes/278731/</a> on an Ubuntu server.</p> <p>I make a daemon instance like this:</p> <pre><code>class MyDaemon(Daemon): def run(self): while True: try: ...
0
2009-11-02T13:05:51Z
1,661,428
<p>Turns out the daemon wasn't sleeping. It was looping without sleeping 30 seconds between every turn. Thanks Aaron.</p> <p>I fixed it by changing my code to this:</p> <pre><code>class MyDaemon(Daemon): def run(self): while True: try: do_my_data_processing() ...
0
2009-11-02T13:47:39Z
[ "python", "cpu", "daemon" ]
Check if object is file-like in Python
1,661,262
<p><a href="http://docs.python.org/library/stdtypes.html#bltin-file-objects">File-like objects</a> are objects in Python that behave like a real file, e.g. have a read() and a write method(), but have a different implementation. It is and realization of the <a href="http://en.wikipedia.org/wiki/Duck%5Ftyping">Duck Typi...
49
2009-11-02T13:13:57Z
1,661,270
<p>You can try and call the method then catch the exception:</p> <pre><code>try: fp.read() except AttributeError: raise something </code></pre> <p>If you only want a read and a write method you could do this:</p> <pre><code>if not (hasattr(fp, 'read') and hasattr(fp, 'write')): raise something </code></pr...
5
2009-11-02T13:15:15Z
[ "python", "file" ]
Check if object is file-like in Python
1,661,262
<p><a href="http://docs.python.org/library/stdtypes.html#bltin-file-objects">File-like objects</a> are objects in Python that behave like a real file, e.g. have a read() and a write method(), but have a different implementation. It is and realization of the <a href="http://en.wikipedia.org/wiki/Duck%5Ftyping">Duck Typi...
49
2009-11-02T13:13:57Z
1,661,326
<p>The dominant paradigm here is EAFP: easier to ask forgiveness than permission. Go ahead and use the file interface, then handle the resulting exception, or let them propagate to the caller.</p>
29
2009-11-02T13:25:38Z
[ "python", "file" ]
Check if object is file-like in Python
1,661,262
<p><a href="http://docs.python.org/library/stdtypes.html#bltin-file-objects">File-like objects</a> are objects in Python that behave like a real file, e.g. have a read() and a write method(), but have a different implementation. It is and realization of the <a href="http://en.wikipedia.org/wiki/Duck%5Ftyping">Duck Typi...
49
2009-11-02T13:13:57Z
1,661,354
<p>It is generally not good practice to have checks like this in your code at all unless you have special requirements. </p> <p>In Python the typing is dynamic, why do you feel need to check whether the object is file like, rather than just using it as if it was a file and handling the resulting error? </p> <p>Any ch...
26
2009-11-02T13:29:29Z
[ "python", "file" ]
Check if object is file-like in Python
1,661,262
<p><a href="http://docs.python.org/library/stdtypes.html#bltin-file-objects">File-like objects</a> are objects in Python that behave like a real file, e.g. have a read() and a write method(), but have a different implementation. It is and realization of the <a href="http://en.wikipedia.org/wiki/Duck%5Ftyping">Duck Typi...
49
2009-11-02T13:13:57Z
1,661,454
<p>As others have said you should generally avoid such checks. One exception is when the object might legitimately be different types and you want different behaviour depending on the type. The EAFP method doesn't always work here as an object could look like more than one type of duck!</p> <p>For example an initialis...
31
2009-11-02T13:52:57Z
[ "python", "file" ]
Check if object is file-like in Python
1,661,262
<p><a href="http://docs.python.org/library/stdtypes.html#bltin-file-objects">File-like objects</a> are objects in Python that behave like a real file, e.g. have a read() and a write method(), but have a different implementation. It is and realization of the <a href="http://en.wikipedia.org/wiki/Duck%5Ftyping">Duck Typi...
49
2009-11-02T13:13:57Z
1,668,561
<p>Under most circumstances, the best way to handle this is not to. If a method takes a file-like object, and it turns out the object it's passed isn't, the exception that gets raised when the method tries to use the object is not any less informative than any exception you might have raised explicitly.</p> <p>There'...
2
2009-11-03T16:42:42Z
[ "python", "file" ]
Check if object is file-like in Python
1,661,262
<p><a href="http://docs.python.org/library/stdtypes.html#bltin-file-objects">File-like objects</a> are objects in Python that behave like a real file, e.g. have a read() and a write method(), but have a different implementation. It is and realization of the <a href="http://en.wikipedia.org/wiki/Duck%5Ftyping">Duck Typi...
49
2009-11-02T13:13:57Z
6,867,901
<p>It's often useful to raise an error by checking a condition, when that error normally wouldn't be raised until much later on. This is especially true for the boundary between 'user-land' and 'api' code.</p> <p>You wouldn't place a metal detector at a police station on the exit door, you would place it at the entran...
9
2011-07-29T02:04:21Z
[ "python", "file" ]
Check if object is file-like in Python
1,661,262
<p><a href="http://docs.python.org/library/stdtypes.html#bltin-file-objects">File-like objects</a> are objects in Python that behave like a real file, e.g. have a read() and a write method(), but have a different implementation. It is and realization of the <a href="http://en.wikipedia.org/wiki/Duck%5Ftyping">Duck Typi...
49
2009-11-02T13:13:57Z
24,812,058
<p>For 3.1+, one of the following:</p> <pre><code>isinstance(something, io.TextIOBase) isinstance(something, io.BufferedIOBase) isinstance(something, io.RawIOBase) isinstance(something, io.IOBase) </code></pre> <p>For 2.x, "file-like object" is too vague a thing to check for, but the documentation for whatever functi...
9
2014-07-17T19:36:16Z
[ "python", "file" ]
Disable boto logging without modifying the boto files
1,661,275
<p>I am using the Boto library to talk to AWS. I want to disable logging. (Or redirect to /dev/null or other file). I cant find an obvious way to do this. I tried this, but that doesn't seem to help.</p> <pre><code>import boto boto.set_file_logger('boto', 'logs/boto.log') </code></pre> <p>This says it is possible, <a...
21
2009-11-02T13:15:48Z
1,667,019
<p>You could try</p> <pre><code>import logging logging.getLogger('boto').setLevel(logging.CRITICAL) </code></pre> <p>which will suppress all (other than CRITICAL) errors.</p> <p>Boto uses logging configuration files (e.g. <code>/etc/boto.cfg</code>, <code>~/.boto</code>) so see if you can configure it to your needs ...
45
2009-11-03T12:23:56Z
[ "python", "logging", "amazon-web-services", "boto" ]
Disable boto logging without modifying the boto files
1,661,275
<p>I am using the Boto library to talk to AWS. I want to disable logging. (Or redirect to /dev/null or other file). I cant find an obvious way to do this. I tried this, but that doesn't seem to help.</p> <pre><code>import boto boto.set_file_logger('boto', 'logs/boto.log') </code></pre> <p>This says it is possible, <a...
21
2009-11-02T13:15:48Z
36,184,329
<p>Better yet, disable <code>propagate</code> for boto:</p> <pre><code>import boto boto.set_file_logger('boto', 'logs/boto.log') logging.getLogger('boto').propagate = False </code></pre>
1
2016-03-23T17:00:21Z
[ "python", "logging", "amazon-web-services", "boto" ]
BeautifulSoup with Jython
1,661,310
<p>I just tried to run BeautifulSoup (3.1.0.1) with Jython (2.5.1) and I was amazed to see how much slower it was than CPython. Parsing a page (<a href="http://www.fixprotocol.org/specifications/fields/5000-5999" rel="nofollow">http://www.fixprotocol.org/specifications/fields/5000-5999</a>) with CPython took just under...
4
2009-11-02T13:22:53Z
1,665,542
<p>I can confirm similar findings.</p> <p>Intel Mac, OS X 10.6.1, Java 1.6.0_15 64-bit, Jython 2.5.1.</p> <p>Running your code with CPython 2.6.1 takes 0.1–0.2 seconds, but running it with Jython takes at least tens of seconds; I didn't wait more than 30. It also uses a lot of CPU.</p> <p>I tried Beautiful Soup 3....
6
2009-11-03T06:11:54Z
[ "python", "jython", "beautifulsoup" ]
App Engine: What is the fastest way to check if my datastore query returns any result?
1,661,421
<p>I like to check if there is any result for my datastore query in the Google App Engine Datastore. This is my query:</p> <pre><code>users = User.all() users.filter("hash =", current_user_hash) </code></pre> <p>What is the fastest and most elegant way to check if my query returns any result?</p> <p>PS: I know a way...
0
2009-11-02T13:46:08Z
1,661,563
<p><code>users.count(1)</code> is probably the fastest way to do this; <code>users.fetch(1)</code> would be the other way to accomplish this, but requires fetching an entire entity; depending on the size of that entity this could be fairly slow.</p>
2
2009-11-02T14:16:51Z
[ "python", "google-app-engine", "gae-datastore" ]
App Engine: What is the fastest way to check if my datastore query returns any result?
1,661,421
<p>I like to check if there is any result for my datastore query in the Google App Engine Datastore. This is my query:</p> <pre><code>users = User.all() users.filter("hash =", current_user_hash) </code></pre> <p>What is the fastest and most elegant way to check if my query returns any result?</p> <p>PS: I know a way...
0
2009-11-02T13:46:08Z
1,661,843
<p>If you also need to fetch the results, the most efficient way is to fetch the results with .fetch(), and then check if the list is nonempty. If you don't actually need the results, call .count(1).</p> <p>What you <em>shouldn't</em> do is call .count(1) if you also need the results - this'll require executing the qu...
4
2009-11-02T15:09:58Z
[ "python", "google-app-engine", "gae-datastore" ]
matplotlib for R user?
1,661,479
<p>I regularly make figures (the exploratory data analysis type) in R. I also program in Python and was wondering if there are features or concepts in matplotlib that would be worth learning. For instance, I am quite happy with R - but its image() function will produce large files with pixelated output, whereas Matlab'...
8
2009-11-02T14:01:35Z
1,662,207
<p>This is a tough one to answer. </p> <p>I recently switched some of my graphing workload from R to matplotlib. In my humble opinion, I find matplotlib's graphs to be prettier (better default colors, they look crisper and more modern). I also think matplotlib renders PNGs a whole lot better.</p> <p>The real motiv...
10
2009-11-02T16:14:29Z
[ "python", "matplotlib", "scipy", "data-visualization" ]
matplotlib for R user?
1,661,479
<p>I regularly make figures (the exploratory data analysis type) in R. I also program in Python and was wondering if there are features or concepts in matplotlib that would be worth learning. For instance, I am quite happy with R - but its image() function will produce large files with pixelated output, whereas Matlab'...
8
2009-11-02T14:01:35Z
1,662,225
<p>I think that the largest advantage is that matplotlib is based on Python, which you say you already know. So, this is one language less to learn. Just spend the time mastering Python, and you'll benefit both directly for the plotting task at hand and indirectly for your other Python needs. </p> <p>Besides, IMHO Pyt...
3
2009-11-02T16:19:23Z
[ "python", "matplotlib", "scipy", "data-visualization" ]
Creating an Infographic In Python
1,661,565
<p>I want to create a simple infographic in python. Matplotlib seems to have a lot of features but nothing that covers off my simple heatmap grid example.</p> <p>The infographic is a simple 5 x 5 grid with numbers inside ranging from 0 to 1. The grid squares would then be coloured in 0=white 1=blue 0.5 being a pale bl...
4
2009-11-02T14:17:04Z
1,661,841
<p><a href="http://www.cairographics.org/pycairo/" rel="nofollow">PyCairo</a> is your friend. Simple example:</p> <pre><code>from __future__ import with_statement import cairo img = cairo.ImageSurface(cairo.FORMAT_ARGB32,100,100) g = cairo.Context(img) for x in range(0,100,10): for y in range(0,100,10): g....
2
2009-11-02T15:09:39Z
[ "python", "grid", "matplotlib", "charts", "heatmap" ]
Creating an Infographic In Python
1,661,565
<p>I want to create a simple infographic in python. Matplotlib seems to have a lot of features but nothing that covers off my simple heatmap grid example.</p> <p>The infographic is a simple 5 x 5 grid with numbers inside ranging from 0 to 1. The grid squares would then be coloured in 0=white 1=blue 0.5 being a pale bl...
4
2009-11-02T14:17:04Z
1,661,891
<p>It depends what you need to do with the graph once you have it, <a href="http://matplotlib.sourceforge.net/index.html" rel="nofollow">Matplotlib</a> allows you to interactively show the graph on the screen, save it in either vector, pdf or bitmap format, and more.</p> <p>If you opt for this framework, <code>imshow<...
4
2009-11-02T15:19:15Z
[ "python", "grid", "matplotlib", "charts", "heatmap" ]
Creating an Infographic In Python
1,661,565
<p>I want to create a simple infographic in python. Matplotlib seems to have a lot of features but nothing that covers off my simple heatmap grid example.</p> <p>The infographic is a simple 5 x 5 grid with numbers inside ranging from 0 to 1. The grid squares would then be coloured in 0=white 1=blue 0.5 being a pale bl...
4
2009-11-02T14:17:04Z
1,662,449
<p>One possibility would be to generate SVG from python. You can view SVG in Firefox or Inkscape.</p> <p>Here's a quick-and-dirty example:</p> <pre><code>import random def square(x, y, value): r, g, b = value * 255, value * 255, 255 s = '&lt;rect x="%d" y="%d" width="1" height="1" style="fill:rgb(%d,%d,%d);"...
2
2009-11-02T16:59:26Z
[ "python", "grid", "matplotlib", "charts", "heatmap" ]
Finding the highest key
1,661,621
<p>I'm just confused about why my code would not work, here's the question and the code I have so far (the test run says my answer is wrong).</p> <p>Given the dictionary <code>d</code>, find the largest key in the dictionary and associate the corresponding value with the variable <code>val_of_max</code>. For example, ...
0
2009-11-02T14:29:55Z
1,661,632
<p>your code prints the <em>key</em> with the maximum value. What you want is:</p> <pre><code>d = {5:3, 4:1, 12:2, 14:9} val_of_max = d[max(d.keys())] print val_of_max </code></pre> <p>That is, you have to dereference the key to return the value.</p>
11
2009-11-02T14:31:32Z
[ "python", "dictionary" ]
Finding the highest key
1,661,621
<p>I'm just confused about why my code would not work, here's the question and the code I have so far (the test run says my answer is wrong).</p> <p>Given the dictionary <code>d</code>, find the largest key in the dictionary and associate the corresponding value with the variable <code>val_of_max</code>. For example, ...
0
2009-11-02T14:29:55Z
1,661,657
<p>this will do:</p> <pre><code>&gt;&gt;&gt; d = {5:3, 4:1, 12:2, 14:9} &gt;&gt;&gt; d[max(d)] 9 &gt;&gt;&gt; max(d) # just in case you're looking for this 14 </code></pre>
5
2009-11-02T14:35:49Z
[ "python", "dictionary" ]
Finding the highest key
1,661,621
<p>I'm just confused about why my code would not work, here's the question and the code I have so far (the test run says my answer is wrong).</p> <p>Given the dictionary <code>d</code>, find the largest key in the dictionary and associate the corresponding value with the variable <code>val_of_max</code>. For example, ...
0
2009-11-02T14:29:55Z
1,663,799
<p>Same code but remember to call the value of the key:</p> <pre><code>d = {5:3, 4:1, 12:2, 14:9} val_of_max = max(d.keys()) print d[val_of_max] </code></pre>
1
2009-11-02T21:25:19Z
[ "python", "dictionary" ]
Finding the highest key
1,661,621
<p>I'm just confused about why my code would not work, here's the question and the code I have so far (the test run says my answer is wrong).</p> <p>Given the dictionary <code>d</code>, find the largest key in the dictionary and associate the corresponding value with the variable <code>val_of_max</code>. For example, ...
0
2009-11-02T14:29:55Z
1,747,244
<pre><code>d= {5:3, 4:1, 12:2, 14:9} </code></pre> <p>To print the value associated with the largest key:</p> <pre><code>print max(d.iteritems())[1] </code></pre> <p>To print the key associated with the largest value:</p> <pre><code>import operator print max(d.iteritems(), key=operator.itemgetter(1))[0] </code></pr...
0
2009-11-17T07:54:14Z
[ "python", "dictionary" ]
Why doesn't Python's mmap work with large files?
1,661,986
<p>I am writing a module that amongst other things allows bitwise read access to files. The files can potentially be large (hundreds of GB) so I wrote a simple class that lets me treat the file like a string and hides all the seeking and reading.</p> <p>At the time I wrote my wrapper class I didn't know about the <a h...
39
2009-11-02T15:34:22Z
1,662,036
<p>You're setting the length parameter to zero, which means map in the entire file. On a 32 bit build, this won't be possible if the file length is more than 2GB (possibly 4GB).</p>
2
2009-11-02T15:42:06Z
[ "python", "performance", "memory", "mmap" ]
Why doesn't Python's mmap work with large files?
1,661,986
<p>I am writing a module that amongst other things allows bitwise read access to files. The files can potentially be large (hundreds of GB) so I wrote a simple class that lets me treat the file like a string and hides all the seeking and reading.</p> <p>At the time I wrote my wrapper class I didn't know about the <a h...
39
2009-11-02T15:34:22Z
1,662,149
<p>A 32-bit program and operating system can only address a maximum of 32 bits of memory i.e. 4GB. There are other factors that make the total even smaller; for example, Windows reserves between 0.5 and 2GB for hardware access, and of course your program is going to take some space as well.</p> <p><strong>Edit:</stron...
15
2009-11-02T16:01:05Z
[ "python", "performance", "memory", "mmap" ]
Why doesn't Python's mmap work with large files?
1,661,986
<p>I am writing a module that amongst other things allows bitwise read access to files. The files can potentially be large (hundreds of GB) so I wrote a simple class that lets me treat the file like a string and hides all the seeking and reading.</p> <p>At the time I wrote my wrapper class I didn't know about the <a h...
39
2009-11-02T15:34:22Z
1,662,411
<p>From IEEE 1003.1:</p> <blockquote> <p>The mmap() function shall establish a mapping between a process' address space and a file, shared memory object, or [TYM] typed memory object.</p> </blockquote> <p>It needs all the virtual address space because that's exactly what <code>mmap()</code> <em>does</em>....
34
2009-11-02T16:52:46Z
[ "python", "performance", "memory", "mmap" ]
Why doesn't Python's mmap work with large files?
1,661,986
<p>I am writing a module that amongst other things allows bitwise read access to files. The files can potentially be large (hundreds of GB) so I wrote a simple class that lets me treat the file like a string and hides all the seeking and reading.</p> <p>At the time I wrote my wrapper class I didn't know about the <a h...
39
2009-11-02T15:34:22Z
1,662,616
<p>The point you are missing is that mmap is a memory mapping function that maps a file into memory for arbitrary access across the requested data range by any means.</p> <p>What you are looking for sounds more like some sort of a data window class that presents an api allowing you to look at small windows of a large ...
6
2009-11-02T17:34:48Z
[ "python", "performance", "memory", "mmap" ]
Why doesn't Python's mmap work with large files?
1,661,986
<p>I am writing a module that amongst other things allows bitwise read access to files. The files can potentially be large (hundreds of GB) so I wrote a simple class that lets me treat the file like a string and hides all the seeking and reading.</p> <p>At the time I wrote my wrapper class I didn't know about the <a h...
39
2009-11-02T15:34:22Z
1,662,646
<p>You ask the OS to map the entire file in a memory range. It won't be read until you trigger page faults by reading/writing, but it still needs to make sure the entire range is available to your process, and if that range is too big, there will be difficulties.</p>
1
2009-11-02T17:40:28Z
[ "python", "performance", "memory", "mmap" ]
Why doesn't Python's mmap work with large files?
1,661,986
<p>I am writing a module that amongst other things allows bitwise read access to files. The files can potentially be large (hundreds of GB) so I wrote a simple class that lets me treat the file like a string and hides all the seeking and reading.</p> <p>At the time I wrote my wrapper class I didn't know about the <a h...
39
2009-11-02T15:34:22Z
1,663,603
<p>the mmap module provides all the tools you need to poke around in your large file, but due to the limitations other folks have mentioned, you can't map it <strong><em>all at once</em></strong>. You can map a good sized chunk at once, do some processing and then unmap that and map another. the key arguments to the ...
8
2009-11-02T20:48:42Z
[ "python", "performance", "memory", "mmap" ]
Why doesn't Python's mmap work with large files?
1,661,986
<p>I am writing a module that amongst other things allows bitwise read access to files. The files can potentially be large (hundreds of GB) so I wrote a simple class that lets me treat the file like a string and hides all the seeking and reading.</p> <p>At the time I wrote my wrapper class I didn't know about the <a h...
39
2009-11-02T15:34:22Z
1,666,666
<p>Sorry to answer my own question, but I think the real problem I had was not realising that mmap was a standard POSIX system call with particular characterisatations and limitations and that the Python mmap is supposed just to expose its functionality.</p> <p>The Python documentation doesn't mention the POSIX mmap a...
16
2009-11-03T11:04:31Z
[ "python", "performance", "memory", "mmap" ]
python's datetime and end of the month
1,662,140
<p>How to create datetime object representing the very last moment of the current month ?</p>
4
2009-11-02T15:58:45Z
1,662,154
<p>Use a simple trick: Set the date to the first of the <em>next</em> month and then subtract one second/hour/day/as much as you need.</p>
14
2009-11-02T16:02:10Z
[ "python", "datetime" ]
python's datetime and end of the month
1,662,140
<p>How to create datetime object representing the very last moment of the current month ?</p>
4
2009-11-02T15:58:45Z
1,663,240
<pre><code>import datetime def eom(dt): sometime_next_month= dt.replace(day=1) + datetime.timedelta(days=31) start_of_next_month= sometime_next_month.replace(day=1,hour=0,minute=0,second=0) return start_of_next_month - datetime.timedelta(seconds=1) &gt;&gt;&gt; eom(datetime.datetime(1972, 2, 1, 23, 50, 5...
1
2009-11-02T19:41:05Z
[ "python", "datetime" ]
python's datetime and end of the month
1,662,140
<p>How to create datetime object representing the very last moment of the current month ?</p>
4
2009-11-02T15:58:45Z
24,930,016
<pre><code>selected_date = date(some_year, some_month, some_day) if selected_date.month == 12: # December last_day_selected_month = date(selected_date.year, selected_date.month, 31) else: last_day_selected_month = date(selected_date.year, selected_date.month + 1, 1) - timedelta(days=1) </code></pre> <p>wher...
0
2014-07-24T09:30:19Z
[ "python", "datetime" ]
How can I capture the return value of shutil.copy() in Python ( on DOS )?
1,662,261
<p>I am trying to record the success or failure of a number of copy commands, into a log file. I'm using <code>shutil.copy()</code> - e.g.</p> <pre><code>str_list.append(getbitmapsfrom) game.bigbitmap = "i doubt this is there.bmp" str_list.append(game.bigbitmap) source = '\\'.join(str_list) shutil.copy(source, newbig...
8
2009-11-02T16:26:01Z
1,662,290
<p>You will rarely see C-like return codes in Python, errors are signalled by exceptions instead.</p> <p>The correct way of logging result is:</p> <pre><code>try: shutil.copy(src, dest) except EnvironmentError: print "Error happended" else: print "OK" </code></pre>
4
2009-11-02T16:30:20Z
[ "python", "exception", "logging" ]
How can I capture the return value of shutil.copy() in Python ( on DOS )?
1,662,261
<p>I am trying to record the success or failure of a number of copy commands, into a log file. I'm using <code>shutil.copy()</code> - e.g.</p> <pre><code>str_list.append(getbitmapsfrom) game.bigbitmap = "i doubt this is there.bmp" str_list.append(game.bigbitmap) source = '\\'.join(str_list) shutil.copy(source, newbig...
8
2009-11-02T16:26:01Z
1,662,314
<p>You'll want to look at the <a href="http://docs.python.org/tutorial/errors.html#exceptions">exceptions section</a> of the <a href="http://docs.python.org/tutorial/index.html">Python tutorial</a>. In the case of shutil.copy() not finding one of the arguments, an IOError exception will be raised. You can get the mes...
13
2009-11-02T16:33:44Z
[ "python", "exception", "logging" ]
How can I capture the return value of shutil.copy() in Python ( on DOS )?
1,662,261
<p>I am trying to record the success or failure of a number of copy commands, into a log file. I'm using <code>shutil.copy()</code> - e.g.</p> <pre><code>str_list.append(getbitmapsfrom) game.bigbitmap = "i doubt this is there.bmp" str_list.append(game.bigbitmap) source = '\\'.join(str_list) shutil.copy(source, newbig...
8
2009-11-02T16:26:01Z
4,518,880
<pre><code>try: shutil.copy(archivo, dirs) except EnvironmentError: print "Error en el copiado" escritura = "no se pudo copiar %s a %s \n" % (archivo, dirs) else: print "Copiado con exito" escritura = "%s --&gt; %s \n" % (archivo, dirs) finally: log = open("/tmp/errorcreararboldats.log", "a") ...
1
2010-12-23T12:47:51Z
[ "python", "exception", "logging" ]
problem with the new lines when I use toprettyxml()
1,662,351
<p>I'm currently using the toprettyxml() function of the xml.dom module in a python script and I have some troubles with the newlines. If don't use the newl parameter or if I use toprettyxml(newl='\n') actually it displays several new lines instead of only one.</p> <p>For instance </p> <pre><code>f = open(filename, '...
9
2009-11-02T16:40:24Z
1,662,727
<p>Are you viewing the resulting file on Windows? If so, try using <code>toprettyxml(newl='\r\n')</code>.</p>
0
2009-11-02T17:57:20Z
[ "python", "xml" ]
problem with the new lines when I use toprettyxml()
1,662,351
<p>I'm currently using the toprettyxml() function of the xml.dom module in a python script and I have some troubles with the newlines. If don't use the newl parameter or if I use toprettyxml(newl='\n') actually it displays several new lines instead of only one.</p> <p>For instance </p> <pre><code>f = open(filename, '...
9
2009-11-02T16:40:24Z
1,983,039
<p>If you don't mind installing new packages, try beautifulsoup. I had very good experiences with its <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#Parsing%20XML" rel="nofollow">xml prettyfier</a>.</p>
1
2009-12-30T23:20:38Z
[ "python", "xml" ]
problem with the new lines when I use toprettyxml()
1,662,351
<p>I'm currently using the toprettyxml() function of the xml.dom module in a python script and I have some troubles with the newlines. If don't use the newl parameter or if I use toprettyxml(newl='\n') actually it displays several new lines instead of only one.</p> <p>For instance </p> <pre><code>f = open(filename, '...
9
2009-11-02T16:40:24Z
2,455,250
<p><code>toprettyxml()</code> is quite awful. It is not a matter of Windows and '\r\n'. Trying any string as the <code>newl</code>parameter shows that too many lines are being added. Not only that, but other blanks (that may cause you problems when a machine reads the xml) are also added.</p> <p>Some workarounds avail...
9
2010-03-16T14:40:13Z
[ "python", "xml" ]
problem with the new lines when I use toprettyxml()
1,662,351
<p>I'm currently using the toprettyxml() function of the xml.dom module in a python script and I have some troubles with the newlines. If don't use the newl parameter or if I use toprettyxml(newl='\n') actually it displays several new lines instead of only one.</p> <p>For instance </p> <pre><code>f = open(filename, '...
9
2009-11-02T16:40:24Z
23,224,135
<p><code>toprettyxml(newl='')</code> works for me on Windows.</p>
1
2014-04-22T15:42:57Z
[ "python", "xml" ]
problem with the new lines when I use toprettyxml()
1,662,351
<p>I'm currently using the toprettyxml() function of the xml.dom module in a python script and I have some troubles with the newlines. If don't use the newl parameter or if I use toprettyxml(newl='\n') actually it displays several new lines instead of only one.</p> <p>For instance </p> <pre><code>f = open(filename, '...
9
2009-11-02T16:40:24Z
39,984,422
<p>I found another great solution :</p> <pre><code>f = open(filename, 'w') dom_string = dom1.toprettyxml(encoding='UTF-8') dom_string = os.linesep.join([s for s in dom_string.splitlines() if s.strip()]) f.write(dom_string) f.close() </code></pre> <p>Above solution basically removes the unwanted newlines from the dom_...
1
2016-10-11T18:40:56Z
[ "python", "xml" ]
xml.etree.ElementTree equivalent in Java
1,662,375
<p>I've been doing quite a bit of simple XML-processing in python and grown to like the <a href="http://docs.python.org/library/xml.etree.elementtree.html#module-xml.etree.ElementTree">ElementTree</a> way of doing things.</p> <p>Is there something similar and as easy to use in Java? I find the DOM model a bit cumbers...
10
2009-11-02T16:44:53Z
1,662,458
<p>You might look into the following alternatives:</p> <p><a href="http://www.dom4j.org/" rel="nofollow">dom4j</a></p> <p><a href="http://www.xom.nu/" rel="nofollow">xom</a></p> <p><a href="http://www.jdom.org/" rel="nofollow">jdom</a></p> <p>Since I never used ElementTree I don't know wich one is the closest. If y...
1
2009-11-02T17:01:27Z
[ "java", "python", "xml" ]
xml.etree.ElementTree equivalent in Java
1,662,375
<p>I've been doing quite a bit of simple XML-processing in python and grown to like the <a href="http://docs.python.org/library/xml.etree.elementtree.html#module-xml.etree.ElementTree">ElementTree</a> way of doing things.</p> <p>Is there something similar and as easy to use in Java? I find the DOM model a bit cumbers...
10
2009-11-02T16:44:53Z
1,662,507
<p>We find XOM (<a href="http://www.xom.nu" rel="nofollow">http://www.xom.nu</a>) to provide simple subclassable Element functionality.</p>
1
2009-11-02T17:11:17Z
[ "java", "python", "xml" ]
xml.etree.ElementTree equivalent in Java
1,662,375
<p>I've been doing quite a bit of simple XML-processing in python and grown to like the <a href="http://docs.python.org/library/xml.etree.elementtree.html#module-xml.etree.ElementTree">ElementTree</a> way of doing things.</p> <p>Is there something similar and as easy to use in Java? I find the DOM model a bit cumbers...
10
2009-11-02T16:44:53Z
1,662,607
<p>To be honest, all XML APIs in Java suck, you just can vary the level of suckage you push yourself into which may turn horrible/slow to manageable/decent to even suprisingly OK at times.</p> <p>This all mostly stems from the fact that Java APIs try to be as <a href="http://www.w3.org/DOM/" rel="nofollow">W3C DOM</a>...
5
2009-11-02T17:32:35Z
[ "java", "python", "xml" ]
xml.etree.ElementTree equivalent in Java
1,662,375
<p>I've been doing quite a bit of simple XML-processing in python and grown to like the <a href="http://docs.python.org/library/xml.etree.elementtree.html#module-xml.etree.ElementTree">ElementTree</a> way of doing things.</p> <p>Is there something similar and as easy to use in Java? I find the DOM model a bit cumbers...
10
2009-11-02T16:44:53Z
1,663,217
<p>It is true the Java XML APIs are not the greatest in terms of usability. My prefered options would be <a href="http://www.xom.nu/" rel="nofollow">XOM</a>, <a href="http://www.jdom.org/" rel="nofollow">JDOM</a> then the built in <a href="http://en.wikipedia.org/wiki/JAXP" rel="nofollow">JAXP</a> in that order. There ...
0
2009-11-02T19:36:49Z
[ "java", "python", "xml" ]
How to generate a choicelist from all ImageSpecs
1,662,520
<p>I want to generate a choicelist for all specs that inherit from <code>imagekit.specs.ImageSpec</code>.</p> <p>The idea is to allow users of the admin interface to select an ImageSpec to add to a picture.</p> <p>i.e:</p> <pre><code>class Display(ImageSpec): pre_cache = True increment_count = True proce...
1
2009-11-02T17:13:03Z
1,662,631
<p>Well, something like the following will get you a list of all the ImageSpec subclasses defined in the file:</p> <pre><code>def subclassfilter(x, baseclass): return x is not baseclass and isinstance(x, type) and issubclass(x, baseclass) subclasses = [c for c in locals().values() if subclassfilter(c, ImageSpec)]...
2
2009-11-02T17:37:25Z
[ "python", "django", "imagekit", "django-imagekit" ]
Running Python's IDLE in windows
1,662,576
<p>I messed up my IDLE shortcut. What is the way to start IDLE from the cmd.exe shell in Windows?</p>
7
2009-11-02T17:22:42Z
1,662,586
<p>On my system, running <code>C:\Python26\lib\idlelib\idle.py</code> launches idle from the command prompt. Obviously you will need to adjust your path if your main Python directory isn't <code>C:\Python26\</code>.</p> <p>It looks like you could also launch it via <code>idle.pyw</code> or <code>idle.bat</code> in th...
14
2009-11-02T17:25:56Z
[ "python", "windows", "python-idle" ]
Running Python's IDLE in windows
1,662,576
<p>I messed up my IDLE shortcut. What is the way to start IDLE from the cmd.exe shell in Windows?</p>
7
2009-11-02T17:22:42Z
12,381,743
<p>You can just add a path in your Environment variables tab in My Computer Properties --> Advanced as <code>c:\Python27\Lib\idlelib</code>. After adding this path just write <code>idle.pyw</code> in <code>cmd</code> whenever you want to run IDLE. </p> <p>Just make sure you replace the folder name with whatever direc...
2
2012-09-12T05:32:04Z
[ "python", "windows", "python-idle" ]
OCaml question:How to construct a formated string in pythonic way
1,662,853
<p>All of these start from a simple idea: How to write python-style formatted string in ocaml.</p> <p>pythoners could init a string as:</p> <pre><code>str = "this var: %s" % this_var str2 = "this: %s; that: %s" % (this_var, that_var) </code></pre> <p>but ocaml's formatted string code as :</p> <pre><code>let str = P...
2
2009-11-02T18:24:59Z
1,662,989
<p>(1) I don't think there's a good way to do it that is going to be nicer than using <code>Printf.sprintf</code> directly. I mean, you can extend what you've already come up with:</p> <pre><code>let (%) = Printf.sprintf let str3 = ("this: %s; that: %s; other: %s" % this_var) that_var other_var </code></pre> <p>which...
5
2009-11-02T18:55:23Z
[ "ocaml", "python" ]
OCaml question:How to construct a formated string in pythonic way
1,662,853
<p>All of these start from a simple idea: How to write python-style formatted string in ocaml.</p> <p>pythoners could init a string as:</p> <pre><code>str = "this var: %s" % this_var str2 = "this: %s; that: %s" % (this_var, that_var) </code></pre> <p>but ocaml's formatted string code as :</p> <pre><code>let str = P...
2
2009-11-02T18:24:59Z
1,666,122
<p>Why would one want to replace statically checked sprintf with some dynamic formatting? OCaml's Printf is both compact in usage and safe at runtime. Compare that to C printf which is compact but unsafe and C++ streams which are safe but verbose. Python's format is no way better than C printf (except that you get exc...
2
2009-11-03T09:06:48Z
[ "ocaml", "python" ]
OCaml question:How to construct a formated string in pythonic way
1,662,853
<p>All of these start from a simple idea: How to write python-style formatted string in ocaml.</p> <p>pythoners could init a string as:</p> <pre><code>str = "this var: %s" % this_var str2 = "this: %s; that: %s" % (this_var, that_var) </code></pre> <p>but ocaml's formatted string code as :</p> <pre><code>let str = P...
2
2009-11-02T18:24:59Z
2,753,893
<blockquote> <p>If Ocaml cannot dynamically generate some string as format6 str and pass it to sprintf? for code:</p> <p><code>let s = "%s" in Printf.sprintf s "hello"</code></p> </blockquote> <p>What if we bypass the typing system...</p> <pre><code>external string_to_format : string -&gt; ('a, 'b, 'c, 'd...
-1
2010-05-02T15:16:18Z
[ "ocaml", "python" ]
OCaml question:How to construct a formated string in pythonic way
1,662,853
<p>All of these start from a simple idea: How to write python-style formatted string in ocaml.</p> <p>pythoners could init a string as:</p> <pre><code>str = "this var: %s" % this_var str2 = "this: %s; that: %s" % (this_var, that_var) </code></pre> <p>but ocaml's formatted string code as :</p> <pre><code>let str = P...
2
2009-11-02T18:24:59Z
3,931,261
<p>You should check out OCaml Batteries Included's extended/extensible <code>printf</code>. I have the feeling that you can do what you want with it.</p>
1
2010-10-14T08:12:02Z
[ "ocaml", "python" ]
Python on windows7 intel 64bit
1,662,920
<p>I've been messing around with Python over the weekend and find myself pretty much back at where I started. </p> <p>I've specifically been having issues with easy_install and nltk giving me errors about not finding packages, etc. </p> <p>I've tried both Python 2.6 and Python 3.1. </p> <p>I think part of the proble...
4
2009-11-02T18:43:00Z
1,662,955
<p>The most popular 64-bit mode for "86-oid" processor is commonly known as AMD64 because AMD first came up with it (Intel at that time was pushing Itanium instead, and that didn't really catch fire -- it's still around but I don't even know if Win7 supports it); Intel later had to imitate that mode to get into the mas...
13
2009-11-02T18:48:57Z
[ "python", "installation" ]
How do I loop through all levels of a data structure to extract all data when I don't know how many levels there will be?
1,663,077
<p>I need to extract data from a structure and put it into a list, but I don't know how many levels the structure has.</p> <p>For each level, I can call <code>level.children()</code>, if there are no levels below the current one, it returns <code>[]</code>, if there are, it returns <code>[object, object, ...]</code>, ...
2
2009-11-02T19:13:27Z
1,663,114
<p>You're describing <a href="http://en.wikipedia.org/wiki/Recursion%5F%28computer%5Fscience%29" rel="nofollow">recursion</a>, but I'm guessing there are <a href="http://codespeak.net/lxml/" rel="nofollow">better</a>, <a href="http://pyxml.sourceforge.net/topics/howto/xml-howto.html" rel="nofollow">ways</a>, <a href="h...
10
2009-11-02T19:17:55Z
[ "python", "xml", "data-structures", "loops" ]
How do I loop through all levels of a data structure to extract all data when I don't know how many levels there will be?
1,663,077
<p>I need to extract data from a structure and put it into a list, but I don't know how many levels the structure has.</p> <p>For each level, I can call <code>level.children()</code>, if there are no levels below the current one, it returns <code>[]</code>, if there are, it returns <code>[object, object, ...]</code>, ...
2
2009-11-02T19:13:27Z
1,663,137
<p>The concept you're looking to use here is called "<a href="http://www.freenetpages.co.uk/hp/alan.gauld/tutrecur.htm" rel="nofollow">Recursion</a>".</p>
5
2009-11-02T19:21:36Z
[ "python", "xml", "data-structures", "loops" ]
What may be the problem (Django views)...?
1,663,082
<p>I am writing a GUI application using <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29" rel="nofollow">Django</a> 1.1.1.</p> <p>This is the views.py:</p> <pre><code>from django.http import HttpResponse def mainpage(request): f=open('pages/index.html','r').readlines() out='''''' for ...
0
2009-11-02T19:14:07Z
1,663,206
<p>If you require just simple output of html page, this can be achieved by simply putting following into urls.py:</p> <p><code>(r'^$', 'direct_to_template', {'template': 'index.html'})</code></p>
3
2009-11-02T19:33:12Z
[ "python", "django" ]
What may be the problem (Django views)...?
1,663,082
<p>I am writing a GUI application using <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29" rel="nofollow">Django</a> 1.1.1.</p> <p>This is the views.py:</p> <pre><code>from django.http import HttpResponse def mainpage(request): f=open('pages/index.html','r').readlines() out='''''' for ...
0
2009-11-02T19:14:07Z
1,663,288
<p>For the root page don't use <code>r'^/$'</code>, just <code>r'^$'</code>, because this <code>^</code> means "start of the string after domain AND SLASH" (after <code>127.0.0.1/</code> if you run app on localhost). That's why <code>localhost:8080//</code> works for you.</p> <p>Edit: check yours paths too. Do you hav...
1
2009-11-02T19:50:37Z
[ "python", "django" ]
What may be the problem (Django views)...?
1,663,082
<p>I am writing a GUI application using <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29" rel="nofollow">Django</a> 1.1.1.</p> <p>This is the views.py:</p> <pre><code>from django.http import HttpResponse def mainpage(request): f=open('pages/index.html','r').readlines() out='''''' for ...
0
2009-11-02T19:14:07Z
1,663,316
<p>Your actual code in the view is incorrect. Here is my fixed up version:</p> <pre><code>from django.http import HttpResponse def mainpage(request): lines=open('loader/pages/index.html','r').readlines() out='''''' for line in lines: out+=line print out return HttpResponse(out) </code></p...
0
2009-11-02T19:56:05Z
[ "python", "django" ]
What may be the problem (Django views)...?
1,663,082
<p>I am writing a GUI application using <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29" rel="nofollow">Django</a> 1.1.1.</p> <p>This is the views.py:</p> <pre><code>from django.http import HttpResponse def mainpage(request): f=open('pages/index.html','r').readlines() out='''''' for ...
0
2009-11-02T19:14:07Z
1,663,324
<p>Got it! ;)</p> <p>It seems that the mainpage function actually runs on the urls.py (as it is imported from the views.py) file so the path I must provide is gui/pages/index.html. I still had a problem, 'type object not iterable', but the following worked:</p> <pre><code>def mainpage(request): f=open('gui/pages/...
0
2009-11-02T19:56:37Z
[ "python", "django" ]
What should I install in order to be able to use GTK in Python on Ubuntu?
1,663,109
<p>In my source code I have:</p> <pre><code>import gtk </code></pre> <p>But when I run the script with python3 script.py command I get the following error. What package should I install to get it working?</p> <p>Edit: my bad. here is the error:</p> <pre><code>ImportError: No module named gtk </code></pre> <p>Edit2...
0
2009-11-02T19:16:48Z
1,663,145
<p>PyGtk doesn't support Python 3 yet. You might want to use Python 2.x and then you will need to install the <code>python-gtk2</code> package.</p>
1
2009-11-02T19:22:23Z
[ "python" ]
What should I install in order to be able to use GTK in Python on Ubuntu?
1,663,109
<p>In my source code I have:</p> <pre><code>import gtk </code></pre> <p>But when I run the script with python3 script.py command I get the following error. What package should I install to get it working?</p> <p>Edit: my bad. here is the error:</p> <pre><code>ImportError: No module named gtk </code></pre> <p>Edit2...
0
2009-11-02T19:16:48Z
1,664,260
<p>There is no big difference between how Python 3 and Python 2.6 handle unicode and international text, technically. The biggest difference is what the classes are called and what the defaults are.</p> <p>So if you in Python 3 write:</p> <pre><code>s = "Grüß Gott" </code></pre> <p>you take this in Python 2.x:</p>...
0
2009-11-02T22:55:30Z
[ "python" ]
Using Python to check words
1,663,133
<p>I'm stuck on a simple problem. I've got a dictionary of words in the English language, and a sample text that is to be checked. I've got to check every word in the sample against the dictionary, and the code I'm using is wrong.</p> <pre><code>for word in checkList: # iterates through every word in the sample ...
0
2009-11-02T19:21:09Z
1,663,171
<p>Clearly "word not in refDict" always evaluates to True. This is probably because the contents of refDict or checkList are not what you think they are. Are they both tuples or lists of strings?</p>
2
2009-11-02T19:26:40Z
[ "python" ]
Using Python to check words
1,663,133
<p>I'm stuck on a simple problem. I've got a dictionary of words in the English language, and a sample text that is to be checked. I've got to check every word in the sample against the dictionary, and the code I'm using is wrong.</p> <pre><code>for word in checkList: # iterates through every word in the sample ...
0
2009-11-02T19:21:09Z
1,663,199
<p>Consider stripping your words of any whitespace that might be there, and changing all the words of both sets to the same case. Like this:</p> <pre><code>word.strip().lower() </code></pre> <p>That way you can make sure you're comparing apples to apples.</p>
5
2009-11-02T19:32:29Z
[ "python" ]
Using Python to check words
1,663,133
<p>I'm stuck on a simple problem. I've got a dictionary of words in the English language, and a sample text that is to be checked. I've got to check every word in the sample against the dictionary, and the code I'm using is wrong.</p> <pre><code>for word in checkList: # iterates through every word in the sample ...
0
2009-11-02T19:21:09Z
1,663,203
<p>The snippet you have is functional. See for example</p> <pre><code>&gt;&gt;&gt; refDict = {'alpha':1, 'bravo':2, 'charlie':3, 'delta':4} &gt;&gt;&gt; s = 'he said bravo to charlie O\'Brian and jack Alpha' &gt;&gt;&gt; for word in s.split(): ... if word not in refDict: ... print(repr(word)) # by temporaril...
6
2009-11-02T19:33:03Z
[ "python" ]
Using Python to check words
1,663,133
<p>I'm stuck on a simple problem. I've got a dictionary of words in the English language, and a sample text that is to be checked. I've got to check every word in the sample against the dictionary, and the code I'm using is wrong.</p> <pre><code>for word in checkList: # iterates through every word in the sample ...
0
2009-11-02T19:21:09Z
1,663,293
<p>The code you have would work if the keys in <code>refDict</code> are the correctly spelt words. If the correctly spelt words are the values in your dict then you need something like this:</p> <pre><code>for word in checkList: if word not in refDict.values(): print word </code></pre> <p>Is there a reaso...
1
2009-11-02T19:51:04Z
[ "python" ]
Using Python to check words
1,663,133
<p>I'm stuck on a simple problem. I've got a dictionary of words in the English language, and a sample text that is to be checked. I've got to check every word in the sample against the dictionary, and the code I'm using is wrong.</p> <pre><code>for word in checkList: # iterates through every word in the sample ...
0
2009-11-02T19:21:09Z
1,663,853
<p>Are the words in the refDict the keys or the values? </p> <p>Your code will only see keys: e.g.:</p> <pre><code>refDict = { 'w':'x', 'y':'z' } for word in [ 'w','x','y','z' ]: if word not in refDict: print word </code></pre> <p>prints:</p> <pre><code>x z </code></pre> <p>Othewise you want;</p> <p>if word ...
0
2009-11-02T21:32:42Z
[ "python" ]
Using Python to check words
1,663,133
<p>I'm stuck on a simple problem. I've got a dictionary of words in the English language, and a sample text that is to be checked. I've got to check every word in the sample against the dictionary, and the code I'm using is wrong.</p> <pre><code>for word in checkList: # iterates through every word in the sample ...
0
2009-11-02T19:21:09Z
1,663,915
<p>Your <code>refDict</code> is probably wrong. The <code>in</code> keyword checks if the value is in the keys of the dictionary. I believe you've put your words in as values.</p> <p>I'd propose using a <code>set</code> instead of a dictionary.</p> <pre><code>knownwords = set("dog", "cat") knownwords.add("apple") te...
0
2009-11-02T21:42:58Z
[ "python" ]