title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
ValueError: invalid literal for int() with base 10
1,241,395
<p>I received the following error when trying to retrieve data using <a href="http://en.wikipedia.org/wiki/Google%5FApp%5FEngine" rel="nofollow">Google App Engine</a> from a single entry to a single page e.g. foobar.com/page/1 would show all the data from id 1:</p> <pre><code>ValueError: invalid literal for int() with base 10 </code></pre> <p>Here are the files:</p> <p><strong>Views.py</strong></p> <pre><code>class One(webapp.RequestHandler): def get(self, id): id = models.Page.get_by_id(int(str(self.request.get("id")))) page_query = models.Page.get(db.Key.from_path('Page', id)) pages = page_query template_values = { 'pages': pages, } path = os.path.join(os.path.dirname(__file__), 'template/list.html') self.response.out.write(template.render(path, template_values)) </code></pre> <p><strong>Urls.py</strong>:</p> <pre><code>(r'/browse/(\d+)/', One), </code></pre> <p><strong>Error:</strong></p> <pre> Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 501, in __call__ handler.get(*groups) File "/Volumes/foobar/views.py", line 72, in get id = models.Page.get_by_id(int(str(self.request.get("id")))) ValueError: invalid literal for int() with base 10: '' </pre>
3
2009-08-06T20:56:44Z
1,243,466
<p>I'm not quite sure what you're trying to achieve here. The first line:</p> <pre><code> id = models.Page.get_by_id(int(str(self.request.get("id")))) </code></pre> <p>returns a Page object with an ID fetched from the query string. To make it work with the passed in argument, change it to:</p> <pre><code> id = models.Page.get_by_id(int(id)) </code></pre> <p>Odder is the second line:</p> <pre><code> page_query = models.Page.get(db.Key.from_path('Page', id)) </code></pre> <p>This does not return a query - it returns a page object, and if you replace 'id' with 'int(id)' does precisely the same thing as the first line. What are you trying to achieve here?</p>
1
2009-08-07T07:42:09Z
[ "python", "google-app-engine" ]
ValueError: invalid literal for int() with base 10
1,241,395
<p>I received the following error when trying to retrieve data using <a href="http://en.wikipedia.org/wiki/Google%5FApp%5FEngine" rel="nofollow">Google App Engine</a> from a single entry to a single page e.g. foobar.com/page/1 would show all the data from id 1:</p> <pre><code>ValueError: invalid literal for int() with base 10 </code></pre> <p>Here are the files:</p> <p><strong>Views.py</strong></p> <pre><code>class One(webapp.RequestHandler): def get(self, id): id = models.Page.get_by_id(int(str(self.request.get("id")))) page_query = models.Page.get(db.Key.from_path('Page', id)) pages = page_query template_values = { 'pages': pages, } path = os.path.join(os.path.dirname(__file__), 'template/list.html') self.response.out.write(template.render(path, template_values)) </code></pre> <p><strong>Urls.py</strong>:</p> <pre><code>(r'/browse/(\d+)/', One), </code></pre> <p><strong>Error:</strong></p> <pre> Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 501, in __call__ handler.get(*groups) File "/Volumes/foobar/views.py", line 72, in get id = models.Page.get_by_id(int(str(self.request.get("id")))) ValueError: invalid literal for int() with base 10: '' </pre>
3
2009-08-06T20:56:44Z
3,199,722
<p>I had a similar error in one of my code. I just did a simple hack of converting it into decimal first and later converting it into int <code>int(Decimal(str(self.request.get("id"))))</code> </p>
0
2010-07-07T23:44:23Z
[ "python", "google-app-engine" ]
ValueError: invalid literal for int() with base 10
1,241,395
<p>I received the following error when trying to retrieve data using <a href="http://en.wikipedia.org/wiki/Google%5FApp%5FEngine" rel="nofollow">Google App Engine</a> from a single entry to a single page e.g. foobar.com/page/1 would show all the data from id 1:</p> <pre><code>ValueError: invalid literal for int() with base 10 </code></pre> <p>Here are the files:</p> <p><strong>Views.py</strong></p> <pre><code>class One(webapp.RequestHandler): def get(self, id): id = models.Page.get_by_id(int(str(self.request.get("id")))) page_query = models.Page.get(db.Key.from_path('Page', id)) pages = page_query template_values = { 'pages': pages, } path = os.path.join(os.path.dirname(__file__), 'template/list.html') self.response.out.write(template.render(path, template_values)) </code></pre> <p><strong>Urls.py</strong>:</p> <pre><code>(r'/browse/(\d+)/', One), </code></pre> <p><strong>Error:</strong></p> <pre> Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 501, in __call__ handler.get(*groups) File "/Volumes/foobar/views.py", line 72, in get id = models.Page.get_by_id(int(str(self.request.get("id")))) ValueError: invalid literal for int() with base 10: '' </pre>
3
2009-08-06T20:56:44Z
36,850,201
<p>The error (as I'm sure that you know - or should know as it seems you have come very far in programming) means that you are typing/reading an invalid literal (invalid character) for something that should have base 10 value (i.e. 0-9 numbers).</p>
0
2016-04-25T20:14:57Z
[ "python", "google-app-engine" ]
Controlling getter and setter for a python's class
1,241,703
<p>Consider the following class :</p> <pre><code>class Token: def __init__(self): self.d_dict = {} def __setattr__(self, s_name, value): self.d_dict[s_name] = value def __getattr__(self, s_name): if s_name in self.d_dict.keys(): return self.d_dict[s_name] else: raise AttributeError('No attribute {0} found !'.format(s_name)) </code></pre> <p>In my code Token have some other function (like get_all() wich return d_dict, has(s_name) which tell me if my token has a particular attribute).</p> <p>Anyway, I think their is a flaw in my plan since it don't work : when I create a new instance, python try to call <code>__setattr__('d_dict', '{}')</code>.</p> <p>How can I achieve a similar behaviour (maybe in a more pythonic way ?) without having to write something like Token.set(name, value) and get(name) each I want to set or get an attribute for a token.</p> <p>Critics about design flaw and/or stupidity welcome :)</p> <p>Thank !</p>
4
2009-08-06T21:46:55Z
1,241,764
<p>You need to special-case d_dict.</p> <p>Although of course, in the above code, all you do is replicate what any object does with <code>__dict__</code> already, so it's pretty pointless. Do I guess correctly if you intended to special case some attributes and actally use methods for those?</p> <p>In that case, you can use properties.</p> <pre><code>class C(object): def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x </code></pre>
3
2009-08-06T21:59:34Z
[ "python" ]
Controlling getter and setter for a python's class
1,241,703
<p>Consider the following class :</p> <pre><code>class Token: def __init__(self): self.d_dict = {} def __setattr__(self, s_name, value): self.d_dict[s_name] = value def __getattr__(self, s_name): if s_name in self.d_dict.keys(): return self.d_dict[s_name] else: raise AttributeError('No attribute {0} found !'.format(s_name)) </code></pre> <p>In my code Token have some other function (like get_all() wich return d_dict, has(s_name) which tell me if my token has a particular attribute).</p> <p>Anyway, I think their is a flaw in my plan since it don't work : when I create a new instance, python try to call <code>__setattr__('d_dict', '{}')</code>.</p> <p>How can I achieve a similar behaviour (maybe in a more pythonic way ?) without having to write something like Token.set(name, value) and get(name) each I want to set or get an attribute for a token.</p> <p>Critics about design flaw and/or stupidity welcome :)</p> <p>Thank !</p>
4
2009-08-06T21:46:55Z
1,241,783
<p>A solution, not very pythonic but works. As Lennart Regebro pointed, you have to use a special case for d_dict.</p> <pre><code>class Token(object): def __init__(self): super(Token,self).__setattr__('d_dict', {}) def __getattr__(self,name): return self.a[name] def __setattr__(self,name,value): self.a[name] = value </code></pre> <p>You need to use new style classes.</p>
1
2009-08-06T22:04:56Z
[ "python" ]
Controlling getter and setter for a python's class
1,241,703
<p>Consider the following class :</p> <pre><code>class Token: def __init__(self): self.d_dict = {} def __setattr__(self, s_name, value): self.d_dict[s_name] = value def __getattr__(self, s_name): if s_name in self.d_dict.keys(): return self.d_dict[s_name] else: raise AttributeError('No attribute {0} found !'.format(s_name)) </code></pre> <p>In my code Token have some other function (like get_all() wich return d_dict, has(s_name) which tell me if my token has a particular attribute).</p> <p>Anyway, I think their is a flaw in my plan since it don't work : when I create a new instance, python try to call <code>__setattr__('d_dict', '{}')</code>.</p> <p>How can I achieve a similar behaviour (maybe in a more pythonic way ?) without having to write something like Token.set(name, value) and get(name) each I want to set or get an attribute for a token.</p> <p>Critics about design flaw and/or stupidity welcome :)</p> <p>Thank !</p>
4
2009-08-06T21:46:55Z
1,241,805
<p>It's worth remembering that <code>__getattr__</code> is only called if the attribute doesn't exist in the object, whereas <code>__setattr__</code> is always called.</p>
1
2009-08-06T22:09:13Z
[ "python" ]
Controlling getter and setter for a python's class
1,241,703
<p>Consider the following class :</p> <pre><code>class Token: def __init__(self): self.d_dict = {} def __setattr__(self, s_name, value): self.d_dict[s_name] = value def __getattr__(self, s_name): if s_name in self.d_dict.keys(): return self.d_dict[s_name] else: raise AttributeError('No attribute {0} found !'.format(s_name)) </code></pre> <p>In my code Token have some other function (like get_all() wich return d_dict, has(s_name) which tell me if my token has a particular attribute).</p> <p>Anyway, I think their is a flaw in my plan since it don't work : when I create a new instance, python try to call <code>__setattr__('d_dict', '{}')</code>.</p> <p>How can I achieve a similar behaviour (maybe in a more pythonic way ?) without having to write something like Token.set(name, value) and get(name) each I want to set or get an attribute for a token.</p> <p>Critics about design flaw and/or stupidity welcome :)</p> <p>Thank !</p>
4
2009-08-06T21:46:55Z
1,241,809
<p>The special-casing of <code>__dict__</code> works like this:</p> <pre><code>def __init__(self): self.__dict__['d_dict'] = {} </code></pre> <p>There is no need to use a new-style class for that.</p>
3
2009-08-06T22:10:15Z
[ "python" ]
Controlling getter and setter for a python's class
1,241,703
<p>Consider the following class :</p> <pre><code>class Token: def __init__(self): self.d_dict = {} def __setattr__(self, s_name, value): self.d_dict[s_name] = value def __getattr__(self, s_name): if s_name in self.d_dict.keys(): return self.d_dict[s_name] else: raise AttributeError('No attribute {0} found !'.format(s_name)) </code></pre> <p>In my code Token have some other function (like get_all() wich return d_dict, has(s_name) which tell me if my token has a particular attribute).</p> <p>Anyway, I think their is a flaw in my plan since it don't work : when I create a new instance, python try to call <code>__setattr__('d_dict', '{}')</code>.</p> <p>How can I achieve a similar behaviour (maybe in a more pythonic way ?) without having to write something like Token.set(name, value) and get(name) each I want to set or get an attribute for a token.</p> <p>Critics about design flaw and/or stupidity welcome :)</p> <p>Thank !</p>
4
2009-08-06T21:46:55Z
1,242,054
<p>the problem seems to be in time of evaluation of your code in __init__ method. You could define __new__ method and initialize d_dict variable there instead of __init__. Thats a bit hackish but it works, remember though to comment it as after few months it'll be total magic.</p> <pre><code>&gt;&gt;&gt; class Foo(object): ... def __new__(cls, *args): ... my_cls = super(Foo, cls).__new__(cls, *args) ... my_cls.d_dict = {} ... return my_cls &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; id(f.d_dict) 3077948796L &gt;&gt;&gt; d = Foo() &gt;&gt;&gt; id(d.d_dict) 3078142804L </code></pre> <p>Word of explanation why I consider that hackish: call to __new__ returns new instance of <em>class</em> so then <em>d_dict</em> initialised in there is kind of <strong>static</strong>, but it's initialised with new instance of dictionary each time class is "<em>created</em>" so everything works as you need.</p>
2
2009-08-06T23:22:57Z
[ "python" ]
Controlling getter and setter for a python's class
1,241,703
<p>Consider the following class :</p> <pre><code>class Token: def __init__(self): self.d_dict = {} def __setattr__(self, s_name, value): self.d_dict[s_name] = value def __getattr__(self, s_name): if s_name in self.d_dict.keys(): return self.d_dict[s_name] else: raise AttributeError('No attribute {0} found !'.format(s_name)) </code></pre> <p>In my code Token have some other function (like get_all() wich return d_dict, has(s_name) which tell me if my token has a particular attribute).</p> <p>Anyway, I think their is a flaw in my plan since it don't work : when I create a new instance, python try to call <code>__setattr__('d_dict', '{}')</code>.</p> <p>How can I achieve a similar behaviour (maybe in a more pythonic way ?) without having to write something like Token.set(name, value) and get(name) each I want to set or get an attribute for a token.</p> <p>Critics about design flaw and/or stupidity welcome :)</p> <p>Thank !</p>
4
2009-08-06T21:46:55Z
1,252,326
<p>I think we'll be able to say something about the overall design of your class if you explain its purpose. For example, </p> <pre><code># This is a class that serves as a dictionary but also has user-defined methods class mydict(dict): pass # This is a class that allows setting x.attr = value or getting x.attr: class mysetget: pass # This is a class that allows setting x.attr = value or getting x.attr: class mygetsethas: def has(self, key): return key in self.__dict__ x = mygetsethas() x.a = 5 print(x.has('a'), x.a) </code></pre> <p>I think the last class is closest to what you meant, and I also like to play with syntax and get lots of joy from it, but unfortunately this is not a good thing. Reasons why it's not advisable to use object attributes to re-implement dictionary: you can't use <code>x.3</code>, you conflict with <code>x.has()</code>, you have to put quotes in <code>has('a')</code> and many more.</p>
0
2009-08-09T21:22:18Z
[ "python" ]
Specifying relative path in py2exe
1,241,708
<p>When specifying my script file in setup.py, e.g. "script": 'pythonturtle.py', how can I specify its relative position in the file system? In my case, I need to go down two folders and then go into the "src" folder and it's in there. How do I write this in a cross-platform way?</p>
1
2009-08-06T21:47:43Z
1,242,020
<p>How can you speak of py2exe and cross-platform? py2exe is windows only.</p> <p>As far as I know, you have to keep your setup file in the same place as your script. Or if you don't have to it is certainly a strong convention.</p> <p>What you can do is define a dist_dir option so that your program gets built in the right place.</p> <pre><code>setup( options = {"py2exe": {"dist_dir": os.path.join("..", "foo", "bar")}}, windows = ["pythonturtle.py"], ) </code></pre>
3
2009-08-06T23:12:51Z
[ "python", "path", "py2exe" ]
Store data series in file or database if I want to do row level math operations?
1,241,758
<p>I'm developing an app that handle sets of financial series data (input as csv or open document), one set could be say 10's x 1000's up to double precision numbers (Simplifying, but thats what matters).</p> <p>I plan to do operations on that data (eg. sum, difference, averages etc.) as well including generation of say another column based on computations on the input. This will be between columns (row level operations) on one set and also between columns on many (potentially all) sets at the row level also. I plan to write it in Python and it will eventually need a intranet facing interface to display the results/graphs etc. for now, csv output based on some input parameters will suffice.</p> <p>What is the best way to store the data and manipulate? So far I see my choices as being either (1) to write csv files to disk and trawl through them to do the math or (2) I could put them into a database and rely on the database to handle the math. My main concern is speed/performance as the number of datasets grows as there will be inter-dataset row level math that needs to be done.</p> <p>-Has anyone had experience going down either path and what are the pitfalls/gotchas that I should be aware of? <br>-What are the reasons why one should be chosen over another? <br>-Are there any potential speed/performance pitfalls/boosts that I need to be aware of before I start that could influence the design? <br>-Is there any project or framework out there to help with this type of task? </p> <p>-Edit- More info: The rows will all read all in order, BUT I may need to do some resampling/interpolation to match the differing input lengths as well as differing timestamps for each row. Since each dataset will always have a differing length that is not fixed, I'll have some scratch table/memory somewhere to hold the interpolated/resampled versions. I'm not sure if it makes more sense to try to store this (and try to upsample/interploate to a common higher length) or just regenerate it each time its needed.</p>
0
2009-08-06T21:58:14Z
1,241,784
<p>Are you likely to need all rows in order or will you want only specific known rows?<br /> If you need to read all the data there isn't much advantage to having it in a database.</p> <p>edit: If the code fits in memory then a simple CSV is fine. Plain text data formats are always easier to deal with than opaque ones if you can use them.</p>
0
2009-08-06T22:05:04Z
[ "python", "database", "database-design", "file-io" ]
Store data series in file or database if I want to do row level math operations?
1,241,758
<p>I'm developing an app that handle sets of financial series data (input as csv or open document), one set could be say 10's x 1000's up to double precision numbers (Simplifying, but thats what matters).</p> <p>I plan to do operations on that data (eg. sum, difference, averages etc.) as well including generation of say another column based on computations on the input. This will be between columns (row level operations) on one set and also between columns on many (potentially all) sets at the row level also. I plan to write it in Python and it will eventually need a intranet facing interface to display the results/graphs etc. for now, csv output based on some input parameters will suffice.</p> <p>What is the best way to store the data and manipulate? So far I see my choices as being either (1) to write csv files to disk and trawl through them to do the math or (2) I could put them into a database and rely on the database to handle the math. My main concern is speed/performance as the number of datasets grows as there will be inter-dataset row level math that needs to be done.</p> <p>-Has anyone had experience going down either path and what are the pitfalls/gotchas that I should be aware of? <br>-What are the reasons why one should be chosen over another? <br>-Are there any potential speed/performance pitfalls/boosts that I need to be aware of before I start that could influence the design? <br>-Is there any project or framework out there to help with this type of task? </p> <p>-Edit- More info: The rows will all read all in order, BUT I may need to do some resampling/interpolation to match the differing input lengths as well as differing timestamps for each row. Since each dataset will always have a differing length that is not fixed, I'll have some scratch table/memory somewhere to hold the interpolated/resampled versions. I'm not sure if it makes more sense to try to store this (and try to upsample/interploate to a common higher length) or just regenerate it each time its needed.</p>
0
2009-08-06T21:58:14Z
1,241,787
<p>What matters most if all data will fit simultaneously into memory. From the size that you give, it seems that this is easily the case (a few megabytes at worst).</p> <p>If so, I would discourage using a relational database, and do all operations directly in Python. Depending on what other processing you need, I would probably rather use binary pickles, than CSV.</p>
0
2009-08-06T22:05:40Z
[ "python", "database", "database-design", "file-io" ]
Store data series in file or database if I want to do row level math operations?
1,241,758
<p>I'm developing an app that handle sets of financial series data (input as csv or open document), one set could be say 10's x 1000's up to double precision numbers (Simplifying, but thats what matters).</p> <p>I plan to do operations on that data (eg. sum, difference, averages etc.) as well including generation of say another column based on computations on the input. This will be between columns (row level operations) on one set and also between columns on many (potentially all) sets at the row level also. I plan to write it in Python and it will eventually need a intranet facing interface to display the results/graphs etc. for now, csv output based on some input parameters will suffice.</p> <p>What is the best way to store the data and manipulate? So far I see my choices as being either (1) to write csv files to disk and trawl through them to do the math or (2) I could put them into a database and rely on the database to handle the math. My main concern is speed/performance as the number of datasets grows as there will be inter-dataset row level math that needs to be done.</p> <p>-Has anyone had experience going down either path and what are the pitfalls/gotchas that I should be aware of? <br>-What are the reasons why one should be chosen over another? <br>-Are there any potential speed/performance pitfalls/boosts that I need to be aware of before I start that could influence the design? <br>-Is there any project or framework out there to help with this type of task? </p> <p>-Edit- More info: The rows will all read all in order, BUT I may need to do some resampling/interpolation to match the differing input lengths as well as differing timestamps for each row. Since each dataset will always have a differing length that is not fixed, I'll have some scratch table/memory somewhere to hold the interpolated/resampled versions. I'm not sure if it makes more sense to try to store this (and try to upsample/interploate to a common higher length) or just regenerate it each time its needed.</p>
0
2009-08-06T21:58:14Z
1,245,169
<p><strong>"I plan to do operations on that data (eg. sum, difference, averages etc.) as well including generation of say another column based on computations on the input."</strong></p> <p>This is the standard use case for a data warehouse star-schema design. Buy Kimball's The Data Warehouse Toolkit. Read (and understand) the star schema before doing anything else.</p> <p><strong>"What is the best way to store the data and manipulate?</strong>" </p> <p>A Star Schema.</p> <p>You can implement this as flat files (CSV is fine) or RDBMS. If you use flat files, you write simple loops to do the math. If you use an RDBMS you write simple SQL <em>and</em> simple loops. </p> <p><strong>"My main concern is speed/performance as the number of datasets grows"</strong> </p> <p>Nothing is as fast as a flat file. Period. RDBMS is slower. </p> <p>The RDBMS value proposition stems from SQL being a relatively simple way to specify <code>SELECT SUM(), COUNT() FROM fact JOIN dimension WHERE filter GROUP BY dimension attribute</code>. Python isn't as terse as SQL, but it's just as fast and just as flexible. Python competes against SQL.</p> <p><strong>"pitfalls/gotchas that I should be aware of?"</strong></p> <p>DB design. If you don't get the star schema and how to separate facts from dimensions, all approaches are doomed. Once you separate facts from dimensions, all approaches are approximately equal.</p> <p><strong>"What are the reasons why one should be chosen over another?"</strong></p> <p>RDBMS slow and flexible. Flat files fast and (sometimes) less flexible. Python levels the playing field.</p> <p><strong>"Are there any potential speed/performance pitfalls/boosts that I need to be aware of before I start that could influence the design?"</strong></p> <p>Star Schema: central fact table surrounded by dimension tables. Nothing beats it.</p> <p><strong>"Is there any project or framework out there to help with this type of task?"</strong></p> <p>Not really.</p>
2
2009-08-07T14:44:41Z
[ "python", "database", "database-design", "file-io" ]
Store data series in file or database if I want to do row level math operations?
1,241,758
<p>I'm developing an app that handle sets of financial series data (input as csv or open document), one set could be say 10's x 1000's up to double precision numbers (Simplifying, but thats what matters).</p> <p>I plan to do operations on that data (eg. sum, difference, averages etc.) as well including generation of say another column based on computations on the input. This will be between columns (row level operations) on one set and also between columns on many (potentially all) sets at the row level also. I plan to write it in Python and it will eventually need a intranet facing interface to display the results/graphs etc. for now, csv output based on some input parameters will suffice.</p> <p>What is the best way to store the data and manipulate? So far I see my choices as being either (1) to write csv files to disk and trawl through them to do the math or (2) I could put them into a database and rely on the database to handle the math. My main concern is speed/performance as the number of datasets grows as there will be inter-dataset row level math that needs to be done.</p> <p>-Has anyone had experience going down either path and what are the pitfalls/gotchas that I should be aware of? <br>-What are the reasons why one should be chosen over another? <br>-Are there any potential speed/performance pitfalls/boosts that I need to be aware of before I start that could influence the design? <br>-Is there any project or framework out there to help with this type of task? </p> <p>-Edit- More info: The rows will all read all in order, BUT I may need to do some resampling/interpolation to match the differing input lengths as well as differing timestamps for each row. Since each dataset will always have a differing length that is not fixed, I'll have some scratch table/memory somewhere to hold the interpolated/resampled versions. I'm not sure if it makes more sense to try to store this (and try to upsample/interploate to a common higher length) or just regenerate it each time its needed.</p>
0
2009-08-06T21:58:14Z
1,249,257
<p>For speed optimization, I would suggest two other avenues of investigation beyond changing your underlying storage mechanism:</p> <p><strong>1) Use an intermediate data structure.</strong></p> <p>If maximizing speed is more important than minimizing memory usage, you may get good results out of using a different data structure as the basis of your calculations, rather than focusing on the underlying storage mechanism. This is a strategy that, in practice, has reduced runtime in projects I've worked on dramatically, regardless of whether the data was stored in a database or text (in my case, XML).</p> <p>While sums and averages will require runtime in only <a href="http://en.wikipedia.org/wiki/Big%5FO%5Fnotation" rel="nofollow">O(n)</a>, more complex calculations could easily push that into O(n^2) without applying this strategy. O(n^2) would be a performance hit that would likely have far more of a perceived speed impact than whether you're reading from CSV or a database. An example case would be if your data rows reference other data rows, and there's a need to aggregate data based on those references.</p> <p>So if you find yourself doing calculations more complex than a sum or an average, you might explore data structures that can be created in O(n) and would keep your calculation operations in O(n) or better. As Martin pointed out, it sounds like your whole data sets can be held in memory comfortably, so this may yield some big wins. What kind of data structure you'd create would be dependent on the nature of the calculation you're doing.</p> <p><strong>2) Pre-cache.</strong></p> <p>Depending on how the data is to be used, you could store the calculated values ahead of time. As soon as the data is produced/loaded, perform your sums, averages, etc., and store those aggregations alongside your original data, or hold them in memory as long as your program runs. If this strategy is applicable to your project (i.e. if the users aren't coming up with unforeseen calculation requests on the fly), reading the data shouldn't be prohibitively long-running, whether the data comes from text or a database.</p>
1
2009-08-08T16:25:04Z
[ "python", "database", "database-design", "file-io" ]
What is the recommended Python module for fast Fourier transforms (FFT)?
1,241,797
<p>Taking speed as an issue it may be better to choose another language, but what is your library/module/implementation of choice for doing a 1D fast Fourier transform (FFT) in Python?</p>
4
2009-08-06T22:07:40Z
1,241,883
<p>I would recommend using the <a href="http://www.fftw.org" rel="nofollow">FFTW</a> library ("the fastest Fourier transform in the West"). The <a href="http://www.fftw.org/download.html" rel="nofollow">FFTW download page</a> states that Python wrappers exist, but the link is broken. A Google search turned up <a href="http://developer.berlios.de/projects/pyfftw/" rel="nofollow">Python FFTW</a>, which provides Python bindings to FFTW3.</p>
3
2009-08-06T22:29:15Z
[ "python", "benchmarking", "fft" ]
What is the recommended Python module for fast Fourier transforms (FFT)?
1,241,797
<p>Taking speed as an issue it may be better to choose another language, but what is your library/module/implementation of choice for doing a 1D fast Fourier transform (FFT) in Python?</p>
4
2009-08-06T22:07:40Z
1,241,961
<p>I would recommend numpy library, I not sure if it's the fastest implementation that exist but but surely it's one of best scientific module on the "market". </p>
8
2009-08-06T22:50:27Z
[ "python", "benchmarking", "fft" ]
What is the recommended Python module for fast Fourier transforms (FFT)?
1,241,797
<p>Taking speed as an issue it may be better to choose another language, but what is your library/module/implementation of choice for doing a 1D fast Fourier transform (FFT) in Python?</p>
4
2009-08-06T22:07:40Z
1,241,983
<p>FFTW would probably be the fastest implementation, if you can find a python binding that actually works.</p> <p>The easiest thing to use is certainly <a href="http://www.scipy.org/SciPyPackages/Fftpack?highlight=%28fft%29">scipy.fft</a>, though. Plus, you get all the power of numpy/scipy to go along with it.</p> <p>I've only used it for a toy project (a basic music visualization) but it was fast enough to process bog standard audio at 44khz at 60fps, as far as I can remember.</p>
5
2009-08-06T22:55:38Z
[ "python", "benchmarking", "fft" ]
django binary (no source code) deployment
1,241,813
<p>is there possible only to deploy binary version of web application based on django , no source code publish?</p> <p>Thanks</p>
8
2009-08-06T22:11:48Z
1,241,837
<p>Yes, you can, sort of.</p> <p>Have a read of <a href="http://effbot.org/zone/python-compile.htm" rel="nofollow">http://effbot.org/zone/python-compile.htm</a> - that should answer your question!</p>
3
2009-08-06T22:15:40Z
[ "python", "django", "binary" ]
django binary (no source code) deployment
1,241,813
<p>is there possible only to deploy binary version of web application based on django , no source code publish?</p> <p>Thanks</p>
8
2009-08-06T22:11:48Z
1,248,511
<p>No, there isn't a reliable to do this at the moment. Even compiled code like referenced in the answer above this one isn't 100% secure.</p> <p><strong>My advice:</strong> clean open code for your clients and a good relation with them is the only way to go. Keeping your code hidden can be good from a business point of view but from a client relation point of view it's a real show stopper. Advertise: "Our code is open!", which doesn't mean your clients can do anything they want with it.</p>
3
2009-08-08T10:21:16Z
[ "python", "django", "binary" ]
django binary (no source code) deployment
1,241,813
<p>is there possible only to deploy binary version of web application based on django , no source code publish?</p> <p>Thanks</p>
8
2009-08-06T22:11:48Z
1,248,531
<p>Oh, again that old one... Simply stated, you can't deploy an application in a non-compiled language (Python, Perl, PHP, Ruby...) in a source-safe way - all existing tricks are extremely easy to circumvent. Anyway, that doesn't matter at all: the contract you have with your customer does. Even for Java there are neat decompilers.</p> <p>If your customer wants to redeploy by hand your application on another machine, he could anyway even if the application was in C. Unless you wrote a dongle-protected anti-piracy scheme? Come on. You have to build a relation with your client. This is a social, commercial and legal problem that <strong>can't</strong> be solved with a technical stunt.</p>
5
2009-08-08T10:36:38Z
[ "python", "django", "binary" ]
In GTK on Windows, how do I change the background color of the whole app?
1,241,846
<p>According to <a href="http://www.pygtk.org/docs/pygtk/gtk-constants.html" rel="nofollow">http://www.pygtk.org/docs/pygtk/gtk-constants.html</a>, there are five state types: <code>STATE_NORMAL</code>, <code>STATE_INSENSITIVE</code>, etc. I want to set the background color of a Table, HBox, VBox, whatever, and I've tried setting every possible color of every kind of state:</p> <pre><code> style = self.get_style() for a in (style.base, style.fg, style.bg, style.light, style.dark, style.mid, style.text, style.base, style.text_aa): for st in (gtk.STATE_NORMAL, gtk.STATE_INSENSITIVE, gtk.STATE_PRELIGHT, gtk.STATE_SELECTED, gtk.STATE_ACTIVE): a[st] = gtk.gdk.Color(0, 34251, 0) </code></pre> <p>Nothing has any effect. The only one that has any effect is when I manually created EventBoxes and specifically used the existing gtk.STATE_NORMAL color to blend with other colors. All the ones created by gtk without my intervention were not affected, though.</p> <p>What's the proper way to go about doing this? I wouldn't mind having to make a gtkrc file or whatever. Is this because hbox, vbox, etc., don't have a color, but are transparent? Who provides the general color of the application, then?</p>
1
2009-08-06T22:18:25Z
1,242,057
<p>Mostly google-fu (no windows here), posting as an "answer" mostly for a slightly better formatting. See if experimenting with the full-blown gtkrc like the one from <a href="http://wolfs-ubuntu.blogspot.com/2009/02/trouble-with-gtkrc.html" rel="nofollow">here</a> brings the fruits. The location, based on <a href="http://www.daa.com.au/pipermail/pygtk/2002-June/002945.html" rel="nofollow">this</a> and <a href="http://developer.pidgin.im/wiki/Using%20Pidgin#WhatisagtkrcfileandwherecanIfindit" rel="nofollow">this</a> appears to vary - so unless someone has the deterministic approach of finding it, filemon could be a sensible approach.</p> <p>Being mostly a user for these kinds of apps, I would prefer the settings from my gtkrc over the hardcoded by what the programmer thought would be "the best", anytime. </p>
2
2009-08-06T23:23:24Z
[ "python", "windows", "gtk", "colors", "pygtk" ]
In GTK on Windows, how do I change the background color of the whole app?
1,241,846
<p>According to <a href="http://www.pygtk.org/docs/pygtk/gtk-constants.html" rel="nofollow">http://www.pygtk.org/docs/pygtk/gtk-constants.html</a>, there are five state types: <code>STATE_NORMAL</code>, <code>STATE_INSENSITIVE</code>, etc. I want to set the background color of a Table, HBox, VBox, whatever, and I've tried setting every possible color of every kind of state:</p> <pre><code> style = self.get_style() for a in (style.base, style.fg, style.bg, style.light, style.dark, style.mid, style.text, style.base, style.text_aa): for st in (gtk.STATE_NORMAL, gtk.STATE_INSENSITIVE, gtk.STATE_PRELIGHT, gtk.STATE_SELECTED, gtk.STATE_ACTIVE): a[st] = gtk.gdk.Color(0, 34251, 0) </code></pre> <p>Nothing has any effect. The only one that has any effect is when I manually created EventBoxes and specifically used the existing gtk.STATE_NORMAL color to blend with other colors. All the ones created by gtk without my intervention were not affected, though.</p> <p>What's the proper way to go about doing this? I wouldn't mind having to make a gtkrc file or whatever. Is this because hbox, vbox, etc., don't have a color, but are transparent? Who provides the general color of the application, then?</p>
1
2009-08-06T22:18:25Z
1,242,325
<p>It's because VBox and Hbox don't have an associated Window. <a href="http://library.gnome.org/devel/gtk-tutorial/2.15/x483.html" rel="nofollow">click here to see other widgets without windows</a>. I would create event boxes and add the HBox or VBox inside the event box.</p>
1
2009-08-07T00:47:49Z
[ "python", "windows", "gtk", "colors", "pygtk" ]
In GTK on Windows, how do I change the background color of the whole app?
1,241,846
<p>According to <a href="http://www.pygtk.org/docs/pygtk/gtk-constants.html" rel="nofollow">http://www.pygtk.org/docs/pygtk/gtk-constants.html</a>, there are five state types: <code>STATE_NORMAL</code>, <code>STATE_INSENSITIVE</code>, etc. I want to set the background color of a Table, HBox, VBox, whatever, and I've tried setting every possible color of every kind of state:</p> <pre><code> style = self.get_style() for a in (style.base, style.fg, style.bg, style.light, style.dark, style.mid, style.text, style.base, style.text_aa): for st in (gtk.STATE_NORMAL, gtk.STATE_INSENSITIVE, gtk.STATE_PRELIGHT, gtk.STATE_SELECTED, gtk.STATE_ACTIVE): a[st] = gtk.gdk.Color(0, 34251, 0) </code></pre> <p>Nothing has any effect. The only one that has any effect is when I manually created EventBoxes and specifically used the existing gtk.STATE_NORMAL color to blend with other colors. All the ones created by gtk without my intervention were not affected, though.</p> <p>What's the proper way to go about doing this? I wouldn't mind having to make a gtkrc file or whatever. Is this because hbox, vbox, etc., don't have a color, but are transparent? Who provides the general color of the application, then?</p>
1
2009-08-06T22:18:25Z
5,398,966
<p>You need to call <code>self.set_style(style)</code> after changing the style. I used your code as a template and adding that line makes the background of everything green.</p>
0
2011-03-22T23:07:37Z
[ "python", "windows", "gtk", "colors", "pygtk" ]
Qt QFileDialog QSizePolicy of sidebar
1,241,893
<p>With a QFileDialog I'm trying to change the size of the side bar in a QFileDialog. I want it to have a larger width. I was looking at dir(QtGui.QFileDialog) which shows a plethora of functions/methods and dir(QtGui.QSizePolicy) which seemed like the right choice. I've not been able to manipulate the size of the side bar though.</p> <pre><code>print 'sizePolicy: ', self.sizePolicy() urls = [ QtCore.QUrl("file:"), QtCore.QUrl("file:///usr/home/")] self.fileBrowser.setSidebarUrls( urls ) </code></pre> <p><em>Returns // sizePolicy: </em></p> <p>It seems to average out the length of the names to create the width of the side bar. Anyone know a way around this? Size policy returns back a QSizePolicy object, but I don't know how to manipulate the side bar's size.</p> <p>Thanks!</p>
0
2009-08-06T22:31:48Z
1,835,107
<p>I would suggest using find_children and then maybe qobject_cast to get the sidebar object and the manipulate it directly. </p>
0
2009-12-02T19:05:41Z
[ "python", "qt", "resize", "pyqt" ]
Optimal way to replace characters in large string with Python?
1,242,209
<p>I'm dealing with cleaning relatively large (30ish lines) blocks of text. Here's an excerpt:</p> <blockquote> <p>PID|1||06225401^^^PA0^MR||PATIENT^FAKE R|||F </p> <p>PV1|1|I|||||025631^DoctorZ^^^^^^^PA0^^^^DRH|DRH||||...</p> <p>ORC|RE||CYT-09-06645^AP||||||200912110333|INTERFACE07</p> <p>OBR|1||CYT09-06645|8104^^L|||20090602|||||||200906030000[conditio...</p> <p>OBX|1|TX|8104|1|SOURCE OF SPECIMEN:[source]||||||F|||200912110333|CYT ...</p> </blockquote> <p>I currently have a script that takes out illegal characters or terms. Here's an example.</p> <pre><code> infile = open(thisFile,'r') m = infile.read() #remove junk headers m = m.replace("4þPATHþ", "") m = m.replace("10þALLþ", "") </code></pre> <p>My goal is to modify this script so that I can add 4 digits to the end of one of the fields. In specific, the date field ("20090602") in the OBR line. The finished script will be able to work with any file that follows this same format. Is this possible with the way I currently handle the file input or do I have to use some different logic?</p>
0
2009-08-07T00:09:05Z
1,242,242
<p>You may find the answers here helpful.</p> <p><a href="http://stackoverflow.com/questions/1175540/iterative-find-replace-from-a-list-of-tuples-in-python/1175547">http://stackoverflow.com/questions/1175540/iterative-find-replace-from-a-list-of-tuples-in-python/1175547</a></p>
2
2009-08-07T00:18:55Z
[ "python" ]
Optimal way to replace characters in large string with Python?
1,242,209
<p>I'm dealing with cleaning relatively large (30ish lines) blocks of text. Here's an excerpt:</p> <blockquote> <p>PID|1||06225401^^^PA0^MR||PATIENT^FAKE R|||F </p> <p>PV1|1|I|||||025631^DoctorZ^^^^^^^PA0^^^^DRH|DRH||||...</p> <p>ORC|RE||CYT-09-06645^AP||||||200912110333|INTERFACE07</p> <p>OBR|1||CYT09-06645|8104^^L|||20090602|||||||200906030000[conditio...</p> <p>OBX|1|TX|8104|1|SOURCE OF SPECIMEN:[source]||||||F|||200912110333|CYT ...</p> </blockquote> <p>I currently have a script that takes out illegal characters or terms. Here's an example.</p> <pre><code> infile = open(thisFile,'r') m = infile.read() #remove junk headers m = m.replace("4þPATHþ", "") m = m.replace("10þALLþ", "") </code></pre> <p>My goal is to modify this script so that I can add 4 digits to the end of one of the fields. In specific, the date field ("20090602") in the OBR line. The finished script will be able to work with any file that follows this same format. Is this possible with the way I currently handle the file input or do I have to use some different logic?</p>
0
2009-08-07T00:09:05Z
1,242,253
<p>Here's an outline (untested) ... basically you do it a line at a time</p> <pre><code>for line in infile: data = line.rstrip("\n").split("|") kind = data[0] # start of changes if kind == "OBR": data[7] += "0000" # check that 7 is correct! # end of changes outrecord = "|".join(data) outfile.write(outrecord + "\n") </code></pre> <p>The above assumes that you are selecting fix-up targets by line-type (example: "OBR") and column index (example: 7). If there are only a few such targets, just add more similar fix statements. If there are many targets, you could specify them like this:</p> <pre><code>fix_targets = { "OBR": [7], "XYZ": [1, 42], } </code></pre> <p>and the fix_up code would look like this:</p> <pre><code>if kind in fix_targets: for col_index in fix_targets[kind]: data[col_index] += "0000" </code></pre> <p>You may like in any case to add code to check that data[col_index] really is a date in YYYYMMDD format before changing it.</p> <p>None of the above addresses removing the unwanted headers, because you didn't show example data. I <em>guess</em> that applying your replacements to each line (and avoiding writing the line if it became only whitespace after replacements) would do the trick.</p>
2
2009-08-07T00:23:53Z
[ "python" ]
Multiple blocks of same name in Jinja2
1,242,239
<p>In <a href="http://jinja.pocoo.org/">Jinja2</a>, I have a base template like this:</p> <pre><code>&lt;title&gt;{% block title %}{% endblock %} - example.com&lt;/title&gt; [...] &lt;h1&gt; {% block title %}{% endblock %} - example.com &lt;/h1&gt; </code></pre> <p>Jinja2, then, fails with the following message:</p> <pre><code> lines = [self.message, ' ' + location] : block 'title' defined twice </code></pre> <p>It must be now evident as to what I am trying to do - to have the same title in two places: the TITLE tag and the H1 tag, but the part of the title is actually provided by other derived templates.</p> <p>How does one typically achieve this?</p>
22
2009-08-07T00:18:14Z
1,245,030
<p>As documented <a href="http://jinja.pocoo.org/2/documentation/templates#child-template">here</a>, defining a block creates a macro with the name of the block in the special "self" object:</p> <pre><code>&lt;title&gt;{% block title %}{% endblock %} - example.com&lt;/title&gt; [...] &lt;h1&gt; {{ self.title() }} - example.com &lt;/h1&gt; </code></pre>
44
2009-08-07T14:27:05Z
[ "python", "html", "templates", "jinja2" ]
Generating a graph with multiple (sets of multiple sets of multiple) X-axis data sets
1,242,270
<p>I am looking for a way to generate a graph with multiple sets of data on the X-axis, each of which is divided into multiple sets of multiple sets. I basically want to take <a href="http://gdgraph.com/samples/sample1A.html" rel="nofollow">this graph</a> and place similar graphs side by side with it. I am trying to graph the build a graph of the duration (Y-axis) of the same jobs (0-3) with different configurations (0-1) on multiple servers (each group with the same 8 jobs). Hopefully the following diagram will illustrate what I am trying to accomplish (smaller groupings are separated by pipes, larger groupings by double pipes):</p> <pre>|| 0 1 | 0 1 | 0 1 | 0 1 || 0 1 | 0 1 | 0 1 | 0 1 || 0 1 | 0 1 | 0 1 | 0 1 || || 0 | 1 | 2 | 3 || 0 | 1 | 2 | 3 || 0 | 1 | 2 | 3 || || Server 1 || Server 2 || Server 3 ||</pre> <p>Is this possible with either the GD::Graph Perl module or the matplotlib Python module? I can't find examples or documentation on this subject for either.</p>
3
2009-08-07T00:28:45Z
1,242,743
<p>Here's some Python code that will produce what you're looking for. (The example uses 3 configurations rather than 2 to make sure the code was fairly general.)</p> <pre><code>import matplotlib.pyplot as plt import random nconfigs, njobs, nservers = 3, 4, 4 width = .9/(nconfigs*njobs) job_colors = [(0,0,1), (0,1,0), (1,0,0), (1,0,1)] def dim(color, fraction=.5): return tuple([fraction*channel for channel in color]) plt.figure() x = 0 for iserver in range(nservers): for ijob in range(njobs): for iconfig in range(nconfigs): color = dim(job_colors[ijob], (iconfig+2.)/(nconfigs+1)) plt.bar(x, 1.+random.random(), width, color=color) x += width x += .1 plt.show() </code></pre> <p>This code is probably fairly transparent. The odd term <code>(iconfig+2.)/(nconfigs+1)</code> is just to dim the colors for the different configurations, but keep them bright enough so the colors can be distinguished.</p> <p>The output looks like:</p> <p><img src="http://i28.tinypic.com/dgrnzk.png" alt="alt text" /></p>
6
2009-08-07T03:26:27Z
[ "python", "perl", "matplotlib", "graphing" ]
Generating a graph with multiple (sets of multiple sets of multiple) X-axis data sets
1,242,270
<p>I am looking for a way to generate a graph with multiple sets of data on the X-axis, each of which is divided into multiple sets of multiple sets. I basically want to take <a href="http://gdgraph.com/samples/sample1A.html" rel="nofollow">this graph</a> and place similar graphs side by side with it. I am trying to graph the build a graph of the duration (Y-axis) of the same jobs (0-3) with different configurations (0-1) on multiple servers (each group with the same 8 jobs). Hopefully the following diagram will illustrate what I am trying to accomplish (smaller groupings are separated by pipes, larger groupings by double pipes):</p> <pre>|| 0 1 | 0 1 | 0 1 | 0 1 || 0 1 | 0 1 | 0 1 | 0 1 || 0 1 | 0 1 | 0 1 | 0 1 || || 0 | 1 | 2 | 3 || 0 | 1 | 2 | 3 || 0 | 1 | 2 | 3 || || Server 1 || Server 2 || Server 3 ||</pre> <p>Is this possible with either the GD::Graph Perl module or the matplotlib Python module? I can't find examples or documentation on this subject for either.</p>
3
2009-08-07T00:28:45Z
1,245,797
<p>Recently, I saw a graph that I think does what you want using <a href="http://vis.stanford.edu/protovis/ex/antibiotics-burtin.html" rel="nofollow">protovis</a></p> <p>I have no experience with the program, but the graph was enlightening and I think would give you want you want.</p>
0
2009-08-07T16:42:16Z
[ "python", "perl", "matplotlib", "graphing" ]
Generating a graph with multiple (sets of multiple sets of multiple) X-axis data sets
1,242,270
<p>I am looking for a way to generate a graph with multiple sets of data on the X-axis, each of which is divided into multiple sets of multiple sets. I basically want to take <a href="http://gdgraph.com/samples/sample1A.html" rel="nofollow">this graph</a> and place similar graphs side by side with it. I am trying to graph the build a graph of the duration (Y-axis) of the same jobs (0-3) with different configurations (0-1) on multiple servers (each group with the same 8 jobs). Hopefully the following diagram will illustrate what I am trying to accomplish (smaller groupings are separated by pipes, larger groupings by double pipes):</p> <pre>|| 0 1 | 0 1 | 0 1 | 0 1 || 0 1 | 0 1 | 0 1 | 0 1 || 0 1 | 0 1 | 0 1 | 0 1 || || 0 | 1 | 2 | 3 || 0 | 1 | 2 | 3 || 0 | 1 | 2 | 3 || || Server 1 || Server 2 || Server 3 ||</pre> <p>Is this possible with either the GD::Graph Perl module or the matplotlib Python module? I can't find examples or documentation on this subject for either.</p>
3
2009-08-07T00:28:45Z
4,798,221
<p><a href="http://mathgl.sourceforge.net/" rel="nofollow">MathGL</a> can do it easily and it have Python interface too. See <a href="http://mathgl.sourceforge.net/1d_plots.html" rel="nofollow">this</a> for examples.</p>
0
2011-01-25T20:01:42Z
[ "python", "perl", "matplotlib", "graphing" ]
why does this python program print True
1,242,460
<pre><code>x=True def stupid(): x=False stupid() print x </code></pre>
7
2009-08-07T01:35:47Z
1,242,467
<p>You don't need to declare a function-local variable in Python. The "x=False" is referring to an x local to stupid(). If you really want to modify the global x inside stupid:</p> <pre><code>def stupid(): global x x=False </code></pre>
18
2009-08-07T01:37:55Z
[ "python" ]
why does this python program print True
1,242,460
<pre><code>x=True def stupid(): x=False stupid() print x </code></pre>
7
2009-08-07T01:35:47Z
1,242,468
<p>The x in the function stupid() is a local variable, so you really have 2 variables named x.</p>
2
2009-08-07T01:38:11Z
[ "python" ]
why does this python program print True
1,242,460
<pre><code>x=True def stupid(): x=False stupid() print x </code></pre>
7
2009-08-07T01:35:47Z
1,242,469
<p>Because x's scope is local to the function stupid(). once you call the function, and it ends, you're out of it's scope, and you print the value of "x" that's defined outside of the function stupid() -- and, the x that's defined <em>inside</em> of function stupid() doesn't exist on the stack anymore (once that function ends)</p> <p><strong>edit after your comment:</strong></p> <p>the <em>outer</em> x is referenced when you printed it, just like you did.</p> <p>the <em>inner</em> x can only be referenced whilst your inside the function stupid(). so you can print inside of that function so that you see what value the x inside of it holds.</p> <p><strong>About "global"</strong></p> <ul> <li>it works &amp; answers the question, apparently</li> <li>not a good idea to use all that often</li> <li>causes readability and scalability issues (and potentially more)</li> <li>depending on your project, you may want to reconsider using a global variable defined inside of a local function.</li> </ul>
6
2009-08-07T01:38:19Z
[ "python" ]
why does this python program print True
1,242,460
<pre><code>x=True def stupid(): x=False stupid() print x </code></pre>
7
2009-08-07T01:35:47Z
1,242,482
<p>Add "global x" before x=False in the function and it will print True. Otherwise, it's there are two "x"'s, each in a different scope.</p>
2
2009-08-07T01:40:06Z
[ "python" ]
why does this python program print True
1,242,460
<pre><code>x=True def stupid(): x=False stupid() print x </code></pre>
7
2009-08-07T01:35:47Z
1,242,483
<p>To answer your next question, use <code>global</code>:</p> <pre><code>x=True def stupid(): global x x=False stupid() print x </code></pre>
10
2009-08-07T01:40:10Z
[ "python" ]
why does this python program print True
1,242,460
<pre><code>x=True def stupid(): x=False stupid() print x </code></pre>
7
2009-08-07T01:35:47Z
1,242,495
<p>If you want to access the global variable x from a method in python, you need to do so explicitly:</p> <pre><code>x=True def stupid(): global x x=False stupid() print x </code></pre>
3
2009-08-07T01:42:36Z
[ "python" ]
why does this python program print True
1,242,460
<pre><code>x=True def stupid(): x=False stupid() print x </code></pre>
7
2009-08-07T01:35:47Z
1,242,498
<ul> <li>Because you're making an assignment to <code>x</code> inside <code>stupid()</code>, Python creates a new <code>x</code> inside <code>stupid()</code>.</li> <li>If you were only <em>reading</em> from <code>x</code> inside <code>stupid()</code>, Python would in fact use the global <code>x</code>, which is what you wanted.</li> <li>To force Python to use the global <code>x</code>, add <code>global x</code> as the first line inside <code>stupid()</code>.</li> </ul>
2
2009-08-07T01:43:29Z
[ "python" ]
why does this python program print True
1,242,460
<pre><code>x=True def stupid(): x=False stupid() print x </code></pre>
7
2009-08-07T01:35:47Z
1,243,017
<p>If that code is all inside a function though, <code>global</code> is not going to work, because then <code>x</code> would not be a global variable. In Python 3.x, they introduced the <code>nonlocal</code> keyword, which would make the code work regardless of whether it is at the top level or inside a function:</p> <pre><code>x=True def stupid(): nonlocal x x=False stupid() print x </code></pre>
5
2009-08-07T05:22:37Z
[ "python" ]
How can I highlight a row in a gtk.Table?
1,242,531
<p>I want to highlight specific rows in a <code>gtk.Table</code>. I also want a mouseover to highlight it w/ a different color (like on a link in a web browser). I thought of just packing each cell with an eventBox and changing the <code>STATE_NORMAL</code> and <code>STATE_PRELIGHT</code> bg colors, which does work, but mousing over the eventbox doesn't work. Is there a better way?</p>
2
2009-08-07T01:59:17Z
1,242,545
<p>This seems to work:</p> <pre><code> def attach(w,c1,c2,r1,r2): eb = gtk.EventBox() a = gtk.Alignment(xalign=0.0,yalign=0.5) a.add(w) eb.add(a) eb.set_style(self.rowStyle) def ene(eb,ev): eb.set_state(gtk.STATE_PRELIGHT) def lne(eb,ev): eb.set_state(gtk.STATE_NORMAL) eb.connect('enter-notify-event', ene) eb.connect('leave-notify-event', lne) self.table.attach(eb, c1, c2, r1, r2, xoptions=gtk.EXPAND|gtk.FILL, yoptions=gtk.SHRINK) </code></pre> <p>It only highlights each cell at a time, so I'll have to change the notify events to light up everything. </p> <p>EDIT: <code>self.rowStyle</code> is set as follows:</p> <pre><code>tmpeb = gtk.EventBox() st = tmpeb.get_style().copy() st.bg[gtk.STATE_PRELIGHT] = gtk.gdk.Color(65535,65535,0) self.rowStyle = st </code></pre> <p>I create an <code>EventBox</code> just to get its style.</p>
2
2009-08-07T02:05:18Z
[ "python", "table", "gtk", "colors", "pygtk" ]
What's the point of alloc_color() in gtk?
1,242,541
<p>Various examples always use alloc_color() and stuff like gtk.color.parse('red'), etc. I just do gtk.gdk.Color(65535,0,0), and that seems to work. What's the need for <code>alloc_color</code>?</p>
1
2009-08-07T02:03:16Z
1,242,550
<p>If you're running on a system that uses a palette display (as opposed to a true-colour display), then you must allocate new colours in the palette before you can use them. This is because palette-based displays can only display a limited number of colours at once (usually 256 or sometimes 65536).</p> <p>Most displays these days are capable of true colour display, which can display all available colours simultaneously, so this won't appear to be a problem and you can get away with directly asking for specific colours.</p>
2
2009-08-07T02:08:27Z
[ "python", "gtk", "colors", "pygtk" ]
subclassing int to attain a Hex representation
1,242,589
<p>Basically I want to have access to all standard python int operators, eg <code>__and__</code> and <code>__xor__</code> etc, specifically whenever the result is finally printed I want it represented in Hex format. (Kind of like putting my calculator into Hex mode)</p> <pre><code>class Hex(int): def __repr__(self): return "0x%x"%self __str__=__repr__ # this certainly helps with printing if __name__=="__main__": print Hex(0x1abe11ed) ^ Hex(440720179) print Hex(Hex(0x1abe11ed) ^ Hex(440720179)) </code></pre> <p>Ideally BOTH line of output should be hexadecimal: 0xfacade, however the first one yields decimal: 16435934</p> <p>Any ideas?</p>
2
2009-08-07T02:24:52Z
1,242,598
<p>Override <code>__str__</code> as well.</p> <p><code>__repr__</code> is used when repr(o) is called, and to display a value at the interactive prompt. <code>__str__</code> is called for most instances of stringifying an object, including when it is printed.</p> <p>The default <code>__str__</code> behavior for an object is to fall back to the <code>repr</code>, but <code>int</code> provides its own <code>__str__</code> method (which is identical to <code>__repr__</code> (before Python 3), but does not <em>fall back</em> to <code>__repr__</code>).</p>
0
2009-08-07T02:29:09Z
[ "python", "hex", "subclassing", "representation" ]
subclassing int to attain a Hex representation
1,242,589
<p>Basically I want to have access to all standard python int operators, eg <code>__and__</code> and <code>__xor__</code> etc, specifically whenever the result is finally printed I want it represented in Hex format. (Kind of like putting my calculator into Hex mode)</p> <pre><code>class Hex(int): def __repr__(self): return "0x%x"%self __str__=__repr__ # this certainly helps with printing if __name__=="__main__": print Hex(0x1abe11ed) ^ Hex(440720179) print Hex(Hex(0x1abe11ed) ^ Hex(440720179)) </code></pre> <p>Ideally BOTH line of output should be hexadecimal: 0xfacade, however the first one yields decimal: 16435934</p> <p>Any ideas?</p>
2
2009-08-07T02:24:52Z
1,242,640
<p>You should define <code>__repr__</code> and <code>__str__</code> separately:</p> <pre><code>class Hex(int): def __repr__(self): return "Hex(0x%x)" % self def __str__(self): return "0x%x" % self </code></pre> <p>The <code>__repr__</code> function should (if possible) provide Python text that can be <code>eval()</code>uated to reconstruct the original object. On the other hand, <code>__str__</code> can just return a human readable representation of the object.</p>
7
2009-08-07T02:49:45Z
[ "python", "hex", "subclassing", "representation" ]
subclassing int to attain a Hex representation
1,242,589
<p>Basically I want to have access to all standard python int operators, eg <code>__and__</code> and <code>__xor__</code> etc, specifically whenever the result is finally printed I want it represented in Hex format. (Kind of like putting my calculator into Hex mode)</p> <pre><code>class Hex(int): def __repr__(self): return "0x%x"%self __str__=__repr__ # this certainly helps with printing if __name__=="__main__": print Hex(0x1abe11ed) ^ Hex(440720179) print Hex(Hex(0x1abe11ed) ^ Hex(440720179)) </code></pre> <p>Ideally BOTH line of output should be hexadecimal: 0xfacade, however the first one yields decimal: 16435934</p> <p>Any ideas?</p>
2
2009-08-07T02:24:52Z
1,242,716
<p>You'll need to get the operators (+, -, ** etc) to return instances of Hex. As is, it will return ints, i.e.</p> <pre><code>class Hex(int): def __repr__(self): return "Hex(0x%x)" % self def __str__(self): return "0x%x" % self &gt;&gt;&gt; h1 = Hex(100) &gt;&gt;&gt; h2 = Hex(1000) &gt;&gt;&gt; h1 Hex(0x64) &gt;&gt;&gt; h2 Hex(0x3e8) &gt;&gt;&gt; h1+h2 1100 &gt;&gt;&gt; type(h1+h2) &lt;type 'int'&gt; </code></pre> <p>So, you can override the various operators:</p> <pre><code>class Hex(int): def __repr__(self): return "Hex(0x%x)" % self def __str__(self): return "0x%x" % self def __add__(self, other): return Hex(super(Hex, self).__add__(other)) def __sub__(self, other): return self.__add__(-other) def __pow__(self, power): return Hex(super(Hex, self).__pow__(power)) def __xor__(self, other): return Hex(super(Hex, self).__xor__(other)) &gt;&gt;&gt; h1 = Hex(100) &gt;&gt;&gt; h2 = Hex(1000) &gt;&gt;&gt; h1+h2 Hex(0x44c) &gt;&gt;&gt; type(h1+h2) &lt;class '__main__.Hex'&gt; &gt;&gt;&gt; h1 += h2 &gt;&gt;&gt; h1 Hex(0x44c) &gt;&gt;&gt; h2 ** 2 Hex(0xf4240) &gt;&gt;&gt; Hex(0x1abe11ed) ^ Hex(440720179) &gt;&gt;&gt; Hex(0xfacade) </code></pre> <p>I don't know about this, I feel that there must be a better way without having to override every operator to return an instance of <code>Hex</code>???</p>
1
2009-08-07T03:21:11Z
[ "python", "hex", "subclassing", "representation" ]
subclassing int to attain a Hex representation
1,242,589
<p>Basically I want to have access to all standard python int operators, eg <code>__and__</code> and <code>__xor__</code> etc, specifically whenever the result is finally printed I want it represented in Hex format. (Kind of like putting my calculator into Hex mode)</p> <pre><code>class Hex(int): def __repr__(self): return "0x%x"%self __str__=__repr__ # this certainly helps with printing if __name__=="__main__": print Hex(0x1abe11ed) ^ Hex(440720179) print Hex(Hex(0x1abe11ed) ^ Hex(440720179)) </code></pre> <p>Ideally BOTH line of output should be hexadecimal: 0xfacade, however the first one yields decimal: 16435934</p> <p>Any ideas?</p>
2
2009-08-07T02:24:52Z
1,242,838
<p>In response to your comment: </p> <p>You could write a Mixin by yourself:</p> <pre><code>class IntMathMixin: def __add__(self, other): return type(self)(int(self).__add__(int(other))) # ... analog for the others </code></pre> <p>Then use it like this:</p> <pre><code>class Hex(IntMathMixin, int): def __repr__(self): return "0x%x"%self __str__=__repr__ </code></pre>
1
2009-08-07T04:05:38Z
[ "python", "hex", "subclassing", "representation" ]
subclassing int to attain a Hex representation
1,242,589
<p>Basically I want to have access to all standard python int operators, eg <code>__and__</code> and <code>__xor__</code> etc, specifically whenever the result is finally printed I want it represented in Hex format. (Kind of like putting my calculator into Hex mode)</p> <pre><code>class Hex(int): def __repr__(self): return "0x%x"%self __str__=__repr__ # this certainly helps with printing if __name__=="__main__": print Hex(0x1abe11ed) ^ Hex(440720179) print Hex(Hex(0x1abe11ed) ^ Hex(440720179)) </code></pre> <p>Ideally BOTH line of output should be hexadecimal: 0xfacade, however the first one yields decimal: 16435934</p> <p>Any ideas?</p>
2
2009-08-07T02:24:52Z
1,243,045
<p>A <em>class decorator</em>, especially in Python 2.6 and beyond, is the handiest way to wrap a lot of methods to "return an instance of this class's type rather than an instance of the superclass", which, as other have indicated, is your underlying issue (beyond quibbles with <code>__str__</code> vs <code>__repr__</code>, worthwhile but not at all resolutory for your problem;-).</p> <pre><code>def returnthisclassfrom(specials): specialnames = ['__%s__' % s for s in specials.split()] def wrapit(cls, method): return lambda *a: cls(method(*a)) def dowrap(cls): for n in specialnames: method = getattr(cls, n) setattr(cls, n, wrapit(cls, method)) return cls return dowrap @returnthisclassfrom('and or xor') class Hex(int): def __repr__(self): return hex(self) __str__ = __repr__ a = Hex(2345) b = Hex(5432) print a, b, a^b </code></pre> <p>In Python 2.6, this emits</p> <pre><code>0x929 0x1538 0x1c11 </code></pre> <p>as desired. Of course you can add more methodnames to the decorator, etc; if you're stuck with Python 2.5, remove the decorating line (the one starting with <code>@</code>) and use instead</p> <pre><code>class Hex(int): def __repr__(self): return hex(self) __str__ = __repr__ Hex = returnthisclassfrom('and or xor')(Hex) </code></pre> <p>a mite less elegant, but just as effective;-)</p> <p><strong>Edit</strong>: fixed an occurence of "the usual scoping issue" in the code.</p>
6
2009-08-07T05:35:09Z
[ "python", "hex", "subclassing", "representation" ]
pygtk: free variable referenced before assignment in enclosing scope
1,242,593
<p>Very bizarre scoping error which I can't even see. Inside of an updater function, I have a nested helper function to... help w/ something:</p> <pre><code> def attach_row(ws,r1,r2): es = [] for i,w in enumerate(ws): eb = gtk.EventBox() a = gtk.Alignment(xalign=0.0,yalign=0.5) a.add(w) eb.add(a) eb.set_style(self.rowStyle.copy()) es.append(eb) self.table.attach(eb, i, i+1, r1, r2, xoptions=gtk.EXPAND|gtk.FILL, yoptions=gtk.SHRINK) def ene(_,ev): for eb in es: eb.set_state(gtk.STATE_PRELIGHT) def lne(_,ev): for eb in es: eb.set_state(gtk.STATE_NORMAL) for eb in es: eb.connect('enter-notify-event', ene) eb.connect('leave-notify-event', lne) </code></pre> <p>This works once in a while, but if the update() function runs too much, I eventually get:</p> <pre><code> for eb in es: NameError: free variable 'es' referenced before assignment in enclosing scope </code></pre> <p>What is causing this? es is most certainly assigned before those functions ever get called. Isn't that right? Is some bizarre thing happening where for some reason the ene() for a previously created row gets called while the new one is being created, and the closed over <code>es</code> gets overwritten?</p>
6
2009-08-07T02:25:52Z
1,242,794
<p>Don't have enough points to leave this as a comment (just registered) ...</p> <ul> <li>No 'es' variable globally or in a higher scope?</li> <li>attach_row isn't also a nested function?</li> <li>NameError exception points to for loop line in ene or lne functions?</li> </ul> <p>One possible, but icky, workaround might be to make ene and lne classes that are instantiated and callable as functions via a __call__() method.</p>
0
2009-08-07T03:47:44Z
[ "python", "programming-languages", "gtk", "closures", "semantics" ]
pygtk: free variable referenced before assignment in enclosing scope
1,242,593
<p>Very bizarre scoping error which I can't even see. Inside of an updater function, I have a nested helper function to... help w/ something:</p> <pre><code> def attach_row(ws,r1,r2): es = [] for i,w in enumerate(ws): eb = gtk.EventBox() a = gtk.Alignment(xalign=0.0,yalign=0.5) a.add(w) eb.add(a) eb.set_style(self.rowStyle.copy()) es.append(eb) self.table.attach(eb, i, i+1, r1, r2, xoptions=gtk.EXPAND|gtk.FILL, yoptions=gtk.SHRINK) def ene(_,ev): for eb in es: eb.set_state(gtk.STATE_PRELIGHT) def lne(_,ev): for eb in es: eb.set_state(gtk.STATE_NORMAL) for eb in es: eb.connect('enter-notify-event', ene) eb.connect('leave-notify-event', lne) </code></pre> <p>This works once in a while, but if the update() function runs too much, I eventually get:</p> <pre><code> for eb in es: NameError: free variable 'es' referenced before assignment in enclosing scope </code></pre> <p>What is causing this? es is most certainly assigned before those functions ever get called. Isn't that right? Is some bizarre thing happening where for some reason the ene() for a previously created row gets called while the new one is being created, and the closed over <code>es</code> gets overwritten?</p>
6
2009-08-07T02:25:52Z
1,243,009
<p>Pretty mysterious indeed -- looks like the closure's disappearing out from under the inner functions. Wonder if that's related to <em>how</em> pygtk holds such callback functions (I'm not familiar with its internals). To try to probe for that -- what happens if you also append ene and lne to a global list at the end of <code>attach_row</code>, just to make sure they're held "normally" somewhere so their closure survives -- does the problem persist in that case?</p> <p>If it does, then I have to admit the problem's just TOO mysterious and concur with the previous answer suggesting, as a workaround, the use of callables that hold their state in a clearer way (I'd suggest two bound methods of one class instance, since they share their state, but two instance of a single class with <code>__call__</code> and receiving the state to set and the list of event boxes in its <code>__init__</code> is surely also reasonable -- having two separate classes IMHO would be a slight exaggeration;-).</p>
4
2009-08-07T05:17:27Z
[ "python", "programming-languages", "gtk", "closures", "semantics" ]
Beautiful Soup cannot find a CSS class if the object has other classes, too
1,242,755
<p>if a page has <code>&lt;div class="class1"&gt;</code> and <code>&lt;p class="class1"&gt;</code>, then <code>soup.findAll(True, 'class1')</code> will find them both.</p> <p>If it has <code>&lt;p class="class1 class2"&gt;</code>, though, it will not be found. How do I find all objects with a certain class, regardless of whether they have other classes, too?</p>
34
2009-08-07T03:34:19Z
1,242,801
<p>Unfortunately, BeautifulSoup treats this as a class with a space in it <code>'class1 class2'</code> rather than two classes <code>['class1','class2']</code>. A workaround is to use a regular expression to search for the class instead of a string.</p> <p>This works: </p> <pre><code>soup.findAll(True, {'class': re.compile(r'\bclass1\b')}) </code></pre>
32
2009-08-07T03:49:51Z
[ "python", "screen-scraping", "beautifulsoup" ]
Beautiful Soup cannot find a CSS class if the object has other classes, too
1,242,755
<p>if a page has <code>&lt;div class="class1"&gt;</code> and <code>&lt;p class="class1"&gt;</code>, then <code>soup.findAll(True, 'class1')</code> will find them both.</p> <p>If it has <code>&lt;p class="class1 class2"&gt;</code>, though, it will not be found. How do I find all objects with a certain class, regardless of whether they have other classes, too?</p>
34
2009-08-07T03:34:19Z
1,245,368
<p>You should use <a href="http://lxml.de/" rel="nofollow">lxml</a>. It works with multiple class values separated by spaces ('class1 class2').</p> <p>Despite its name, lxml is also for parsing and scraping HTML. It's much, much faster than BeautifulSoup, and it even handles "broken" HTML better than BeautifulSoup (their claim to fame). It has a compatibility API for BeautifulSoup too if you don't want to learn the lxml API.</p> <p><a href="http://blog.ianbicking.org/2008/12/10/lxml-an-underappreciated-web-scraping-library/" rel="nofollow">Ian Bicking agrees</a> and prefers lxml over BeautifulSoup.</p> <p>There's no reason to use BeautifulSoup anymore, unless you're on Google App Engine or something where anything not purely Python isn't allowed.</p> <p>You can even use CSS selectors with lxml, so it's far easier to use than BeautifulSoup. Try playing around with it in an interactive Python console.</p>
10
2009-08-07T15:18:07Z
[ "python", "screen-scraping", "beautifulsoup" ]
Beautiful Soup cannot find a CSS class if the object has other classes, too
1,242,755
<p>if a page has <code>&lt;div class="class1"&gt;</code> and <code>&lt;p class="class1"&gt;</code>, then <code>soup.findAll(True, 'class1')</code> will find them both.</p> <p>If it has <code>&lt;p class="class1 class2"&gt;</code>, though, it will not be found. How do I find all objects with a certain class, regardless of whether they have other classes, too?</p>
34
2009-08-07T03:34:19Z
18,424,791
<p>Just in case anybody comes across this question. BeautifulSoup now supports this:</p> <pre><code>Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] Type "copyright", "credits" or "license" for more information. In [1]: import bs4 In [2]: soup = bs4.BeautifulSoup('&lt;div class="foo bar"&gt;&lt;/div&gt;') In [3]: soup(attrs={'class': 'bar'}) Out[3]: [&lt;div class="foo bar"&gt;&lt;/div&gt;] </code></pre> <p>Also, you don't have to type findAll anymore.</p>
14
2013-08-25T01:28:49Z
[ "python", "screen-scraping", "beautifulsoup" ]
Beautiful Soup cannot find a CSS class if the object has other classes, too
1,242,755
<p>if a page has <code>&lt;div class="class1"&gt;</code> and <code>&lt;p class="class1"&gt;</code>, then <code>soup.findAll(True, 'class1')</code> will find them both.</p> <p>If it has <code>&lt;p class="class1 class2"&gt;</code>, though, it will not be found. How do I find all objects with a certain class, regardless of whether they have other classes, too?</p>
34
2009-08-07T03:34:19Z
28,291,193
<p>It’s very useful to search for a tag that has a certain CSS class, but the name of the CSS attribute, “class”, is a reserved word in Python. Using class as a keyword argument will give you a syntax error. As of Beautiful Soup 4.1.2, you can search by CSS class using the keyword argument class_:</p> <p><strong>Like:</strong></p> <pre><code>soup.find_all("a", class_="class1") </code></pre>
2
2015-02-03T04:06:15Z
[ "python", "screen-scraping", "beautifulsoup" ]
Finding python site-packages directory with CMake
1,242,904
<p>I use CMake to build my application. How can I find where the python site-packages directory is located? I need the path in order to compile an extension to python.</p> <p>CMake has to be able to find the path on all three major OS as I plan to deploy my application on Linux, Mac and Windows.</p> <p>I tried using</p> <pre><code>include(FindPythonLibs) find_path( PYTHON_SITE_PACKAGES site-packages ${PYTHON_INCLUDE_PATH}/.. ) </code></pre> <p>however that does not work. </p> <p>I can also obtain the path by running </p> <pre><code>python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()" </code></pre> <p>on the shell, but how would I invoke that from CMake ?</p> <p>SOLUTION:</p> <p>Thanks, Alex. So the command that gives me the site-package dir is:</p> <pre><code>execute_process ( COMMAND python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()" OUTPUT_VARIABLE PYTHON_SITE_PACKAGES OUTPUT_STRIP_TRAILING_WHITESPACE) </code></pre> <p>The OUTPUT_STRIP_TRAILING_WHITESPACE command is needed to remove the trailing new line.</p>
9
2009-08-07T04:36:09Z
1,242,979
<p>You can execute external processes in cmake with <a href="http://www.cmake.org/cmake/help/cmake2.6docs.html#command:execute%5Fprocess">execute_process</a> (and get the output into a variable if needed, as it would be here).</p>
5
2009-08-07T05:06:40Z
[ "python", "cmake" ]
Finding python site-packages directory with CMake
1,242,904
<p>I use CMake to build my application. How can I find where the python site-packages directory is located? I need the path in order to compile an extension to python.</p> <p>CMake has to be able to find the path on all three major OS as I plan to deploy my application on Linux, Mac and Windows.</p> <p>I tried using</p> <pre><code>include(FindPythonLibs) find_path( PYTHON_SITE_PACKAGES site-packages ${PYTHON_INCLUDE_PATH}/.. ) </code></pre> <p>however that does not work. </p> <p>I can also obtain the path by running </p> <pre><code>python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()" </code></pre> <p>on the shell, but how would I invoke that from CMake ?</p> <p>SOLUTION:</p> <p>Thanks, Alex. So the command that gives me the site-package dir is:</p> <pre><code>execute_process ( COMMAND python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()" OUTPUT_VARIABLE PYTHON_SITE_PACKAGES OUTPUT_STRIP_TRAILING_WHITESPACE) </code></pre> <p>The OUTPUT_STRIP_TRAILING_WHITESPACE command is needed to remove the trailing new line.</p>
9
2009-08-07T04:36:09Z
2,539,171
<p>I suggest to use get_python_lib(True) if you are making this extension as a dynamic library. This first parameter should be true if you need the platform specific location (in 64bit linux machines, this could be /usr/lib64 instead of /usr/lib)</p>
1
2010-03-29T15:34:01Z
[ "python", "cmake" ]
Finding python site-packages directory with CMake
1,242,904
<p>I use CMake to build my application. How can I find where the python site-packages directory is located? I need the path in order to compile an extension to python.</p> <p>CMake has to be able to find the path on all three major OS as I plan to deploy my application on Linux, Mac and Windows.</p> <p>I tried using</p> <pre><code>include(FindPythonLibs) find_path( PYTHON_SITE_PACKAGES site-packages ${PYTHON_INCLUDE_PATH}/.. ) </code></pre> <p>however that does not work. </p> <p>I can also obtain the path by running </p> <pre><code>python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()" </code></pre> <p>on the shell, but how would I invoke that from CMake ?</p> <p>SOLUTION:</p> <p>Thanks, Alex. So the command that gives me the site-package dir is:</p> <pre><code>execute_process ( COMMAND python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()" OUTPUT_VARIABLE PYTHON_SITE_PACKAGES OUTPUT_STRIP_TRAILING_WHITESPACE) </code></pre> <p>The OUTPUT_STRIP_TRAILING_WHITESPACE command is needed to remove the trailing new line.</p>
9
2009-08-07T04:36:09Z
40,006,251
<p>Slightly updated version that I used for <a href="https://github.com/lcm-proj-lcm" rel="nofollow">lcm</a>:</p> <pre><code>execute_process( COMMAND "${PYTHON_EXECUTABLE}" -c "if True: from distutils import sysconfig as sc print(sc.get_python_lib(prefix='', plat_specific=True))" OUTPUT_VARIABLE PYTHON_SITE OUTPUT_STRIP_TRAILING_WHITESPACE) </code></pre> <p>This sets <code>PYTHON_SITE</code> to the appropriate prefix-relative path, suitable for use like:</p> <pre><code>install( FILES ${mypackage_python_files} DESTINATION ${PYTHON_SITE}/mypackage) </code></pre> <p>(Please don't install to an absolute path! Doing so bypasses <code>CMAKE_INSTALL_PREFIX</code>.)</p>
0
2016-10-12T18:52:08Z
[ "python", "cmake" ]
How to disable Control-C in a WindowsXP Python console program?
1,243,047
<p>I'd like to put my cmd.com window into a mode where Control-C does not generate a SIGINT signal to Python (ActiveState if it matters).</p> <p>I know I can use the signal module to handle SIGINT. The problem is that handling SIGINT is too late; by the time it is handled, it has already interrupted a system call.</p> <p>I'd like something equivalent to the *nix "raw" mode. Just let the input queue up and when it is safe for my application to read it, it will.</p> <p>Maddeningly enough, msvcrt.getch() seems to return Control-C as a character. But that only works while the program is blocked by getch() itself. If I am in another system call (sleep, just to use an example), I get the SIGINT.</p>
0
2009-08-07T05:35:40Z
1,243,099
<p>You need to call the win32 API function <a href="http://msdn.microsoft.com/en-us/library/ms686016%28VS.85%29.aspx" rel="nofollow">SetConsoleCtrlHandler</a> with NULL (0) as its first parameter and TRUE (1) as its second parameter. If you're already using pywin32, <a href="http://docs.activestate.com/activepython/2.5/pywin32/win32api%5F%5FSetConsoleCtrlHandler%5Fmeth.html" rel="nofollow">win32.SetConsoleCtrlHandler</a> is fine for the purpose, otherwise ctypes should work, specifically via <code>ctypes.windll.kernel32.SetConsoleCtrlHandler(0, 1)</code>/</p>
3
2009-08-07T05:51:10Z
[ "python", "windows-xp", "console-application", "copy-paste", "control-c" ]
Qt Image From Web
1,243,064
<p>I'd like PyQt to load an image and display it from the web. Dozens of examples I've found online did not work, as they are for downloading the image.</p> <p>I simply want to view it.</p> <p>Something like</p> <pre><code>from PyQt4.QtWebKit import * web = QWebView() web.load(QUrl("http://stackoverflow.com/content/img/so/logo.png")) </code></pre>
2
2009-08-07T05:41:50Z
1,243,137
<pre><code>import sys from PyQt4 import QtCore, QtGui, QtWebKit app = QtGui.QApplication(sys.argv) web = QtWebKit.QWebView() web.load(QtCore.QUrl("http://upload.wikimedia.org/wikipedia/commons/a/af/Tux.png")) web.show() sys.exit(app.exec_()) </code></pre>
5
2009-08-07T06:00:46Z
[ "python", "qt", "pyqt", "qwebview", "qwebelement" ]
Validating XML in Python without non-python dependencies
1,243,449
<p>I'm writing a small Python app for distribution. I need to include simple XML validation (it's a debugging tool), but I want to avoid any dependencies on compiled C libraries such as lxml or pyxml as those will make the resulting app much harder to distribute. I can't find anything that seems to fit the bill - for DTDs, Relax NG or XML Schema. Any suggestions?</p>
3
2009-08-07T07:36:34Z
1,243,473
<p>Why don't you try invoking an online XML validator and parsing the results? </p> <p>I couldn't find any free REST or SOAP based services but it would be easy enough to use a normal HTML form based one such as <a href="http://www.stg.brown.edu/service/xmlvalid/" rel="nofollow">this one</a> or <a href="http://www.validome.org/xml/" rel="nofollow">this one</a>. You just need to construct the correct request and parse the results (<a href="http://docs.python.org/library/httplib.html" rel="nofollow">httplib</a> may be of help here if you don't want to use a third party library such as <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">mechanize</a> to easy the pain).</p>
1
2009-08-07T07:45:09Z
[ "python", "xml", "validation", "schema", "dtd" ]
Validating XML in Python without non-python dependencies
1,243,449
<p>I'm writing a small Python app for distribution. I need to include simple XML validation (it's a debugging tool), but I want to avoid any dependencies on compiled C libraries such as lxml or pyxml as those will make the resulting app much harder to distribute. I can't find anything that seems to fit the bill - for DTDs, Relax NG or XML Schema. Any suggestions?</p>
3
2009-08-07T07:36:34Z
1,243,508
<p>Do you mean something like <a href="http://www.familieleuthe.de/MiniXsv.html" rel="nofollow">MiniXsv</a>? I have never used it, but from the website, we can read that</p> <blockquote> <p>minixsv is a lightweight XML schema validator package written in pure Python (at least Python 2.4 is required).</p> </blockquote> <p>so, it should work for you.</p> <p>I believe that <a href="http://effbot.org/zone/element-index.htm" rel="nofollow">ElementTree</a> could also be used for that goal, but I am not 100% sure.</p>
4
2009-08-07T07:59:53Z
[ "python", "xml", "validation", "schema", "dtd" ]
Validating XML in Python without non-python dependencies
1,243,449
<p>I'm writing a small Python app for distribution. I need to include simple XML validation (it's a debugging tool), but I want to avoid any dependencies on compiled C libraries such as lxml or pyxml as those will make the resulting app much harder to distribute. I can't find anything that seems to fit the bill - for DTDs, Relax NG or XML Schema. Any suggestions?</p>
3
2009-08-07T07:36:34Z
1,243,559
<p>I haven't looked at it in a while so it might have changed, but Fourthought's <a href="http://www.fourthought.com/4Suite.html" rel="nofollow">4Suite</a> (<a href="http://4suite.org/index.xhtml" rel="nofollow">community edition</a>) could still be pure Python.</p> <p>Edit: just browsed through the docs and it's <strong>mostly</strong> Python which probably isn't enough for you.</p>
1
2009-08-07T08:18:42Z
[ "python", "xml", "validation", "schema", "dtd" ]
Validating XML in Python without non-python dependencies
1,243,449
<p>I'm writing a small Python app for distribution. I need to include simple XML validation (it's a debugging tool), but I want to avoid any dependencies on compiled C libraries such as lxml or pyxml as those will make the resulting app much harder to distribute. I can't find anything that seems to fit the bill - for DTDs, Relax NG or XML Schema. Any suggestions?</p>
3
2009-08-07T07:36:34Z
1,243,840
<p>The beautifulsoup module is pure Python (and a single .py file), but I don't know if it will fulfill your validation needs, I've only used it for quickly extracting some fields on large XMLs.</p> <p><a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">http://www.crummy.com/software/BeautifulSoup/</a></p>
0
2009-08-07T09:32:47Z
[ "python", "xml", "validation", "schema", "dtd" ]
Access a large file in a zip archive with HTML in a python-webkit WebView without extracting
1,243,485
<p>I apologize for any confusion from the question title. It's kind of a complex situation with components that are new to me so I'm unsure of how to describe it succinctly.</p> <p>I have some xml data and an image in an archive (zip in this case, but could easily be tar or tar.gz) and using python, gtk, and webkit, place the image in a webkit.WebView, along with some of the other data. The xml is child's play to access without extracting the files, but the image is another issue.</p> <p>I'd like to avoid extracting the image to to the hdd before putting it in the WebView and doing a base64 encode of the image data feels cludgy, especially since the images could potentially reach tens of megabytes.</p> <p>Basically I'm looking for a way to construct an URI to a file stored inside a container file.</p> <p>I asked a few days ago in IRC and was directed toward virtual file systems. In the searches I performed I found a few references to creating a vfs from a zip file, but no examples or even much in the way of documentation on virtual file systems themselves (gnomeVFS, gvfs, gio.) I may be looking in all the wrong places, however.</p>
1
2009-08-07T07:48:55Z
1,243,541
<p>The <a href="http://docs.python.org/library/zipfile.html" rel="nofollow"><code>zipfile</code></a> module in the standard Python library provides tools to create, read, write, append, and list a ZIP file. </p> <p>Using <a href="http://docs.python.org/library/zipfile.html#zipfile.ZipFile.read" rel="nofollow"><code>ZipFile.read(name[, pwd])</code></a> ( return the bytes of the file name in the archive), you can apply <a href="http://docs.python.org/library/base64.html#base64.b64encode" rel="nofollow"><code>base64.b64encode(s[, altchars])</code></a> to the content. Note that in this straightforward process, the unzipped <em>and</em> the encoded versions are stored in memory.</p>
1
2009-08-07T08:12:37Z
[ "python", "zip", "gzip", "tar", "virtualfilesystem" ]
Programmatically extract data from an Excel spreadsheet
1,243,545
<p>Is there a simple way, using some common Unix scripting language (Perl/Python/Ruby) or command line utility, to convert an Excel Spreadsheet file to CSV? Specifically, this one:</p> <p><a href="http://www.econ.yale.edu/~shiller/data/ie_data.xls">http://www.econ.yale.edu/~shiller/data/ie_data.xls</a></p> <p>And specifically the third sheet of that spreadsheet (the first two being charts).</p>
6
2009-08-07T08:13:54Z
1,243,548
<p>I may have found an acceptable answer already:</p> <p><a href="http://search.cpan.org/perldoc/xls2csv" rel="nofollow">xls2csv</a></p> <p>But interested to hear what other options there are, or about tools in other languages.</p>
1
2009-08-07T08:15:32Z
[ "python", "ruby", "perl", "excel", "csv" ]
Programmatically extract data from an Excel spreadsheet
1,243,545
<p>Is there a simple way, using some common Unix scripting language (Perl/Python/Ruby) or command line utility, to convert an Excel Spreadsheet file to CSV? Specifically, this one:</p> <p><a href="http://www.econ.yale.edu/~shiller/data/ie_data.xls">http://www.econ.yale.edu/~shiller/data/ie_data.xls</a></p> <p>And specifically the third sheet of that spreadsheet (the first two being charts).</p>
6
2009-08-07T08:13:54Z
1,243,628
<p>Maybe <a href="http://pypi.python.org/pypi/xlrd">xlrd</a> will do the Job (in Python)</p> <p>edit: I should really learn to read questions. But writing csv shouldn't be a huge problem so maybe you can actually use it.</p>
8
2009-08-07T08:38:03Z
[ "python", "ruby", "perl", "excel", "csv" ]
Programmatically extract data from an Excel spreadsheet
1,243,545
<p>Is there a simple way, using some common Unix scripting language (Perl/Python/Ruby) or command line utility, to convert an Excel Spreadsheet file to CSV? Specifically, this one:</p> <p><a href="http://www.econ.yale.edu/~shiller/data/ie_data.xls">http://www.econ.yale.edu/~shiller/data/ie_data.xls</a></p> <p>And specifically the third sheet of that spreadsheet (the first two being charts).</p>
6
2009-08-07T08:13:54Z
1,243,631
<p>For python, there are a number of options, see <a href="http://pypi.python.org/pypi/xlrd" rel="nofollow">here</a>, <a href="http://pyxlreader.sourceforge.net/" rel="nofollow">here</a> and <a href="http://www.velocityreviews.com/forums/t352440-how-to-read-excel-files-in-python.html" rel="nofollow">here</a>. Note that the last option will only work on Windows with Excel installed.</p>
1
2009-08-07T08:38:19Z
[ "python", "ruby", "perl", "excel", "csv" ]
Programmatically extract data from an Excel spreadsheet
1,243,545
<p>Is there a simple way, using some common Unix scripting language (Perl/Python/Ruby) or command line utility, to convert an Excel Spreadsheet file to CSV? Specifically, this one:</p> <p><a href="http://www.econ.yale.edu/~shiller/data/ie_data.xls">http://www.econ.yale.edu/~shiller/data/ie_data.xls</a></p> <p>And specifically the third sheet of that spreadsheet (the first two being charts).</p>
6
2009-08-07T08:13:54Z
1,243,763
<p>There is a really good Perl library for xls reading: <a href="http://search.cpan.org/perldoc/Spreadsheet::ParseExcel" rel="nofollow">Spreadsheet::ParseExcel</a>.</p>
14
2009-08-07T09:15:30Z
[ "python", "ruby", "perl", "excel", "csv" ]
Programmatically extract data from an Excel spreadsheet
1,243,545
<p>Is there a simple way, using some common Unix scripting language (Perl/Python/Ruby) or command line utility, to convert an Excel Spreadsheet file to CSV? Specifically, this one:</p> <p><a href="http://www.econ.yale.edu/~shiller/data/ie_data.xls">http://www.econ.yale.edu/~shiller/data/ie_data.xls</a></p> <p>And specifically the third sheet of that spreadsheet (the first two being charts).</p>
6
2009-08-07T08:13:54Z
1,244,244
<p>Options exist for all three languages. The question is - which one are you most familiar with. This is the language you should use, for sure. And if you're not familiar with either, this application is not really a great example of picking between the languages.</p> <p>Opinionated P.S: if you don't know any of the languages, just learn Python and use <code>xlrd</code>.</p>
1
2009-08-07T11:23:57Z
[ "python", "ruby", "perl", "excel", "csv" ]
Programmatically extract data from an Excel spreadsheet
1,243,545
<p>Is there a simple way, using some common Unix scripting language (Perl/Python/Ruby) or command line utility, to convert an Excel Spreadsheet file to CSV? Specifically, this one:</p> <p><a href="http://www.econ.yale.edu/~shiller/data/ie_data.xls">http://www.econ.yale.edu/~shiller/data/ie_data.xls</a></p> <p>And specifically the third sheet of that spreadsheet (the first two being charts).</p>
6
2009-08-07T08:13:54Z
1,244,248
<p>You can use <a href="http://sourceforge.net/projects/pyexcelerator/" rel="nofollow">pyexcelerator</a> in python.</p> <p>This code (included in the <code>examples</code> folder of pyexcelerator as <code>xls2csv.py</code>) extracts all sheets from the spreadsheets and outputs them to <code>stdout</code> as CSV.</p> <p>You can easily change the code to do what you want.</p> <p>The cool thing about pyexcelerator is that you can also use it to <strong>write/create</strong> excel xls files, without having excel installed.</p> <pre><code>#!/usr/bin/env python # -*- coding: windows-1251 -*- # Copyright (C) 2005 Kiseliov Roman __rev_id__ = """$Id: xls2csv.py,v 1.1 2005/05/19 09:27:42 rvk Exp $""" from pyExcelerator import * import sys me, args = sys.argv[0], sys.argv[1:] if args: for arg in args: print &gt;&gt;sys.stderr, 'extracting data from', arg for sheet_name, values in parse_xls(arg, 'cp1251'): # parse_xls(arg) -- default encoding matrix = [[]] print 'Sheet = "%s"' % sheet_name.encode('cp866', 'backslashreplace') print '----------------' for row_idx, col_idx in sorted(values.keys()): v = values[(row_idx, col_idx)] if isinstance(v, unicode): v = v.encode('cp866', 'backslashreplace') else: v = str(v) last_row, last_col = len(matrix), len(matrix[-1]) while last_row &lt; row_idx: matrix.extend([[]]) last_row = len(matrix) while last_col &lt; col_idx: matrix[-1].extend(['']) last_col = len(matrix[-1]) matrix[-1].extend([v]) for row in matrix: csv_row = ','.join(row) print csv_row else: print 'usage: %s (inputfile)+' % me </code></pre>
3
2009-08-07T11:26:27Z
[ "python", "ruby", "perl", "excel", "csv" ]
Programmatically extract data from an Excel spreadsheet
1,243,545
<p>Is there a simple way, using some common Unix scripting language (Perl/Python/Ruby) or command line utility, to convert an Excel Spreadsheet file to CSV? Specifically, this one:</p> <p><a href="http://www.econ.yale.edu/~shiller/data/ie_data.xls">http://www.econ.yale.edu/~shiller/data/ie_data.xls</a></p> <p>And specifically the third sheet of that spreadsheet (the first two being charts).</p>
6
2009-08-07T08:13:54Z
1,415,131
<p>In Ruby, here is the code I use: (requires the excellent parseexcel gem) require 'parseexcel'</p> <pre><code>def excelGetSheet(worksheet) sheet=Array.new worksheet.each { |row| if row != nil # empty row? cells=Array.new j=0 row.each { |cell| cells &lt;&lt; cell.to_s('latin1') unless cell == nil j=j+1 } sheet &lt;&lt; cells end } return sheet end workbook = Spreadsheet::ParseExcel.parse("MyExcelFile.xls") sheet1 = excelGetSheet(workbook.worksheet(0)) puts sheet1.inspect </code></pre>
2
2009-09-12T13:34:31Z
[ "python", "ruby", "perl", "excel", "csv" ]
Programmatically extract data from an Excel spreadsheet
1,243,545
<p>Is there a simple way, using some common Unix scripting language (Perl/Python/Ruby) or command line utility, to convert an Excel Spreadsheet file to CSV? Specifically, this one:</p> <p><a href="http://www.econ.yale.edu/~shiller/data/ie_data.xls">http://www.econ.yale.edu/~shiller/data/ie_data.xls</a></p> <p>And specifically the third sheet of that spreadsheet (the first two being charts).</p>
6
2009-08-07T08:13:54Z
2,091,379
<p>for ruby, the spreadsheet gem is excellent to read write modify, ...excell files</p> <p><a href="https://github.com/zdavatz/spreadsheet" rel="nofollow">https://github.com/zdavatz/spreadsheet</a></p>
4
2010-01-19T05:45:08Z
[ "python", "ruby", "perl", "excel", "csv" ]
Programmatically extract data from an Excel spreadsheet
1,243,545
<p>Is there a simple way, using some common Unix scripting language (Perl/Python/Ruby) or command line utility, to convert an Excel Spreadsheet file to CSV? Specifically, this one:</p> <p><a href="http://www.econ.yale.edu/~shiller/data/ie_data.xls">http://www.econ.yale.edu/~shiller/data/ie_data.xls</a></p> <p>And specifically the third sheet of that spreadsheet (the first two being charts).</p>
6
2009-08-07T08:13:54Z
12,808,734
<p>This is quite late to the game, but I thought I'd add another option via Ruby using the gem "roo":</p> <pre> require 'rubygems' require 'roo' my_excel_file = Excelx.new("path/to/my_excel_file.xlsx") my_excel_file.default_sheet = my_excel_file.sheets[2] my_excel_file.to_csv("path/to/my_excel_file.csv") </pre>
3
2012-10-09T21:32:02Z
[ "python", "ruby", "perl", "excel", "csv" ]
can't edit line in python's command line in Linux
1,243,770
<p>I'm running the Python CLI under Linux:</p> <pre><code>bla:visualization&gt; python Python 2.1.1 (#18, Nov 1 2001, 11:15:13) [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2 Type "copyright", "credits" or "license" for more information. &gt;&gt;&gt; </code></pre> <p>For some reason the arrow keys and the delete key don't work:</p> <p><strong>delete:</strong></p> <pre><code>&gt;&gt;&gt; x^H^H^H </code></pre> <p><strong>up arrow:</strong></p> <pre><code>&gt;&gt;&gt; x^[[A^[[A </code></pre> <p>etc...</p> <p>How can I make these work?</p>
3
2009-08-07T09:16:42Z
1,243,818
<p>Install iPython ( <a href="http://ipython.scipy.org/" rel="nofollow">http://ipython.scipy.org/</a> but can be installed using easy_install or pip), it is much much better than the default CLI.</p>
3
2009-08-07T09:28:06Z
[ "python", "linux", "command-line" ]
can't edit line in python's command line in Linux
1,243,770
<p>I'm running the Python CLI under Linux:</p> <pre><code>bla:visualization&gt; python Python 2.1.1 (#18, Nov 1 2001, 11:15:13) [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2 Type "copyright", "credits" or "license" for more information. &gt;&gt;&gt; </code></pre> <p>For some reason the arrow keys and the delete key don't work:</p> <p><strong>delete:</strong></p> <pre><code>&gt;&gt;&gt; x^H^H^H </code></pre> <p><strong>up arrow:</strong></p> <pre><code>&gt;&gt;&gt; x^[[A^[[A </code></pre> <p>etc...</p> <p>How can I make these work?</p>
3
2009-08-07T09:16:42Z
1,243,851
<p>Try setting your terminal from the shell, with <a href="http://linux.die.net/man/1/stty" rel="nofollow"><code>stty</code></a>. Pay special attention to the special characters <code>erase</code> and <code>kill</code>. Your Python installation is 8 years old, consider updating to a newer version.</p>
3
2009-08-07T09:34:20Z
[ "python", "linux", "command-line" ]
can't edit line in python's command line in Linux
1,243,770
<p>I'm running the Python CLI under Linux:</p> <pre><code>bla:visualization&gt; python Python 2.1.1 (#18, Nov 1 2001, 11:15:13) [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2 Type "copyright", "credits" or "license" for more information. &gt;&gt;&gt; </code></pre> <p>For some reason the arrow keys and the delete key don't work:</p> <p><strong>delete:</strong></p> <pre><code>&gt;&gt;&gt; x^H^H^H </code></pre> <p><strong>up arrow:</strong></p> <pre><code>&gt;&gt;&gt; x^[[A^[[A </code></pre> <p>etc...</p> <p>How can I make these work?</p>
3
2009-08-07T09:16:42Z
1,243,902
<p>The basic problem is that your Python installation was likely not compiled with the <code>readline</code> library. You can confirm this by trying to import the <code>readline</code> module:</p> <pre><code>import readline </code></pre> <p>You should get an error when you import if <code>readline</code> is not present. </p> <p>If this is the case, there's not much you can do other than recompile Python with the <code>readline</code> library, if you can.</p>
6
2009-08-07T09:46:32Z
[ "python", "linux", "command-line" ]
can't edit line in python's command line in Linux
1,243,770
<p>I'm running the Python CLI under Linux:</p> <pre><code>bla:visualization&gt; python Python 2.1.1 (#18, Nov 1 2001, 11:15:13) [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2 Type "copyright", "credits" or "license" for more information. &gt;&gt;&gt; </code></pre> <p>For some reason the arrow keys and the delete key don't work:</p> <p><strong>delete:</strong></p> <pre><code>&gt;&gt;&gt; x^H^H^H </code></pre> <p><strong>up arrow:</strong></p> <pre><code>&gt;&gt;&gt; x^[[A^[[A </code></pre> <p>etc...</p> <p>How can I make these work?</p>
3
2009-08-07T09:16:42Z
15,301,417
<p>I had to install readline-devel to get this to work:</p> <p>yum install readline-devel</p> <p>Now my python command line editing keystrokes work properly.</p>
0
2013-03-08T19:05:01Z
[ "python", "linux", "command-line" ]
Accessing a pointer in an object's internal structure
1,243,806
<p>I'm using the pyOpenSSL interface to the OpenSSL library but it is missing some functions I need and I can't or don't want to modify it to support these methods (for various reasons).</p> <p>So what I want to achieve, is to retrieve the OpenSSL object pointer. After that, I will be able to call the missing functions through ctypes. What is the best method to do that ?</p> <p>I have already found that I can use id() to get the pointer to the pyOpenSSL object. How can I access the ssl variable with that.</p> <p>From pyOpenSSL/connections.h:</p> <pre><code> typedef struct { PyObject_HEAD SSL *ssl; ssl_ContextObj *context; PyObject *socket; PyThreadState *tstate; PyObject *app_data; } ssl_ConnectionObj; </code></pre>
1
2009-08-07T09:25:03Z
1,244,672
<p>Pointers doesn't really make much sense in Python, as you can't do anything with them. They would just be an integer. As you have noticed you can get the address of an object with the id method. But that's just what it is, the address. It's not a pointer, so you can't do anything with it.</p> <p>You could also see it like this: Everything in Python are pointers. The variable you have for the pyOpenSSL object <em>is</em> the pointer. But it is the pointer to the pyOpenSSL-object, not to the connection structure. It's unlikely you can access that structure directly.</p> <p>So you have to tell us what you want to do instead. Maybe there is another solution.</p>
3
2009-08-07T13:22:03Z
[ "python", "pointers", "internals" ]
Consuming COM events in Python
1,244,463
<p>I am trying to do a sample app in python which uses some COM objects. I've read the famous chapter 12 from Python Programing on Win32 but regarding this issue it only states:</p> <blockquote> <p>All event handling is done using normal <code>IConnectionPoint</code> interfaces, and although beyond the scope of this book, is fully supported by the standard Python COM framework.</p> </blockquote> <p>Can anybody shed some light on this? I'd need a simple starter sample. Something like adding code to this sample to catch the OnActivate event for the spreadsheet </p> <pre><code>import win32com.client xl = win32com.client.Dispatch("Excel.Application") ... </code></pre>
7
2009-08-07T12:31:53Z
1,244,513
<p>I haven't automated Excel, but I'm using some code from Microsoft's <a href="http://msdn.microsoft.com/en-us/library/ms722022%28VS.85%29.aspx">Speech API</a> that may be similar enough to get you started:</p> <pre><code>ListenerBase = win32com.client.getevents("SAPI.SpInProcRecoContext") class Listener(ListenerBase): def OnRecognition(self, _1, _2, _3, Result): """Callback whenever something is recognized.""" # Work with Result def OnHypothesis(self, _1, _2, Result): """Callback whenever we have a potential match.""" # Work with Result </code></pre> <p>then later in a main loop:</p> <pre><code> while not self.shutting_down.is_set(): # Trigger the event handlers if we have anything. pythoncom.PumpWaitingMessages() time.sleep(0.1) # Don't use up all our CPU checking constantly </code></pre> <p>Edit for more detail on the main loop:</p> <p>When something happens, the callback doesn't get called immediately; instead you have to call PumpWaitingMessages(), which checks if there are any events waiting and then calls the appropriate callback.</p> <p>If you want to do something else while this is happening, you'll have to run the loop in a separate thread (see the threading module); otherwise it can just sit at the bottom of your script. In my example I was running it in a separate thread because I also had a GUI running; the shutting_down variable is a threading.Event you can use to tell the looping thread to stop.</p>
6
2009-08-07T12:46:03Z
[ "python", "com", "pywin32" ]
Disable console output from subprocess.Popen in Python
1,244,723
<p>I run Python 2.5 on Windows, and somewhere in the code I have</p> <pre><code>subprocess.Popen("taskkill /PID " + str(p.pid)) </code></pre> <p>to kill IE window by pid. The problem is that without setting up piping in Popen I still get output to console - SUCCESS: The process with PID 2068 has been terminated. I debugged it to CreateProcess in subprocess.py, but can't go from there.</p> <p>Anyone knows how to disable this?</p>
8
2009-08-07T13:34:45Z
1,244,757
<pre><code>fh = open("NUL","w") subprocess.Popen("taskkill /PID " + str(p.pid), stdout = fh, stderr = fh) fh.close() </code></pre>
7
2009-08-07T13:41:08Z
[ "python", "console", "subprocess", "popen" ]
Disable console output from subprocess.Popen in Python
1,244,723
<p>I run Python 2.5 on Windows, and somewhere in the code I have</p> <pre><code>subprocess.Popen("taskkill /PID " + str(p.pid)) </code></pre> <p>to kill IE window by pid. The problem is that without setting up piping in Popen I still get output to console - SUCCESS: The process with PID 2068 has been terminated. I debugged it to CreateProcess in subprocess.py, but can't go from there.</p> <p>Anyone knows how to disable this?</p>
8
2009-08-07T13:34:45Z
1,246,714
<pre class="lang-py prettyprint-override"><code>import os from subprocess import check_call, STDOUT DEVNULL = open(os.devnull, 'wb') try: check_call(("taskkill", "/PID", str(p.pid)), stdout=DEVNULL, stderr=STDOUT) finally: DEVNULL.close() </code></pre> <p>I always pass in tuples to subprocess as it saves me worrying about escaping. check_call ensures (a) the subprocess has finished <em>before</em> the pipe closes, and (b) a failure in the called process is not ignored. Finally, <code>os.devnull</code> is the standard, cross-platform way of saying <code>NUL</code> in Python 2.4+.</p> <p>Note that in Py3K, subprocess provides DEVNULL for you, so you can just write:</p> <pre><code>from subprocess import check_call, DEVNULL, STDOUT check_call(("taskkill", "/PID", str(p.pid)), stdout=DEVNULL, stderr=STDOUT) </code></pre>
11
2009-08-07T19:58:22Z
[ "python", "console", "subprocess", "popen" ]
Help me understand this traceback from the twisted.words msn sample
1,244,733
<p>I'm running the twisted.words msn protocol example from the twisted documentation located here: <a href="http://twistedmatrix.com/projects/words/documentation/examples/msn_example.py" rel="nofollow">http://twistedmatrix.com/projects/words/documentation/examples/msn_example.py</a></p> <p>I am aware there is another question about this sample .py on stackoverflow, but this is an entirely different problem. When I run the example, it behaves as expected. Logs into the account and displays information about users on the buddylist, but after having done that it spits out this traceback</p> <pre><code>&gt; Traceback (most recent call last): &gt; File &gt; "c:\python26\lib\site-packages\twisted\python\log.py", &gt; line 84, in callWithLogger &gt; return callWithContext({"system": lp}, func, *args, **kw) File &gt; "c:\python26\lib\site-packages\twisted\python\log.py", &gt; line 69, in callWithContext &gt; return context.call({ILogContext: newCtx}, func, *args, **kw) File &gt; "c:\python26\lib\site-packages\twisted\python\context.py", &gt; line 59, in callWithContext &gt; return self.currentContext().callWithContext(ctx, &gt; func, *args, **kw) File &gt; "c:\python26\lib\site-packages\twisted\python\context.py", &gt; line 37, in callWithContext &gt; return func(*args,**kw) &gt; --- &lt;exception caught here&gt; --- File "c:\python26\lib\site-packages\twisted\internet\selectreactor.py", &gt; line 146, in _doReadOrWrite &gt; why = getattr(selectable, method)() File &gt; "c:\python26\lib\site-packages\twisted\internet\tcp.py", &gt; line 463, in doRead &gt; return self.protocol.dataReceived(data) &gt; File &gt; "c:\python26\lib\site-packages\twisted\protocols\basic.py", line 239, indataReceived &gt; return self.rawDataReceived(data) File &gt; "c:\python26\lib\site-packages\twisted\words\protocols\msn.py", &gt; line 676 in rawDataReceived &gt; self.gotMessage(m) File "c:\python26\lib\site-packages\twisted\words\protocols\msn.py", &gt; line 699, in gotMessage &gt; raise NotImplementedError exceptions.NotImplementedError: </code></pre> <p>could someone help me understand what that means?</p>
3
2009-08-07T13:36:15Z
1,244,795
<p>The method gotMessage claims to not be implemented. That likely means that you have subclassed a class that needs gotMessage to be overridden in the subclass, but you haven't done the overriding.</p>
0
2009-08-07T13:48:11Z
[ "python", "twisted", "msn", "traceback" ]
Help me understand this traceback from the twisted.words msn sample
1,244,733
<p>I'm running the twisted.words msn protocol example from the twisted documentation located here: <a href="http://twistedmatrix.com/projects/words/documentation/examples/msn_example.py" rel="nofollow">http://twistedmatrix.com/projects/words/documentation/examples/msn_example.py</a></p> <p>I am aware there is another question about this sample .py on stackoverflow, but this is an entirely different problem. When I run the example, it behaves as expected. Logs into the account and displays information about users on the buddylist, but after having done that it spits out this traceback</p> <pre><code>&gt; Traceback (most recent call last): &gt; File &gt; "c:\python26\lib\site-packages\twisted\python\log.py", &gt; line 84, in callWithLogger &gt; return callWithContext({"system": lp}, func, *args, **kw) File &gt; "c:\python26\lib\site-packages\twisted\python\log.py", &gt; line 69, in callWithContext &gt; return context.call({ILogContext: newCtx}, func, *args, **kw) File &gt; "c:\python26\lib\site-packages\twisted\python\context.py", &gt; line 59, in callWithContext &gt; return self.currentContext().callWithContext(ctx, &gt; func, *args, **kw) File &gt; "c:\python26\lib\site-packages\twisted\python\context.py", &gt; line 37, in callWithContext &gt; return func(*args,**kw) &gt; --- &lt;exception caught here&gt; --- File "c:\python26\lib\site-packages\twisted\internet\selectreactor.py", &gt; line 146, in _doReadOrWrite &gt; why = getattr(selectable, method)() File &gt; "c:\python26\lib\site-packages\twisted\internet\tcp.py", &gt; line 463, in doRead &gt; return self.protocol.dataReceived(data) &gt; File &gt; "c:\python26\lib\site-packages\twisted\protocols\basic.py", line 239, indataReceived &gt; return self.rawDataReceived(data) File &gt; "c:\python26\lib\site-packages\twisted\words\protocols\msn.py", &gt; line 676 in rawDataReceived &gt; self.gotMessage(m) File "c:\python26\lib\site-packages\twisted\words\protocols\msn.py", &gt; line 699, in gotMessage &gt; raise NotImplementedError exceptions.NotImplementedError: </code></pre> <p>could someone help me understand what that means?</p>
3
2009-08-07T13:36:15Z
1,326,503
<p>It looks like it's a change to the way the MSN server operates, although it doesn't really count as a change to the protocol. What's happening is the MSN server is sending a message to the client immediately after the client connects and the Twisted words example isn't expecting that.</p> <p>Assuming you're running the msn_example.py from <a href="http://twistedmatrix.com/projects/words/documentation/examples/" rel="nofollow">http://twistedmatrix.com/projects/words/documentation/examples/</a>, you can get the example working and see what's happening by adding the following code to the example (right after the end of the listSynchronized function):</p> <pre><code>def gotMessage(self, message): print message.headers print message.getMessage() </code></pre> <p>After making the changes, if you run the example, you should see the following:</p> <pre><code>... 2009-08-25 00:03:23-0700 [Notification,client] {'Content-Type': 'text/x-msmsgsinitialemailnotification; charset=UTF-8', 'MIME-Version': '1.0'} 2009-08-25 00:03:23-0700 [Notification,client] Inbox-Unread: 1 2009-08-25 00:03:23-0700 [Notification,client] Folders-Unread: 0 2009-08-25 00:03:23-0700 [Notification,client] Inbox-URL: /cgi-bin/HoTMaiL 2009-08-25 00:03:23-0700 [Notification,client] Folders-URL: /cgi-bin/folders 2009-08-25 00:03:23-0700 [Notification,client] Post-URL: http://www.hotmail.com 2009-08-25 00:03:23-0700 [Notification,client] </code></pre> <p>We can see that the server is sending the client a message which specifies the number of unread email messages there are for that account.</p> <p>Hope that helps!</p>
1
2009-08-25T07:10:32Z
[ "python", "twisted", "msn", "traceback" ]
How to write a setup.py for a program that depends on packages outside pypi
1,244,784
<p>For instance, what if <code>PIL</code>, <code>python-rsvg</code> and <code>libev3</code> are dependencies of the program? These dependencies are not in pypi index, the latter two are Debian package names.</p>
0
2009-08-07T13:46:32Z
1,244,867
<p>Simply don't put them in your dependencies and document that in your INSTALL or README.</p>
2
2009-08-07T14:01:38Z
[ "python", "setuptools" ]
How to write a setup.py for a program that depends on packages outside pypi
1,244,784
<p>For instance, what if <code>PIL</code>, <code>python-rsvg</code> and <code>libev3</code> are dependencies of the program? These dependencies are not in pypi index, the latter two are Debian package names.</p>
0
2009-08-07T13:46:32Z
1,245,527
<p>If you are packaging something to be installed on Debian (as implied), the best way to manage dependencies is to package your program as a .deb and express the dependencies the Debian way. (Note, PIL is available in Debian as <code>python-imaging</code>.)</p>
0
2009-08-07T15:46:40Z
[ "python", "setuptools" ]
How to write a setup.py for a program that depends on packages outside pypi
1,244,784
<p>For instance, what if <code>PIL</code>, <code>python-rsvg</code> and <code>libev3</code> are dependencies of the program? These dependencies are not in pypi index, the latter two are Debian package names.</p>
0
2009-08-07T13:46:32Z
1,246,840
<p>Since the setup.py is Python code too, you just can download and run the setup.py on those packages.</p>
0
2009-08-07T20:26:10Z
[ "python", "setuptools" ]
How to write a setup.py for a program that depends on packages outside pypi
1,244,784
<p>For instance, what if <code>PIL</code>, <code>python-rsvg</code> and <code>libev3</code> are dependencies of the program? These dependencies are not in pypi index, the latter two are Debian package names.</p>
0
2009-08-07T13:46:32Z
1,249,580
<p>You could use setuptools. setuptools allows you to add any kind of Python installable (any distutils/setuptools enabled package) as a dependency, no matter if it is on PyPI or not.</p> <p>For example, to depend on PIL 1.1.6, use something like:</p> <pre><code>setup(..., install_requires = ["http://effbot.org/downloads/Imaging-1.1.6.tar.gz"], ...) </code></pre> <p>See <a href="http://peak.telecommunity.com/DevCenter/setuptools#declaring-dependencies" rel="nofollow">setuptools</a> docs for more information.</p>
4
2009-08-08T18:33:17Z
[ "python", "setuptools" ]
How to write a setup.py for a program that depends on packages outside pypi
1,244,784
<p>For instance, what if <code>PIL</code>, <code>python-rsvg</code> and <code>libev3</code> are dependencies of the program? These dependencies are not in pypi index, the latter two are Debian package names.</p>
0
2009-08-07T13:46:32Z
1,399,470
<p>I've reported this problem here : </p> <p><a href="http://mail.python.org/pipermail/python-list/2009-September/727045.html" rel="nofollow">http://mail.python.org/pipermail/python-list/2009-September/727045.html</a></p>
1
2009-09-09T12:45:04Z
[ "python", "setuptools" ]
curses-like library for cross-platform console app in python
1,244,897
<p>I'm looking into developing a console application in python which should be able to run under Windows as well as Linux. For this, I'd really like to use a high-level console library like curses. However, as far as I know, curses is not available on Windows.</p> <p>What other options do I have? Unfortunately, using cygwin under Windows is not an option...</p> <p>Thanks for your help!</p>
19
2009-08-07T14:06:07Z
1,244,935
<p><a href="http://pdcurses.sourceforge.net/" rel="nofollow">PDCurses</a> works on Windows, but I don't know any Python wrapper. I wonder whether the curses module could be implemented on Windows with PDCurses?</p>
4
2009-08-07T14:11:48Z
[ "python", "windows", "linux", "console", "ncurses" ]
curses-like library for cross-platform console app in python
1,244,897
<p>I'm looking into developing a console application in python which should be able to run under Windows as well as Linux. For this, I'd really like to use a high-level console library like curses. However, as far as I know, curses is not available on Windows.</p> <p>What other options do I have? Unfortunately, using cygwin under Windows is not an option...</p> <p>Thanks for your help!</p>
19
2009-08-07T14:06:07Z
1,244,980
<p>develop two interfaces for your program, a text console ui and a graphical ui. Make the console one work only on linux. Nobody on windows uses text console apps.</p>
-8
2009-08-07T14:17:53Z
[ "python", "windows", "linux", "console", "ncurses" ]
curses-like library for cross-platform console app in python
1,244,897
<p>I'm looking into developing a console application in python which should be able to run under Windows as well as Linux. For this, I'd really like to use a high-level console library like curses. However, as far as I know, curses is not available on Windows.</p> <p>What other options do I have? Unfortunately, using cygwin under Windows is not an option...</p> <p>Thanks for your help!</p>
19
2009-08-07T14:06:07Z
1,245,106
<p>There is a <a href="http://adamv.com/dev/python/curses/">wcurses</a>. I've never tried it but it may meet your needs. It sounds like it doesn't have full curses compatibility, but may be close enough. Also it might not be using the DOS terminal, but opening a GUI window and drawing monospaced text inside.</p> <p>Other windows text mode options are:</p> <ul> <li>The <a href="http://www.effbot.org/zone/console-handbook.htm">console module</a>;</li> <li><a href="http://newcenturycomputers.net/projects/wconio.html">wconio</a> -- based on Borland's C conio library.</li> </ul> <p>I believe both are windows only. </p>
6
2009-08-07T14:37:56Z
[ "python", "windows", "linux", "console", "ncurses" ]
curses-like library for cross-platform console app in python
1,244,897
<p>I'm looking into developing a console application in python which should be able to run under Windows as well as Linux. For this, I'd really like to use a high-level console library like curses. However, as far as I know, curses is not available on Windows.</p> <p>What other options do I have? Unfortunately, using cygwin under Windows is not an option...</p> <p>Thanks for your help!</p>
19
2009-08-07T14:06:07Z
13,338,753
<p>I don't know why people answer in question comments, but debustad is right, there is a prebuilt curses for Windows:</p> <ul> <li><a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#curses" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/#curses</a></li> </ul> <p>Note lots of other helpful libraries there too. After doing so, install pip and the (lesser known but excellent) <a href="http://bpython-interpreter.org/" rel="nofollow">bpython</a> interactive interpreter to try it out immediately:</p> <pre><code>pip install bpython </code></pre> <p>I also recommend the <a href="http://excess.org/urwid/" rel="nofollow">Urwid library</a> for something higher-level. Never tried it on Windows, but it <a href="http://lists.excess.org/pipermail/urwid/2006-August/000304.html" rel="nofollow">should be possible</a> with one of the curses packages.</p>
3
2012-11-12T05:22:47Z
[ "python", "windows", "linux", "console", "ncurses" ]
curses-like library for cross-platform console app in python
1,244,897
<p>I'm looking into developing a console application in python which should be able to run under Windows as well as Linux. For this, I'd really like to use a high-level console library like curses. However, as far as I know, curses is not available on Windows.</p> <p>What other options do I have? Unfortunately, using cygwin under Windows is not an option...</p> <p>Thanks for your help!</p>
19
2009-08-07T14:06:07Z
30,756,010
<p>I recently hit this issue for a package I was putting together (<a href="https://github.com/peterbrittain/asciimatics" rel="nofollow">https://github.com/peterbrittain/asciimatics</a>). I wasn't very happy with the solutions that required you to install (or worse) build separate binary executables like PDCurses or cygwin, so I created a unified API that provides console colours, cursor positioning and keyboard &amp; mouse input for Windows, OSX and UNIX platforms.</p> <p>This is now live and has been tested on CentOS 6/7 and Windows 7/8/10 and OSX 10.11. You can install it from PYPI using pip and then use the <code>Screen</code> class to control your console. As you can see from the project <a href="https://github.com/peterbrittain/asciimatics/wiki" rel="nofollow">gallery</a>, it should provide all your console needs, but if you need some extra features, please post an enhancement request on GitHub and I'll see what I can do.</p>
2
2015-06-10T12:11:53Z
[ "python", "windows", "linux", "console", "ncurses" ]
Run Python script without opening Pythonwin
1,245,818
<p>I have a python script which I can run from pythonwin on which I give the arguments. Is it possible to automate this so that when I just click on the *.py file, I don't see the script and it asks for the path in a dos window? </p>
1
2009-08-07T16:48:33Z
1,245,828
<p>Rename it to *.pyw to hide the console on execution in Windows.</p>
3
2009-08-07T16:50:08Z
[ "python" ]
Run Python script without opening Pythonwin
1,245,818
<p>I have a python script which I can run from pythonwin on which I give the arguments. Is it possible to automate this so that when I just click on the *.py file, I don't see the script and it asks for the path in a dos window? </p>
1
2009-08-07T16:48:33Z
1,245,835
<p>You can also wrap it in a batch file, containing:</p> <pre><code>c:\path to python.exe c:\path to file.py </code></pre> <p>You can then also easily set an icon, run in window/run hidden etc on the batch file.</p>
2
2009-08-07T16:52:01Z
[ "python" ]
Run Python script without opening Pythonwin
1,245,818
<p>I have a python script which I can run from pythonwin on which I give the arguments. Is it possible to automate this so that when I just click on the *.py file, I don't see the script and it asks for the path in a dos window? </p>
1
2009-08-07T16:48:33Z
1,246,358
<p>You're running on Windows, so you need an association between .py files and some binary to run them. Have a look at <a href="http://stackoverflow.com/questions/707127/python-source-header-comment/707167#707167">this post</a>.</p> <p>When you run "assoc .py", do you get Python.File? When you run "ftype Python.File", what do you get? If "ftype Python.File" points at some python.exe, your python script should run without any prompting.</p>
4
2009-08-07T18:40:26Z
[ "python" ]
Run Python script without opening Pythonwin
1,245,818
<p>I have a python script which I can run from pythonwin on which I give the arguments. Is it possible to automate this so that when I just click on the *.py file, I don't see the script and it asks for the path in a dos window? </p>
1
2009-08-07T16:48:33Z
1,249,490
<p>how does your script ask for or get its parameters? If it expects them from the call to the script (i.e. in sys.argv) and Pythonwin just notices that and prompts you for them (I think Pyscripter does something similar) you can either run it from a CMD window (commandline) where you can give the arguments as in</p> <pre><code>python myscript.py argument-1 argument-2 </code></pre> <p>or modify your script to ask for the arguments itself instead (using a gui like Tkinter if you don't want to run from commandline).</p>
1
2009-08-08T17:52:26Z
[ "python" ]
Handling lines with quotes using python's readline
1,245,907
<p>I've written a simple shell-like program that uses readline in order to provide smart completion of arguments. I would like the mechanism to support arguments that have spaces and are quoted to signify as one argument (as with providing the shell with such). </p> <p>I've seen that shlex.split() knows how to parse quoted arguments, but in case a user wants to complete mid-typing it fails (for example: 'complete "Hello ' would cause an exception to be thrown when passed to shlex, because of unbalanced quotes).</p> <p>Is there code for doing this?</p> <p>Thanks!</p>
0
2009-08-07T17:08:28Z
1,245,925
<p>I don't know of any existing code for the task, but if I were to do this I'd catch the exception, try adding a fake trailing quote, and see how shlex.split does with the string thus modified.</p>
2
2009-08-07T17:11:43Z
[ "python", "readline" ]
Python library for converting files to MP3 and setting their quality
1,246,131
<p>I'm trying to find a Python library that would take an audio file (e.g. .ogg, .wav) and convert it into mp3 for playback on a webpage. </p> <p>Also, any thoughts on setting its quality for playback would be great.</p> <p>Thank you.</p>
8
2009-08-07T17:51:39Z
1,246,158
<p>Looks like PyMedia does this:</p> <p><a href="http://pymedia.org/" rel="nofollow">http://pymedia.org/</a></p> <p>and some more info here on converting to various formats, whilst setting the bitrate:</p> <p><a href="http://pymedia.org/tut/recode%5Faudio.html" rel="nofollow">http://pymedia.org/tut/recode_audio.html</a></p> <p>e.g.</p> <pre><code>params= { 'id': acodec.getCodecId('mp3'), 'bitrate': r.bitrate, 'sample_rate': r.sample_rate, 'ext': 'mp3', 'channels': r.channels } enc= acodec.Encoder( params ) </code></pre>
2
2009-08-07T17:56:14Z
[ "python", "audio", "compression" ]
Python library for converting files to MP3 and setting their quality
1,246,131
<p>I'm trying to find a Python library that would take an audio file (e.g. .ogg, .wav) and convert it into mp3 for playback on a webpage. </p> <p>Also, any thoughts on setting its quality for playback would be great.</p> <p>Thank you.</p>
8
2009-08-07T17:51:39Z
1,246,256
<p>Also, the <a href="http://audiotools.sourceforge.net/" rel="nofollow">Python Audio Tools</a> should be able to do the job with less need for other libraries, which might be easier if you're doing this on a shared web hosting account. (But admittedly I haven't tried it, so I can't confirm how usable it is.)</p>
3
2009-08-07T18:18:18Z
[ "python", "audio", "compression" ]
Python library for converting files to MP3 and setting their quality
1,246,131
<p>I'm trying to find a Python library that would take an audio file (e.g. .ogg, .wav) and convert it into mp3 for playback on a webpage. </p> <p>Also, any thoughts on setting its quality for playback would be great.</p> <p>Thank you.</p>
8
2009-08-07T17:51:39Z
1,246,816
<p>Another option to avoid installing Python modules for this simple task would be to just exec "lame" or other command line encoder from the Python script (with the popen module.)</p>
1
2009-08-07T20:22:14Z
[ "python", "audio", "compression" ]
Python library for converting files to MP3 and setting their quality
1,246,131
<p>I'm trying to find a Python library that would take an audio file (e.g. .ogg, .wav) and convert it into mp3 for playback on a webpage. </p> <p>Also, any thoughts on setting its quality for playback would be great.</p> <p>Thank you.</p>
8
2009-08-07T17:51:39Z
1,246,836
<p>I use the Python bindings for gstreamer. It's a bit hard to get started but once you get going nearly anything's possible.</p> <p>From the command line (from <a href="http://gstreamer.freedesktop.org/data/doc/gstreamer/head/gst-plugins-ugly-plugins/html/gst-plugins-ugly-plugins-lame.html" rel="nofollow">gstreamer's documentation</a>):</p> <pre><code>gst-launch -v filesrc location=music.wav ! decodebin ! audioconvert ! audioresample ! lame bitrate=192 ! id3v2mux ! filesink location=music.mp3 </code></pre> <p>The input <code>filesrc location=...</code> could be anything gstreamer can play, not just .wav. You could add something called a caps filter to resample to a specific rate before you encode.</p> <p>In your Python program you would use <code>gst.parse_launch(...)</code>, get the filesrc and filesink elements, and call setters to change the input and output filenames.</p>
4
2009-08-07T20:25:42Z
[ "python", "audio", "compression" ]
Python library for converting files to MP3 and setting their quality
1,246,131
<p>I'm trying to find a Python library that would take an audio file (e.g. .ogg, .wav) and convert it into mp3 for playback on a webpage. </p> <p>Also, any thoughts on setting its quality for playback would be great.</p> <p>Thank you.</p>
8
2009-08-07T17:51:39Z
1,334,217
<p>You may use ctypes module to call functions directly from dynamic libraries. It doesn't require you to install external Python libs and it has better performance than command line tools, but it's usually harder to implement (plus of course you need to provide external library).</p>
2
2009-08-26T12:01:08Z
[ "python", "audio", "compression" ]