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
sequence |
---|---|---|---|---|---|---|---|---|---|
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each? | 1,983 | <p>In many places, <code>(1,2,3)</code> and <code>[1,2,3]</code> can be used interchangeably.</p>
<p>When should I use one or the other, and why?</p>
| 31 | 2008-08-05T07:18:55Z | 4,595 | <p>Tuples are a quick\flexible way to create <em>composite</em> data-types.
Lists are containers for, well, lists of objects.</p>
<p>For example, you would use a List to store a list of student details in a class.</p>
<p>Each student detail in that list may be a 3-tuple containing their roll number, name and test score.</p>
<pre><code> `[(1,'Mark',86),(2,'John',34)...]`<br></code></pre>
<p>Also, because tuples are immutable they can be used as keys in dictionaries.</p> | 10 | 2008-08-07T11:21:56Z | [
"python",
"list",
"tuples"
] |
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each? | 1,983 | <p>In many places, <code>(1,2,3)</code> and <code>[1,2,3]</code> can be used interchangeably.</p>
<p>When should I use one or the other, and why?</p>
| 31 | 2008-08-05T07:18:55Z | 5,719 | <P>As others have mentioned, Lists and tuples are both containers which can be used to store python objects. Lists are extensible and their contents can change by assignment, on the other hand tuples are immutable.</P>
<P>Also, lists cannot be used as keys in a dictionary whereas tuples can. </P> | 1 | 2008-08-08T06:06:33Z | [
"python",
"list",
"tuples"
] |
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each? | 1,983 | <p>In many places, <code>(1,2,3)</code> and <code>[1,2,3]</code> can be used interchangeably.</p>
<p>When should I use one or the other, and why?</p>
| 31 | 2008-08-05T07:18:55Z | 5,746 | <p>If you can find a solution that works with tuples, use them, as it forces immutability which kind of drives you down a more functional path. You almost never regret going down the functional/immutable path.</p> | 1 | 2008-08-08T06:48:52Z | [
"python",
"list",
"tuples"
] |
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each? | 1,983 | <p>In many places, <code>(1,2,3)</code> and <code>[1,2,3]</code> can be used interchangeably.</p>
<p>When should I use one or the other, and why?</p>
| 31 | 2008-08-05T07:18:55Z | 12,454 | <p>Whenever I need to pass in a collection of items to a function, if I want the function to not change the values passed in - I use tuples. </p>
<p>Else if I want to have the function to alter the values, I use list. </p>
<p>Always if you are using external libraries and need to pass in a list of values to a function and are unsure about the integrity of the data, use a tuple. </p>
| 2 | 2008-08-15T16:38:59Z | [
"python",
"list",
"tuples"
] |
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each? | 1,983 | <p>In many places, <code>(1,2,3)</code> and <code>[1,2,3]</code> can be used interchangeably.</p>
<p>When should I use one or the other, and why?</p>
| 31 | 2008-08-05T07:18:55Z | 12,557 | <p>The notion of tuples are highly expressive:</p>
<ul>
<li><p>Pragmatically, they are great for packing and unpacking values (<code>x,y=coord</code>).</p></li>
<li><p>In combination with dictionaries (hash tables), they allow forms of mapping that would otherwise require many levels of association. For example, consider marking that (x,y) has been found.</p>
<pre><code>// PHP
if (!isset($found[$x])) {
$found[$x] = Array();
$found[$x][$y] = true;
} else if (!isset($found[$x][$y])) {
$found[$x][$y] = true;
}
# Python
found[(x,y)] = True # parens added for clarity
</code></pre></li>
<li><p>Lists should be used with the expectation of operations on its contents (hence the various mentions of immutability). One will want to pop, push, splice, slice, search, insert before, insert after, etc with a list.</p></li>
<li><p>Tuples should be a low-level representation of an object, where simple comparisons are made, or operations such as extracting the n'th element or n elements in a predictable fashion, such as the coordinates example given earlier.</p></li>
<li><p>Lastly, lists are not hashable, so the type of mapping done with dictionaries (hash tables in Perl, associative arrays in PHP) must be done with tuples.</p>
<p>Here's a simple example of tuples and dictionaries, together at last:</p>
<pre><code>"""
couple is a tuple of two people
doesLike is a dictionary mapping couples to True or False
"""
couple = "john", "jane"
doesLike = dict()
doesLike[couple] = True
doesLike["jane", "john"] = False # unrequited love :'(
</code></pre></li>
</ul>
| 7 | 2008-08-15T18:00:37Z | [
"python",
"list",
"tuples"
] |
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each? | 1,983 | <p>In many places, <code>(1,2,3)</code> and <code>[1,2,3]</code> can be used interchangeably.</p>
<p>When should I use one or the other, and why?</p>
| 31 | 2008-08-05T07:18:55Z | 6,477,369 | <p>[1, 2, 3] is a list in which one can add or delete items.<br>
(1, 2, 3) is a tuple in which once defined, modification cannot be done.</p>
| 2 | 2011-06-25T11:14:19Z | [
"python",
"list",
"tuples"
] |
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each? | 1,983 | <p>In many places, <code>(1,2,3)</code> and <code>[1,2,3]</code> can be used interchangeably.</p>
<p>When should I use one or the other, and why?</p>
| 31 | 2008-08-05T07:18:55Z | 26,250,158 | <p><code>[1,2,3]</code> is a list.</p>
<p><code>(1,2,3)</code> is a tuple and immutable.</p>
| 1 | 2014-10-08T06:02:42Z | [
"python",
"list",
"tuples"
] |
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each? | 1,983 | <p>In many places, <code>(1,2,3)</code> and <code>[1,2,3]</code> can be used interchangeably.</p>
<p>When should I use one or the other, and why?</p>
| 31 | 2008-08-05T07:18:55Z | 28,888,938 | <p>Basically, <code>(1, 2, 3)</code> is a tuple, while <code>[1, 2, 3]</code> is a list. </p>
<p>A tuple is a non-mutable data type which means you are not able to change its contents once it has been created. Tuples are mostly used in order to return more than one value from a function. For example:</p>
<pre><code>def returnNameAndLastName(wholeName):
"""
@param wholeName: string in the format Name LastName
"""
data = wholeName.split()
name = data[0]
lastName = data[1]
return (name, lastName) # parenthesis are optional here
</code></pre>
<p>you can store in a variable the whole tuple or in two independent variables the content of the tuple. <code>myTuple = wholeName("Sam Smith")</code> or <code>name, lastName = wholeName("Sam Smith")</code>. Another application for tuples is use them as dictionaries' keys because, as mention, they are not mutable. Therefore, this is a way to assure the key will not be changed. It is not needed that all the elements of the tuple having the same type. <code>(1, 'Hello', ('version', 2.5), [1, 2, 3])</code> is completely valid. As shown a tuple can be an element of a tuple, and a list can be an element of a tuple too.</p>
<p>On the other hand, a list is a mutable data type which means its content can be change after being created. A list is similar to an array, but to be more specific it is like an array list because an array has a fixed size which cannot be changed, while a list has a variable size depending on the number of elements it contains. Although lists are used to store data that are related, because of Python is not a strongly typed programming language, it is possible to have list which elements have different types like <code>[1, "Goodbye", [1, 'music'], (1, 2, 3)]</code>. As shown, a list can be an element of a list, and a tuple also can be an element of a list.</p>
| 0 | 2015-03-05T22:21:55Z | [
"python",
"list",
"tuples"
] |
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each? | 1,983 | <p>In many places, <code>(1,2,3)</code> and <code>[1,2,3]</code> can be used interchangeably.</p>
<p>When should I use one or the other, and why?</p>
| 31 | 2008-08-05T07:18:55Z | 33,058,118 | <p>open a console and run python.
Try this:</p>
<pre><code> >>> list = [1, 2, 3]
>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delsli
ce__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getit
em__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__',
'__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__r
educe__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__'
, '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__',
'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
</code></pre>
<p>As you may see the last on the last line list have the following methods:
<strong>'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'</strong></p>
<p>Now try the same for tuple:</p>
<pre><code>>>> tuple = (1, 2, 3)
>>> dir(tuple)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__
format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__get
slice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__
lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__'
, '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
</code></pre>
<p>Only <strong>'count' and 'index'</strong> from list methods appears here.</p>
<p>This is because tuples are immutable and they don't support any modifications. Instead they are simpler and faster in internal implementation.</p>
| 1 | 2015-10-10T19:30:36Z | [
"python",
"list",
"tuples"
] |
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each? | 1,983 | <p>In many places, <code>(1,2,3)</code> and <code>[1,2,3]</code> can be used interchangeably.</p>
<p>When should I use one or the other, and why?</p>
| 31 | 2008-08-05T07:18:55Z | 35,496,153 | <p><code>(1,2,3)</code> is a tuple while <code>[1,2,3]</code> is a list. A tuple is an immutable object while a list is mutable.</p>
| 0 | 2016-02-19T02:15:31Z | [
"python",
"list",
"tuples"
] |
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each? | 1,983 | <p>In many places, <code>(1,2,3)</code> and <code>[1,2,3]</code> can be used interchangeably.</p>
<p>When should I use one or the other, and why?</p>
| 31 | 2008-08-05T07:18:55Z | 38,062,967 | <p><code>(1,2,3)</code> is a tuple and <code>[1,2,3]</code> is a list. You either of the two represent sequences of numbers but note that tuples are immutable and list are mutable Python objects. </p>
| 0 | 2016-06-27T20:48:38Z | [
"python",
"list",
"tuples"
] |
File size differences after copying a file to a server vÃa FTP | 2,311 | <p>I have created a PHP-script to update a webserver that is live inside a local directory.
I'm migrating the script into Python. It works fine for the most part, but after a PUT command the size of the file appears to change. Thus, the size of the file is different from that of the file on the server. </p>
<p>Once I download again the file from the FTP server, the only difference is the CR/LF mark. This annoys me because the same script is comparing the size of the files to update. Also, in case it means anything, the script works perfectly in PHP vÃa ftp_put.</p>
<pre><code>from ftplib import FTP
ftpserver = "myserver"
ftpuser = "myuser"
ftppass = "mypwd"
locfile = "g:/test/style.css"
ftpfile = "/temp/style.css"
try:
ftp = FTP(ftpserver, ftpuser, ftppass)
except:
exit ("Cannot connect")
f = open (locfile, "r")
try:
ftp.delete (ftpfile)
except:
pass
# ftp.sendcmd ("TYPE I")
# ftp.storlines("STOR %s" % ftpfile, f)
ftp.storbinary("STOR %s" % ftpfile, f)
f.close()
ftp.dir (ftpfile)
ftp.quit()
</code></pre>
<p>Any suggestions?</p>
| 26 | 2008-08-05T13:40:47Z | 2,316 | <p>Do you need to open the locfile in binary using <code>rb</code>?</p>
<pre><code>f = open (locfile, "rb")
</code></pre>
| 14 | 2008-08-05T13:45:38Z | [
"php",
"python",
"ftp",
"webserver"
] |
File size differences after copying a file to a server vÃa FTP | 2,311 | <p>I have created a PHP-script to update a webserver that is live inside a local directory.
I'm migrating the script into Python. It works fine for the most part, but after a PUT command the size of the file appears to change. Thus, the size of the file is different from that of the file on the server. </p>
<p>Once I download again the file from the FTP server, the only difference is the CR/LF mark. This annoys me because the same script is comparing the size of the files to update. Also, in case it means anything, the script works perfectly in PHP vÃa ftp_put.</p>
<pre><code>from ftplib import FTP
ftpserver = "myserver"
ftpuser = "myuser"
ftppass = "mypwd"
locfile = "g:/test/style.css"
ftpfile = "/temp/style.css"
try:
ftp = FTP(ftpserver, ftpuser, ftppass)
except:
exit ("Cannot connect")
f = open (locfile, "r")
try:
ftp.delete (ftpfile)
except:
pass
# ftp.sendcmd ("TYPE I")
# ftp.storlines("STOR %s" % ftpfile, f)
ftp.storbinary("STOR %s" % ftpfile, f)
f.close()
ftp.dir (ftpfile)
ftp.quit()
</code></pre>
<p>Any suggestions?</p>
| 26 | 2008-08-05T13:40:47Z | 2,317 | <p>Well if you go under the properties of your file in Windows or a *nix environment, you will notice two sizes. One is the sector size, and one is the actual size. The sector size is the number of sectors in bytes that are used up on your hard disk. That is because two files cannot be in the same sector with most modern file systems, so if your file fills up half of the sector the whole sector is marked as filled.</p>
<p>So you might be comparing the sector file size to the actual file size on the FTP server or vice versa.</p> | 2 | 2008-08-05T13:45:47Z | [
"php",
"python",
"ftp",
"webserver"
] |
File size differences after copying a file to a server vÃa FTP | 2,311 | <p>I have created a PHP-script to update a webserver that is live inside a local directory.
I'm migrating the script into Python. It works fine for the most part, but after a PUT command the size of the file appears to change. Thus, the size of the file is different from that of the file on the server. </p>
<p>Once I download again the file from the FTP server, the only difference is the CR/LF mark. This annoys me because the same script is comparing the size of the files to update. Also, in case it means anything, the script works perfectly in PHP vÃa ftp_put.</p>
<pre><code>from ftplib import FTP
ftpserver = "myserver"
ftpuser = "myuser"
ftppass = "mypwd"
locfile = "g:/test/style.css"
ftpfile = "/temp/style.css"
try:
ftp = FTP(ftpserver, ftpuser, ftppass)
except:
exit ("Cannot connect")
f = open (locfile, "r")
try:
ftp.delete (ftpfile)
except:
pass
# ftp.sendcmd ("TYPE I")
# ftp.storlines("STOR %s" % ftpfile, f)
ftp.storbinary("STOR %s" % ftpfile, f)
f.close()
ftp.dir (ftpfile)
ftp.quit()
</code></pre>
<p>Any suggestions?</p>
| 26 | 2008-08-05T13:40:47Z | 2,510 | <p>Small files take up a whole node on the filesystem whatever size that is.</p>
<p>My host tends to report all small files as 4kb in ftp but in a shell gives an accurate size so it might be a 'feature' common to ftp clients.</p> | 0 | 2008-08-05T15:59:24Z | [
"php",
"python",
"ftp",
"webserver"
] |
How can I create a directly-executable cross-platform GUI app using Python? | 2,933 | <p>Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux.</p>
<p>The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the right direction please?</p> | 171 | 2008-08-05T22:26:00Z | 2,937 | <p>First you will need some GUI library with Python bindings and then (if you want) some program that will convert your python scripts into standalone executables.</p>
<p><strong>Cross-platform GUI libraries with Python bindings (Windows, Linux, Mac)</strong></p>
<p>Of course, there are many, but the most popular that I've seen in wild are:</p>
<ul>
<li><a href="http://wiki.python.org/moin/TkInter">Tkinter</a> - based on <a href="http://www.tcl.tk/">Tk GUI toolkit</a> (de-facto standard GUI library for python, free for commercial projects)</li>
<li><a href="http://www.wxpython.org/">WxPython</a> - based on <a href="http://www.wxwidgets.org/">WxWidgets</a> (very popular, free for commercial projects)</li>
<li><a href="http://www.riverbankcomputing.co.uk/news">PyQt</a> - based on <a href="http://trolltech.com/products/qt/">Qt</a> (also very popular and more stable than WxWidgets but costly license for commercial projects)</li>
</ul>
<p>Complete list is at <a href="http://wiki.python.org/moin/GuiProgramming">http://wiki.python.org/moin/GuiProgramming</a></p>
<p><strong>Single executable (Windows)</strong></p>
<ul>
<li><a href="http://www.py2exe.org/">py2exe</a> - Probably the most popular out there (<a href="http://stackoverflow.com/questions/2933/an-executable-python-app/31859#31859">PyInstaller</a> is also gaining in popularity)</li>
</ul>
<p><strong>Single executable (Linux)</strong></p>
<ul>
<li><a href="http://wiki.python.org/moin/Freeze">Freeze</a> - works the same way like py2exe but targets Linux platform</li>
</ul>
<p><strong>Single executable (Mac)</strong></p>
<ul>
<li><a href="https://pythonhosted.org/py2app/">py2app</a> - again, works like py2exe but targets Mac OS</li>
</ul>
| 189 | 2008-08-05T22:34:25Z | [
"python",
"user-interface",
"deployment",
"tkinter",
"release-management"
] |
How can I create a directly-executable cross-platform GUI app using Python? | 2,933 | <p>Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux.</p>
<p>The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the right direction please?</p> | 171 | 2008-08-05T22:26:00Z | 2,941 | <p>You don't need to <em>compile</em> python for Mac/Windows/Linux. It is an interpreted language, so you simply need to have the Python interpreter installed on the system of your choice (it is available for all three platforms).</p>
<p>As for a GUI library that works cross platform, Python's <a href="http://www.tcl.tk/" rel="nofollow">Tk/Tcl</a> widget library works very well, and I believe is sufficiently cross platform.</p>
<p><a href="http://docs.python.org/lib/module-Tkinter.html" rel="nofollow">Tkinter</a> is the python interface to Tk/Tcl</p>
<p>From the python project webpage: </p>
<blockquote>
<p>Tkinter is not the only GuiProgramming
toolkit for Python. It is however the
most commonly used one, and almost the
only one that is portable between
Unix, Mac and Windows</p>
</blockquote> | 0 | 2008-08-05T22:40:17Z | [
"python",
"user-interface",
"deployment",
"tkinter",
"release-management"
] |
How can I create a directly-executable cross-platform GUI app using Python? | 2,933 | <p>Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux.</p>
<p>The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the right direction please?</p> | 171 | 2008-08-05T22:26:00Z | 2,980 | <p>Since python is installed on nearly every non-Windows OS by default now, the only thing you really need to make sure of is that all of the non-standard libraries you use are installed.</p>
<p>Having said that, it is possible to build executables that include the python interpreter, and any libraries you use. This is likely to create a large executable, however.</p>
<p>MacOS X even includes support in the Xcode IDE for creating full standalone GUI apps. These can be run by any user running OS X.</p> | 2 | 2008-08-06T00:29:36Z | [
"python",
"user-interface",
"deployment",
"tkinter",
"release-management"
] |
How can I create a directly-executable cross-platform GUI app using Python? | 2,933 | <p>Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux.</p>
<p>The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the right direction please?</p> | 171 | 2008-08-05T22:26:00Z | 12,166 | <p>An alternative tool to py2exe is <a href="http://pypi.python.org/pypi/bbfreeze/">bbfreeze</a> which generates executables for windows and linux. It's newer than py2exe and handles eggs quite well. I've found it magically works better without configuration for a wide variety of applications.</p>
| 13 | 2008-08-15T11:56:02Z | [
"python",
"user-interface",
"deployment",
"tkinter",
"release-management"
] |
How can I create a directly-executable cross-platform GUI app using Python? | 2,933 | <p>Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux.</p>
<p>The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the right direction please?</p> | 171 | 2008-08-05T22:26:00Z | 12,167 | <p>I'm not sure that this is the best way to do it, but when I'm deploying Ruby GUI apps (not Python, but has the same "problem" as far as .exe's are concerned) on Windows, I just write a short launcher in C# that calls on my main script. It compiles to an executable, and I then have an application executable.</p>
| 2 | 2008-08-15T12:00:37Z | [
"python",
"user-interface",
"deployment",
"tkinter",
"release-management"
] |
How can I create a directly-executable cross-platform GUI app using Python? | 2,933 | <p>Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux.</p>
<p>The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the right direction please?</p> | 171 | 2008-08-05T22:26:00Z | 15,938 | <p>For the GUI itself:</p>
<p><a href="http://wiki.python.org/moin/PyQt" rel="nofollow">PyQT</a> is pretty much the reference.</p>
<p>Another way to develop a rapid user interface is to write a web app,
have it run locally and display the app in the browser.</p>
<p>Plus, if you go for the Tkinter option suggested by lubos hasko
you may want to try portablepy to have your app run on Windows environment
without Python.</p>
| 3 | 2008-08-19T09:45:44Z | [
"python",
"user-interface",
"deployment",
"tkinter",
"release-management"
] |
How can I create a directly-executable cross-platform GUI app using Python? | 2,933 | <p>Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux.</p>
<p>The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the right direction please?</p> | 171 | 2008-08-05T22:26:00Z | 31,859 | <p>Another system (not mentioned in the accepted answer yet) is PyInstaller, which worked for a PyQt project of mine when py2exe would not. I found it easier to use.</p>
<p><a href="http://www.pyinstaller.org/">http://www.pyinstaller.org/</a></p>
<p>Pyinstaller is based on Gordon McMillan's Python Installer. Which is no longer available.</p>
| 39 | 2008-08-28T08:41:45Z | [
"python",
"user-interface",
"deployment",
"tkinter",
"release-management"
] |
How can I create a directly-executable cross-platform GUI app using Python? | 2,933 | <p>Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux.</p>
<p>The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the right direction please?</p> | 171 | 2008-08-05T22:26:00Z | 265,570 | <p>There's also <a href="http://pygtk.org/">PyGTK</a>, which is basically a Python wrapper for the Gnome Toolkit. I've found it easier to wrap my mind around than Tkinter, coming from pretty much no knowledge of GUI programming previously. It works pretty well and has some good tutorials. Unfortunately there isn't an installer for Python 2.6 for Windows yet, and may not be for a while.</p>
| 7 | 2008-11-05T15:53:19Z | [
"python",
"user-interface",
"deployment",
"tkinter",
"release-management"
] |
Calling a function of a module from a string with the function's name in Python | 3,061 | <p>What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module <code>foo</code>, and I have a string whose contents are <code>"bar"</code>. What is the best way to go about calling <code>foo.bar()</code>?</p>
<p>I need to get the return value of the function, which is why I don't just use <code>eval</code>. I figured out how to do it by using <code>eval</code> to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this.</p>
| 761 | 2008-08-06T03:36:08Z | 3,071 | <p>Assuming module <code>foo</code> with method <code>bar</code>:</p>
<pre><code>import foo
methodToCall = getattr(foo, 'bar')
result = methodToCall()
</code></pre>
<p>As far as that goes, lines 2 and 3 can be compressed to:</p>
<pre><code>result = getattr(foo, 'bar')()
</code></pre>
<p>if that makes more sense for your use case. You can use <code>getattr</code> in this fashion on class instance bound methods, module-level methods, class methods... the list goes on.</p>
| 925 | 2008-08-06T03:57:16Z | [
"python"
] |
Calling a function of a module from a string with the function's name in Python | 3,061 | <p>What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module <code>foo</code>, and I have a string whose contents are <code>"bar"</code>. What is the best way to go about calling <code>foo.bar()</code>?</p>
<p>I need to get the return value of the function, which is why I don't just use <code>eval</code>. I figured out how to do it by using <code>eval</code> to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this.</p>
| 761 | 2008-08-06T03:36:08Z | 4,605 | <p>Patrick's solution is probably the cleanest.
If you need to dynamically pick up the module as well, you can import it like:</p>
<pre><code>m = __import__ ('foo')
func = getattr(m,'bar')
func()
</code></pre>
| 145 | 2008-08-07T11:35:23Z | [
"python"
] |
Calling a function of a module from a string with the function's name in Python | 3,061 | <p>What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module <code>foo</code>, and I have a string whose contents are <code>"bar"</code>. What is the best way to go about calling <code>foo.bar()</code>?</p>
<p>I need to get the return value of the function, which is why I don't just use <code>eval</code>. I figured out how to do it by using <code>eval</code> to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this.</p>
| 761 | 2008-08-06T03:36:08Z | 834,451 | <pre><code>locals()["myfunction"]()
</code></pre>
<p>or</p>
<pre><code>globals()["myfunction"]()
</code></pre>
<p><a href="http://docs.python.org/library/functions.html#locals">locals</a> returns a dictionary with a current local symbol table. <a href="http://docs.python.org/library/functions.html#globals">globals</a> returns a dictionary with global symbol table.</p>
| 266 | 2009-05-07T12:45:13Z | [
"python"
] |
Calling a function of a module from a string with the function's name in Python | 3,061 | <p>What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module <code>foo</code>, and I have a string whose contents are <code>"bar"</code>. What is the best way to go about calling <code>foo.bar()</code>?</p>
<p>I need to get the return value of the function, which is why I don't just use <code>eval</code>. I figured out how to do it by using <code>eval</code> to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this.</p>
| 761 | 2008-08-06T03:36:08Z | 9,272,378 | <p>For what it's worth, if you needed to pass the function (or class) name and app name as a string, then you could do this:</p>
<pre><code>myFnName = "MyFn"
myAppName = "MyApp"
app = sys.modules[myAppName]
fn = getattr(app,myFnName)
</code></pre>
| 12 | 2012-02-14T05:55:36Z | [
"python"
] |
Calling a function of a module from a string with the function's name in Python | 3,061 | <p>What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module <code>foo</code>, and I have a string whose contents are <code>"bar"</code>. What is the best way to go about calling <code>foo.bar()</code>?</p>
<p>I need to get the return value of the function, which is why I don't just use <code>eval</code>. I figured out how to do it by using <code>eval</code> to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this.</p>
| 761 | 2008-08-06T03:36:08Z | 12,025,554 | <p>Just a simple contribution. If the class that we need to instance is in the same file, we can use something like this:</p>
<pre><code># Get class from globals and create an instance
m = globals()['our_class']()
# Get the function (from the instance) that we need to call
func = getattr(m, 'function_name')
# Call it
func()
</code></pre>
<p>For example:</p>
<pre><code>class A:
def __init__(self):
pass
def sampleFunc(self, arg):
print('you called sampleFunc({})'.format(arg))
m = globals()['A']()
func = getattr(m, 'sampleFunc')
func('sample arg')
# Sample, all on one line
getattr(globals()['A'](), 'sampleFunc')('sample arg')
</code></pre>
<p>And, if not a class:</p>
<pre><code>def sampleFunc(arg):
print('you called sampleFunc({})'.format(arg))
globals()['sampleFunc']('sample arg')
</code></pre>
| 46 | 2012-08-19T09:40:43Z | [
"python"
] |
Calling a function of a module from a string with the function's name in Python | 3,061 | <p>What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module <code>foo</code>, and I have a string whose contents are <code>"bar"</code>. What is the best way to go about calling <code>foo.bar()</code>?</p>
<p>I need to get the return value of the function, which is why I don't just use <code>eval</code>. I figured out how to do it by using <code>eval</code> to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this.</p>
| 761 | 2008-08-06T03:36:08Z | 14,072,943 | <p>none of what was suggested helped me. I did discover this though.</p>
<pre><code><object>.__getattribute__(<string name>)(<params>)
</code></pre>
<p>I am using python 2.66 </p>
<p>Hope this helps</p>
| 8 | 2012-12-28T16:56:45Z | [
"python"
] |
Calling a function of a module from a string with the function's name in Python | 3,061 | <p>What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module <code>foo</code>, and I have a string whose contents are <code>"bar"</code>. What is the best way to go about calling <code>foo.bar()</code>?</p>
<p>I need to get the return value of the function, which is why I don't just use <code>eval</code>. I figured out how to do it by using <code>eval</code> to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this.</p>
| 761 | 2008-08-06T03:36:08Z | 19,393,328 | <p>Given a string, with a complete python path to a function, this is how I went about getting the result of said function:</p>
<pre><code>import importlib
function_string = 'mypackage.mymodule.myfunc'
mod_name, func_name = function_string.rsplit('.',1)
mod = importlib.import_module(mod_name)
func = getattr(mod, func_name)
result = func()
</code></pre>
| 39 | 2013-10-16T00:24:22Z | [
"python"
] |
Calling a function of a module from a string with the function's name in Python | 3,061 | <p>What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module <code>foo</code>, and I have a string whose contents are <code>"bar"</code>. What is the best way to go about calling <code>foo.bar()</code>?</p>
<p>I need to get the return value of the function, which is why I don't just use <code>eval</code>. I figured out how to do it by using <code>eval</code> to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this.</p>
| 761 | 2008-08-06T03:36:08Z | 22,959,509 | <p>The answer (I hope) no one ever wanted</p>
<p>Eval like behavior</p>
<pre><code>getattr(locals().get("foo") or globals().get("foo"), "bar")()
</code></pre>
<p>Why not add auto-importing</p>
<pre><code>getattr(
locals().get("foo") or
globals().get("foo") or
__import__("foo"),
"bar")()
</code></pre>
<p>In case we have extra dictionaries we want to check</p>
<pre><code>getattr(next((x for x in (f("foo") for f in
[locals().get, globals().get,
self.__dict__.get, __import__])
if x)),
"bar")()
</code></pre>
<p>We need to go deeper</p>
<pre><code>getattr(next((x for x in (f("foo") for f in
([locals().get, globals().get, self.__dict__.get] +
[d.get for d in (list(dd.values()) for dd in
[locals(),globals(),self.__dict__]
if isinstance(dd,dict))
if isinstance(d,dict)] +
[__import__]))
if x)),
"bar")()
</code></pre>
| 17 | 2014-04-09T10:17:41Z | [
"python"
] |
Programmatically talking to a Serial Port in OS X or Linux | 3,976 | <p>I have a Prolite LED sign that I like to set up to show scrolling search queries from a apache logs and other fun statistics. The problem is, my G5 does not have a serial port, so I have to use a usb to serial dongle. It shows up as /dev/cu.usbserial and /dev/tty.usbserial . </p>
<p>When i do this everything seems to be hunky-dory:</p>
<pre><code>stty -f /dev/cu.usbserial
speed 9600 baud;
lflags: -icanon -isig -iexten -echo
iflags: -icrnl -ixon -ixany -imaxbel -brkint
oflags: -opost -onlcr -oxtabs
cflags: cs8 -parenb
</code></pre>
<p>Everything also works when I use the <a href="http://www.versiontracker.com/dyn/moreinfo/macosx/24024">serial port tool</a> to talk to it.</p>
<p>If I run this piece of code while the above mentioned serial port tool, everthing also works. But as soon as I disconnect the tool the connection gets lost. </p>
<pre><code>#!/usr/bin/python
import serial
ser = serial.Serial('/dev/cu.usbserial', 9600, timeout=10)
ser.write("<ID01><PA> \r\n")
read_chars = ser.read(20)
print read_chars
ser.close()
</code></pre>
<p>So the question is, what magicks do I need to perform to start talking to the serial port without the serial port tool? Is that a permissions problem? Also, what's the difference between /dev/cu.usbserial and /dev/tty.usbserial?</p>
<hr>
<p>Nope, no serial numbers. The thing is, the problem persists even with sudo-running the python script, and the only thing that makes it go through if I open the connection in the gui tool that I mentioned.</p>
| 12 | 2008-08-06T21:00:01Z | 4,128 | <p>have you tried watching the traffic between the GUI and the serial port to see if there is some kind of special command being sent across? Also just curious, Python is sending ASCII and not UTF-8 or something else right? The reason I ask is because I noticed your quote changes for the strings and in some languages that actually is the difference between ASCII and UTF-8.</p>
| 0 | 2008-08-06T23:40:43Z | [
"python",
"linux",
"osx",
"serial-port"
] |
Programmatically talking to a Serial Port in OS X or Linux | 3,976 | <p>I have a Prolite LED sign that I like to set up to show scrolling search queries from a apache logs and other fun statistics. The problem is, my G5 does not have a serial port, so I have to use a usb to serial dongle. It shows up as /dev/cu.usbserial and /dev/tty.usbserial . </p>
<p>When i do this everything seems to be hunky-dory:</p>
<pre><code>stty -f /dev/cu.usbserial
speed 9600 baud;
lflags: -icanon -isig -iexten -echo
iflags: -icrnl -ixon -ixany -imaxbel -brkint
oflags: -opost -onlcr -oxtabs
cflags: cs8 -parenb
</code></pre>
<p>Everything also works when I use the <a href="http://www.versiontracker.com/dyn/moreinfo/macosx/24024">serial port tool</a> to talk to it.</p>
<p>If I run this piece of code while the above mentioned serial port tool, everthing also works. But as soon as I disconnect the tool the connection gets lost. </p>
<pre><code>#!/usr/bin/python
import serial
ser = serial.Serial('/dev/cu.usbserial', 9600, timeout=10)
ser.write("<ID01><PA> \r\n")
read_chars = ser.read(20)
print read_chars
ser.close()
</code></pre>
<p>So the question is, what magicks do I need to perform to start talking to the serial port without the serial port tool? Is that a permissions problem? Also, what's the difference between /dev/cu.usbserial and /dev/tty.usbserial?</p>
<hr>
<p>Nope, no serial numbers. The thing is, the problem persists even with sudo-running the python script, and the only thing that makes it go through if I open the connection in the gui tool that I mentioned.</p>
| 12 | 2008-08-06T21:00:01Z | 4,162 | <p><code>/dev/cu.xxxxx</code> is the "callout" device, it's what you use when you establish a connection to the serial device and start talking to it. <code>/dev/tty.xxxxx</code> is the "dialin" device, used for monitoring a port for incoming calls for e.g. a fax listener.</p> | 4 | 2008-08-07T00:19:03Z | [
"python",
"linux",
"osx",
"serial-port"
] |
How to sell Python to a client/boss/person with lots of cash | 4,942 | <p>When asked to create system XYZ and you ask to do it in Python over PHP or Ruby, what are the main features you can mention when they require you to explain it?</p> | 5 | 2008-08-07T16:43:21Z | 4,958 | <p>Focus on the shorter time needed for development/prototype and possibly easier maintenance (none of this may apply against Ruby).</p> | 2 | 2008-08-07T16:50:43Z | [
"php",
"python",
"ruby-on-rails",
"ruby"
] |
How to sell Python to a client/boss/person with lots of cash | 4,942 | <p>When asked to create system XYZ and you ask to do it in Python over PHP or Ruby, what are the main features you can mention when they require you to explain it?</p> | 5 | 2008-08-07T16:43:21Z | 4,978 | <p>This is one of those cases that really boil down to personal preference or situational details. If you're more comfortable and experienced with Python, then say so. Are they asking you to justify it because they're more comfortable with one of the other environments? After you're done, will the system be passed off to someone else for long-term maintenance?</p>
<p>If they ask you to use a technology or language that you're not as familiar with, then make sure they know up-front that it's going to take you longer.</p> | 11 | 2008-08-07T17:04:25Z | [
"php",
"python",
"ruby-on-rails",
"ruby"
] |
How to sell Python to a client/boss/person with lots of cash | 4,942 | <p>When asked to create system XYZ and you ask to do it in Python over PHP or Ruby, what are the main features you can mention when they require you to explain it?</p> | 5 | 2008-08-07T16:43:21Z | 5,014 | <p>I would consider that using python on a new project is completely dependent on what problem you are trying to solve with python. If you want someone to agree with you that you should use python, then show them how python's features apply specifically to that problem.</p>
<p>In the case of web development with python, talk about WSGI and other web libraries and frameworks you could use that would make your life easier. One note for python is that most of the frameworks for python web development can be plugged right into any current project. With ruby on rails, you're practically working in a DSL that anyone who uses your project will have to learn. If they know python, then they can figure out what you are doing with django, etc in a day.</p>
<p>I'm only talking about web development because it appears that's what you are going to be working on seeing ruby, python and PHP in the same list. The real message that's important is applying to whatever it is you like about python <em>directly</em> to some problem you are trying to solve.</p> | 3 | 2008-08-07T17:30:10Z | [
"php",
"python",
"ruby-on-rails",
"ruby"
] |
How to sell Python to a client/boss/person with lots of cash | 4,942 | <p>When asked to create system XYZ and you ask to do it in Python over PHP or Ruby, what are the main features you can mention when they require you to explain it?</p> | 5 | 2008-08-07T16:43:21Z | 15,291 | <p>I agree with mreggen. Tell them by working in Python you can get things done faster. Getting things done faster possibly means money saved by the client. In the least it means that you are working with a language you a more comfortable in, meaning faster development, debugging, and refactoring time. There will be less time spent looking up documentation on what function to use to find the length of a string, etc. </p>
| 0 | 2008-08-18T22:06:02Z | [
"php",
"python",
"ruby-on-rails",
"ruby"
] |
How to sell Python to a client/boss/person with lots of cash | 4,942 | <p>When asked to create system XYZ and you ask to do it in Python over PHP or Ruby, what are the main features you can mention when they require you to explain it?</p> | 5 | 2008-08-07T16:43:21Z | 15,296 | <p>It's one of the preferred languages over at Google - It's several years ahead of Ruby in terms of "maturity" (what ever that really means - but managers like that). Since it's prefered by Google you can also run it on the Google App Engine.</p>
<p>Mircosoft is also embracing Python, and will have a v2.0 of IronPython coming out shortly. They are working on a Ruby implementation as well, but the Python version is way ahead, and is actually "ready for primetime". That give you the possibility for easy integration with .NET code, as well as being able to write client side RIAs in Python when Silverlight 2 ships.</p>
| 4 | 2008-08-18T22:10:13Z | [
"php",
"python",
"ruby-on-rails",
"ruby"
] |
How to sell Python to a client/boss/person with lots of cash | 4,942 | <p>When asked to create system XYZ and you ask to do it in Python over PHP or Ruby, what are the main features you can mention when they require you to explain it?</p> | 5 | 2008-08-07T16:43:21Z | 21,221 | <p>The best sell of Python I've ever seen was by a manager in our group who had a young daughter. He used a quote attributed to Einstein:</p>
<blockquote>
<p>If you can't explain something to a six-year-old, you really don't understand it yourself.</p>
</blockquote>
<p>The next few slides of his presentation demonstrated how he was able to teach his young daughter some basic Python in less than 30 minutes, with examples of the code she wrote and an explanation of what it did.</p>
<p>He ended the presentation with a picture of his daughter and her quote "Programming is fun!"</p>
<p>I would focus on Python's user friendliness and wealth of libraries and frameworks. There are also a lot of little libraries that you might not get in other languages, and would have to write yourself (i.e. <a href="http://blog.programmerslog.com/?p=124">How a C++ developer writes Python</a>).</p>
<p>Good luck!</p>
| 6 | 2008-08-21T21:24:10Z | [
"php",
"python",
"ruby-on-rails",
"ruby"
] |
How to sell Python to a client/boss/person with lots of cash | 4,942 | <p>When asked to create system XYZ and you ask to do it in Python over PHP or Ruby, what are the main features you can mention when they require you to explain it?</p> | 5 | 2008-08-07T16:43:21Z | 9,420,311 | <p>Give them a snippet of code in each (no more than a page) that performs some cool function that they will like. (e.g show outliers in a data set).</p>
<p>Show them each page. One in PHP, Ruby and Python.</p>
<p>Ask them which they find easiest to understand/read.</p>
<p>Tell them thats why you want to use Python. It's easier to read if you've not written it, more manageable, less buggy and quicker to build features because it is the most elegant (pythonic)</p>
| 0 | 2012-02-23T19:59:12Z | [
"php",
"python",
"ruby-on-rails",
"ruby"
] |
How to sell Python to a client/boss/person with lots of cash | 4,942 | <p>When asked to create system XYZ and you ask to do it in Python over PHP or Ruby, what are the main features you can mention when they require you to explain it?</p> | 5 | 2008-08-07T16:43:21Z | 32,847,801 | <p>Though <em>All 3 languages are versatile and used worldwide by programmers</em>, Python still have some advantages over the other two. Like From my personal experience :-</p>
<blockquote>
<ol>
<li>Non-programmers love it (most of 'em choose Python as their first computer language,check this infographic <a href="https://blog.udemy.com/wp-content/uploads/2012/01/PROGRAMMING-LANGUAGE-3.png" rel="nofollow">php vs python vs ruby</a> here)</li>
<li>Multiple frameworks (You can automate your system tasks, can develop apps for web and windows/mac/android OSes)</li>
<li>Making OpenCV apps easily than MATLAB </li>
<li>Testing done easy (you can work on Selenium for all kind of web testing)</li>
</ol>
</blockquote>
<p>OOPS concepts are followed by most languages now , so how come Python can stay behind! Inheritance, Abstraction and Encapsulation are followed by Python as well.</p>
<p>Python as of now is divided into two versions popularly that are not much different in terms of performance but features. <strong>Python2.x and Python 3.x</strong> both have same syntax ,except for some statements like :-</p>
<ol>
<li><strong>print "..."</strong> in Python2.x and <strong>print()</strong> in Python3.x</li>
<li><strong>raw_input()</strong> in Python2.x and <strong>input()</strong> in Python3.x (<em>for getting user input</em>)</li>
</ol>
<p>In the end, client only cares about money and Python helps you save a lot as compared to PHP and Ruby , because instead of hiring experienced programmers , you can make a newbie learn and use Python expertly.</p>
| 0 | 2015-09-29T15:18:37Z | [
"php",
"python",
"ruby-on-rails",
"ruby"
] |
How do you set up Python scripts to work in Apache 2.0? | 5,102 | <p>I tried to follow a couple of googled up tutorials on setting up mod_python, but failed every time. Do you have a good, step-by step, rock-solid howto?</p>
<p>My dev box is OS X, production - Centos.</p> | 14 | 2008-08-07T18:24:12Z | 5,129 | <p>There are two main ways of running Python on Apache. The simplest would be to use CGI and write normal Python scripts while the second is using a web framework like Django or Pylons.</p>
<p>Using CGI is straightforward. Make sure your Apache config file has a cgi-bin set up. If not, follow their documentation (<a href="http://httpd.apache.org/docs/2.0/howto/cgi.html" rel="nofollow">http://httpd.apache.org/docs/2.0/howto/cgi.html</a>). At that point all you need to do is place your Python scripts in the cgi-bin directory and the standard output will become the HTTP response. Refer to Python's documentation for further info (<a href="https://docs.python.org/library/cgi.html" rel="nofollow">https://docs.python.org/library/cgi.html</a>).</p>
<p>If you want to use a web framework you'll need to setup mod_python or FastCGI. These steps are dependent on which framework you want to use. Django provides clear instructions on how to setup mod_python and Django with Apache (<a href="http://www.djangoproject.com/documentation/modpython/" rel="nofollow">http://www.djangoproject.com/documentation/modpython/</a>)</p>
| 12 | 2008-08-07T18:40:53Z | [
"python",
"apache",
"apache2"
] |
How do you set up Python scripts to work in Apache 2.0? | 5,102 | <p>I tried to follow a couple of googled up tutorials on setting up mod_python, but failed every time. Do you have a good, step-by step, rock-solid howto?</p>
<p>My dev box is OS X, production - Centos.</p> | 14 | 2008-08-07T18:24:12Z | 5,165 | <p>Yes, mod_python is pretty confusing to set up. Here's how I did it.</p>
<p>In httpd.conf:</p>
<pre><code>LoadModule python_module modules/mod_python.so<br><br><Directory "/serverbase/htdocs/myapp"><br> AddHandler mod_python .py<br> PythonHandler myapp<br> PythonDebug On<br></code></pre>
<p>and in your application directory:</p>
<pre><code>$ /serverbase/htdocs/myapp$ ls -l<br>total 16<br>-r-xr-xr-x 1 root sys 6484 May 21 15:54 myapp.py<br></code></pre>
<p>Repeat the configuration for each python program you wish to have running under mod_python.</p> | 8 | 2008-08-07T19:02:57Z | [
"python",
"apache",
"apache2"
] |
How do you set up Python scripts to work in Apache 2.0? | 5,102 | <p>I tried to follow a couple of googled up tutorials on setting up mod_python, but failed every time. Do you have a good, step-by step, rock-solid howto?</p>
<p>My dev box is OS X, production - Centos.</p> | 14 | 2008-08-07T18:24:12Z | 5,168 | <p>Are you running Python on UNIX or Windows?</p>
<p>An alternative to mod_python and FastCGI is mod_wsgi. You can find out more at <a href="http://code.google.com/p/modwsgi/" rel="nofollow">modwsgi</a></p>
<p>I have built and installed this on Solaris without problems. I had previously tried mod_python but ran into problems with shared libraries as part of the build. There are <a href="http://code.google.com/p/modwsgi/wiki/InstallationInstructions" rel="nofollow">good install docs</a> available.</p>
| 5 | 2008-08-07T19:05:58Z | [
"python",
"apache",
"apache2"
] |
How do you set up Python scripts to work in Apache 2.0? | 5,102 | <p>I tried to follow a couple of googled up tutorials on setting up mod_python, but failed every time. Do you have a good, step-by step, rock-solid howto?</p>
<p>My dev box is OS X, production - Centos.</p> | 14 | 2008-08-07T18:24:12Z | 14,791,003 | <p>The problem for me wasn't in Apache set up, but in understanding how mod_apache actually uses the .py files. Module-level statements (including those in a <code>if __name__=='__main__'</code> section) are <em>not</em> executed--I assumed that the stdout from running the script at the commandline would be what the server would output, but that's not how it works.</p>
<p>Instead, I wrote a module-level function called <code>index()</code>, and had it return as a string the HTML of the page. It's also possible to have other module-level functions (e.g., <code>otherFunction()</code>) that can be accessed as further segments in the URI (e.g., <code>testScript/otherFunction</code> for the file <code>testScript.py</code>.)</p>
<p>Obviously, this makes more sense than my original stdout conception. Better capability of actually using Python as a scripting language and not a humongous markup language.</p>
| 0 | 2013-02-09T20:05:07Z | [
"python",
"apache",
"apache2"
] |
Does anyone have experience creating a shared library in MATLAB? | 5,136 | <p>A researcher has created a small simulation in MATLAB, and we want to make it accessible to others. My plan is to take the simulation, clean up a few things, and turn it into a set of functions. Then, I plan to compile it into a C library and use SWIG to create a Python wrapper. At that point, I should be able to call the simulation from a small Django app. At least, I hope so.</p>
<p>Do I have the right plan? Has anyone else done something similar? Can you let me know if there are some serious pitfalls I'm not aware of at the moment?</p> | 6 | 2008-08-07T18:47:58Z | 5,302 | <p>I won't help much but I remember that I was able to wrap MATLAB simulation into DLL and then call it from Delphi app. It work really well.</p>
<p>Anyway: good luck!!!</p> | 4 | 2008-08-07T20:57:20Z | [
"python",
"c",
"matlab"
] |
Does anyone have experience creating a shared library in MATLAB? | 5,136 | <p>A researcher has created a small simulation in MATLAB, and we want to make it accessible to others. My plan is to take the simulation, clean up a few things, and turn it into a set of functions. Then, I plan to compile it into a C library and use SWIG to create a Python wrapper. At that point, I should be able to call the simulation from a small Django app. At least, I hope so.</p>
<p>Do I have the right plan? Has anyone else done something similar? Can you let me know if there are some serious pitfalls I'm not aware of at the moment?</p> | 6 | 2008-08-07T18:47:58Z | 16,189 | <p>Perhaps try <a href="http://python.net/crew/theller/ctypes/" rel="nofollow">ctypes </a>instead of SWIG. If it has been included as a part of Python 2.5, then it must be good :-)</p>
| 1 | 2008-08-19T13:51:47Z | [
"python",
"c",
"matlab"
] |
Does anyone have experience creating a shared library in MATLAB? | 5,136 | <p>A researcher has created a small simulation in MATLAB, and we want to make it accessible to others. My plan is to take the simulation, clean up a few things, and turn it into a set of functions. Then, I plan to compile it into a C library and use SWIG to create a Python wrapper. At that point, I should be able to call the simulation from a small Django app. At least, I hope so.</p>
<p>Do I have the right plan? Has anyone else done something similar? Can you let me know if there are some serious pitfalls I'm not aware of at the moment?</p> | 6 | 2008-08-07T18:47:58Z | 138,534 | <p>I'd also try ctypes first. </p>
<ol>
<li>Use the Matlab compiler to compile the code into C. </li>
<li>Compile the C code into a DLL.</li>
<li>Use ctypes to load and call code from this DLL</li>
</ol>
<p>The hardest step is probably 1, but if you already know Matlab and have used the Matlab compiler, you should not have serious problems with it.</p>
| 2 | 2008-09-26T09:55:39Z | [
"python",
"c",
"matlab"
] |
Does anyone have experience creating a shared library in MATLAB? | 5,136 | <p>A researcher has created a small simulation in MATLAB, and we want to make it accessible to others. My plan is to take the simulation, clean up a few things, and turn it into a set of functions. Then, I plan to compile it into a C library and use SWIG to create a Python wrapper. At that point, I should be able to call the simulation from a small Django app. At least, I hope so.</p>
<p>Do I have the right plan? Has anyone else done something similar? Can you let me know if there are some serious pitfalls I'm not aware of at the moment?</p> | 6 | 2008-08-07T18:47:58Z | 1,659,332 | <p>One thing to remember is that the Matlab compiler does not actually compile the Matlab code into native machine instructions. It simply wraps it into a standalone executable or a library with its own runtime engine that runs it. You would be able to run your code without Matlab installed, and you would be able to interface it with other languages, but it will still be interpreted Matlab code, so there would be no speedup.</p>
| 5 | 2009-11-02T03:43:54Z | [
"python",
"c",
"matlab"
] |
Cross Platform, Language Agnostic GUI Markup Language? | 5,313 | <p>I learned Swing back in the day but now I've moved to Python and want to make some apps with GUIs. I haven't had the time to learn a new GUI API so I've been using Jython, but I would prefer to use CPython. </p>
<p>It would be great if I can have one simple markup that allows me to switch GUI libraries. It would be even better if I can use the same markup language across languages so I can quickly make GUIs for any language I'm using. Does anyone know of such a markup/library?</p>
<p>I've seen markups like Glade and wxWidget's markup (I forget the name). They're partly what I'm looking for (making a GUI without coding it in a language) but they're intertwined with a specific library. And neither are really nice looking or friendly to human editting.</p> | 11 | 2008-08-07T21:07:24Z | 5,319 | <p>erm.. HTML? (trying to be funny here... while we wait for real answers..)</p> | 8 | 2008-08-07T21:10:27Z | [
"python",
"user-interface",
"markup"
] |
Cross Platform, Language Agnostic GUI Markup Language? | 5,313 | <p>I learned Swing back in the day but now I've moved to Python and want to make some apps with GUIs. I haven't had the time to learn a new GUI API so I've been using Jython, but I would prefer to use CPython. </p>
<p>It would be great if I can have one simple markup that allows me to switch GUI libraries. It would be even better if I can use the same markup language across languages so I can quickly make GUIs for any language I'm using. Does anyone know of such a markup/library?</p>
<p>I've seen markups like Glade and wxWidget's markup (I forget the name). They're partly what I'm looking for (making a GUI without coding it in a language) but they're intertwined with a specific library. And neither are really nice looking or friendly to human editting.</p> | 11 | 2008-08-07T21:07:24Z | 5,320 | <p>The <a href="http://www.wxwidgets.org/" rel="nofollow" title="wxWidgets">wxWidgets</a> (formerly known as wxWindows) library might be what you're looking for. There's a particularly good port for Python, <a href="http://wxpython.org/" rel="nofollow" title="wxPython">wxPython</a>, as well as versions for different languages -- C#, C++, Perl and Ruby come to mind -- and for various GUIs: Win32, Mac OS X, GTK+, X11, Motif, WinCE. The library's been around for a while and is pretty solid.</p> | 1 | 2008-08-07T21:11:28Z | [
"python",
"user-interface",
"markup"
] |
Cross Platform, Language Agnostic GUI Markup Language? | 5,313 | <p>I learned Swing back in the day but now I've moved to Python and want to make some apps with GUIs. I haven't had the time to learn a new GUI API so I've been using Jython, but I would prefer to use CPython. </p>
<p>It would be great if I can have one simple markup that allows me to switch GUI libraries. It would be even better if I can use the same markup language across languages so I can quickly make GUIs for any language I'm using. Does anyone know of such a markup/library?</p>
<p>I've seen markups like Glade and wxWidget's markup (I forget the name). They're partly what I'm looking for (making a GUI without coding it in a language) but they're intertwined with a specific library. And neither are really nice looking or friendly to human editting.</p> | 11 | 2008-08-07T21:07:24Z | 5,340 | <P>Not sure if this is what you're looking for, but there's <A href="http://glade.gnome.org/" rel="nofollow">Glade</A> (or <A href="http://gladewin32.sourceforge.net/" rel="nofollow">Windows download</A>) which is a designer for GTK+. It generates an XML file which can then be used to build the GUI in a number of different languages.</P> | 3 | 2008-08-07T21:24:26Z | [
"python",
"user-interface",
"markup"
] |
Cross Platform, Language Agnostic GUI Markup Language? | 5,313 | <p>I learned Swing back in the day but now I've moved to Python and want to make some apps with GUIs. I haven't had the time to learn a new GUI API so I've been using Jython, but I would prefer to use CPython. </p>
<p>It would be great if I can have one simple markup that allows me to switch GUI libraries. It would be even better if I can use the same markup language across languages so I can quickly make GUIs for any language I'm using. Does anyone know of such a markup/library?</p>
<p>I've seen markups like Glade and wxWidget's markup (I forget the name). They're partly what I'm looking for (making a GUI without coding it in a language) but they're intertwined with a specific library. And neither are really nice looking or friendly to human editting.</p> | 11 | 2008-08-07T21:07:24Z | 5,343 | <p><a href="http://en.wikipedia.org/wiki/Qt_%28toolkit%29">Qt</a> (pronounced "cute" by its creators[1]) is a cross-platform application development framework, widely used for the development of GUI programs.</p>
<p>Qt uses <strong>C++</strong> with several non-standard extensions implemented by an additional pre-processor that generates standard C++ code before compilation. Qt can also be used in several other programming languages; bindings exist for <strong>Ada</strong> (QtAda)[4], C<strong>#</strong> (Qyoto/Kimono)[5], <strong>Java</strong> (Qt Jambi)[6], <strong>Pascal</strong>, <strong>Perl</strong>, <strong>PHP</strong> (PHP-Qt), <strong>Ruby</strong> (RubyQt), and <strong>Python</strong> (PyQt). It runs on all major platforms, and has extensive internationalization support. Non-GUI features include SQL database access, XML parsing, thread management, network support and a unified cross-platform API for file handling.</p> | 5 | 2008-08-07T21:25:26Z | [
"python",
"user-interface",
"markup"
] |
Cross Platform, Language Agnostic GUI Markup Language? | 5,313 | <p>I learned Swing back in the day but now I've moved to Python and want to make some apps with GUIs. I haven't had the time to learn a new GUI API so I've been using Jython, but I would prefer to use CPython. </p>
<p>It would be great if I can have one simple markup that allows me to switch GUI libraries. It would be even better if I can use the same markup language across languages so I can quickly make GUIs for any language I'm using. Does anyone know of such a markup/library?</p>
<p>I've seen markups like Glade and wxWidget's markup (I forget the name). They're partly what I'm looking for (making a GUI without coding it in a language) but they're intertwined with a specific library. And neither are really nice looking or friendly to human editting.</p> | 11 | 2008-08-07T21:07:24Z | 6,616 | <p><a href="http://www.mozilla.org/projects/xul/" rel="nofollow">XML User Interface Language</a>. Don't know much about it so not sure if it meets your desires. Post back with your experience if you play with it.</p> | 3 | 2008-08-09T04:44:41Z | [
"python",
"user-interface",
"markup"
] |
Cross Platform, Language Agnostic GUI Markup Language? | 5,313 | <p>I learned Swing back in the day but now I've moved to Python and want to make some apps with GUIs. I haven't had the time to learn a new GUI API so I've been using Jython, but I would prefer to use CPython. </p>
<p>It would be great if I can have one simple markup that allows me to switch GUI libraries. It would be even better if I can use the same markup language across languages so I can quickly make GUIs for any language I'm using. Does anyone know of such a markup/library?</p>
<p>I've seen markups like Glade and wxWidget's markup (I forget the name). They're partly what I'm looking for (making a GUI without coding it in a language) but they're intertwined with a specific library. And neither are really nice looking or friendly to human editting.</p> | 11 | 2008-08-07T21:07:24Z | 7,496 | <p>I read a little on XML User Interface Language (XUL) and it looks really robust and well supported. The main problem for me is it's tied to the Gecko rendering engine so it's cross platform the way wxWidgets, QT and GTK+ are cross platform. Also, there Python bindings don't seem as good as those other libraries.</p>
<p>GladeXML and XRC seem like better markups</p>
| 0 | 2008-08-11T03:11:55Z | [
"python",
"user-interface",
"markup"
] |
Cross Platform, Language Agnostic GUI Markup Language? | 5,313 | <p>I learned Swing back in the day but now I've moved to Python and want to make some apps with GUIs. I haven't had the time to learn a new GUI API so I've been using Jython, but I would prefer to use CPython. </p>
<p>It would be great if I can have one simple markup that allows me to switch GUI libraries. It would be even better if I can use the same markup language across languages so I can quickly make GUIs for any language I'm using. Does anyone know of such a markup/library?</p>
<p>I've seen markups like Glade and wxWidget's markup (I forget the name). They're partly what I'm looking for (making a GUI without coding it in a language) but they're intertwined with a specific library. And neither are really nice looking or friendly to human editting.</p> | 11 | 2008-08-07T21:07:24Z | 8,109 | <p>@Cristian and Antony Cramp: while XUL is a nice choice for UI development (cross-platform, open-source licensed, used in Firefox and other major software), it's certainly not language agnostic. You're tied to Gecko, with JS for scripting. There is experimental support for Python scripting, but it's only experimental, AFAIK.</p>
<p>You can define the UI in XUL+JS and use back-end components written in C++ though (there are Python and Java bridges available too).</p>
| 1 | 2008-08-11T19:17:41Z | [
"python",
"user-interface",
"markup"
] |
Cross Platform, Language Agnostic GUI Markup Language? | 5,313 | <p>I learned Swing back in the day but now I've moved to Python and want to make some apps with GUIs. I haven't had the time to learn a new GUI API so I've been using Jython, but I would prefer to use CPython. </p>
<p>It would be great if I can have one simple markup that allows me to switch GUI libraries. It would be even better if I can use the same markup language across languages so I can quickly make GUIs for any language I'm using. Does anyone know of such a markup/library?</p>
<p>I've seen markups like Glade and wxWidget's markup (I forget the name). They're partly what I'm looking for (making a GUI without coding it in a language) but they're intertwined with a specific library. And neither are really nice looking or friendly to human editting.</p> | 11 | 2008-08-07T21:07:24Z | 8,114 | <p>I seriously doubt you're going to find a markup language for GIU's that's <em>not</em> tied to a specific library. For such a thing to exist, there would need to be a standardized GUI markup language, with several implementations.</p>
| 4 | 2008-08-11T19:21:14Z | [
"python",
"user-interface",
"markup"
] |
Cross Platform, Language Agnostic GUI Markup Language? | 5,313 | <p>I learned Swing back in the day but now I've moved to Python and want to make some apps with GUIs. I haven't had the time to learn a new GUI API so I've been using Jython, but I would prefer to use CPython. </p>
<p>It would be great if I can have one simple markup that allows me to switch GUI libraries. It would be even better if I can use the same markup language across languages so I can quickly make GUIs for any language I'm using. Does anyone know of such a markup/library?</p>
<p>I've seen markups like Glade and wxWidget's markup (I forget the name). They're partly what I'm looking for (making a GUI without coding it in a language) but they're intertwined with a specific library. And neither are really nice looking or friendly to human editting.</p> | 11 | 2008-08-07T21:07:24Z | 1,607,717 | <p>I would go with XSLT, therefore it could be embedded in other interfaces as well.</p>
| 0 | 2009-10-22T14:39:51Z | [
"python",
"user-interface",
"markup"
] |
Cross Platform, Language Agnostic GUI Markup Language? | 5,313 | <p>I learned Swing back in the day but now I've moved to Python and want to make some apps with GUIs. I haven't had the time to learn a new GUI API so I've been using Jython, but I would prefer to use CPython. </p>
<p>It would be great if I can have one simple markup that allows me to switch GUI libraries. It would be even better if I can use the same markup language across languages so I can quickly make GUIs for any language I'm using. Does anyone know of such a markup/library?</p>
<p>I've seen markups like Glade and wxWidget's markup (I forget the name). They're partly what I'm looking for (making a GUI without coding it in a language) but they're intertwined with a specific library. And neither are really nice looking or friendly to human editting.</p> | 11 | 2008-08-07T21:07:24Z | 10,751,568 | <p>If you switch to .NET then you can use a common GUI language, for example Razor in MVC (if you are doing web development), and have a choice of C# or VB or a number of other languages.</p>
| 0 | 2012-05-25T09:09:28Z | [
"python",
"user-interface",
"markup"
] |
Convert Bytes to Floating Point Numbers in Python | 5,415 | <p>I have a binary file that I have to parse and I'm using Python. Is there a way to take 4 bytes and convert it to a single precision floating point number?</p> | 21 | 2008-08-07T22:24:27Z | 5,435 | <p>You'll want the <a href="https://docs.python.org/3.4/library/struct.html" rel="nofollow">struct</a> package.</p>
| 13 | 2008-08-07T22:35:48Z | [
"python",
"floating-point"
] |
Convert Bytes to Floating Point Numbers in Python | 5,415 | <p>I have a binary file that I have to parse and I'm using Python. Is there a way to take 4 bytes and convert it to a single precision floating point number?</p> | 21 | 2008-08-07T22:24:27Z | 73,281 | <pre><code>>>> import struct
>>> struct.pack('f', 3.141592654)
b'\xdb\x0fI@'
>>> struct.unpack('f', b'\xdb\x0fI@')
(3.1415927410125732,)
>>> struct.pack('4f', 1.0, 2.0, 3.0, 4.0)
'\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@'
</code></pre>
| 32 | 2008-09-16T14:59:37Z | [
"python",
"floating-point"
] |
Python, Unicode, and the Windows console | 5,419 | <p>When I try to print a Unicode string in a Windows console, I get a <code>UnicodeEncodeError: 'charmap' codec can't encode character ....</code> error. I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? Is there any way I can make Python automatically print a <code>?</code> instead of failing in this situation?</p>
<p><strong>Edit:</strong> I'm using Python 2.5.</p>
<hr>
<p><strong>Note:</strong> @LasseV.Karlsen answer with the checkmark is sort of outdated (from 2008). Please use the solutions/answers/suggestions below with care!!</p>
<p><a href="http://stackoverflow.com/a/32176732/610569">@JFSebastian answer</a> is more relevant as of today (6 Jan 2016).</p>
| 72 | 2008-08-07T22:26:58Z | 5,430 | <p><strong>Note:</strong> This answer is sort of outdated (from 2008). Please use the solution below with care!!</p>
<hr>
<p>Here is a page that details the problem and a solution (search the page for the text <em>Wrapping sys.stdout into an instance</em>):</p>
<p><a href="http://wiki.python.org/moin/PrintFails">PrintFails - Python Wiki</a></p>
<p>Here's a code excerpt from that page:</p>
<pre><code>$ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \
sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \
line = u"\u0411\n"; print type(line), len(line); \
sys.stdout.write(line); print line'
UTF-8
<type 'unicode'> 2
Ð
Ð
$ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \
sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \
line = u"\u0411\n"; print type(line), len(line); \
sys.stdout.write(line); print line' | cat
None
<type 'unicode'> 2
Ð
Ð
</code></pre>
<p>There's some more information on that page, well worth a read.</p>
| 24 | 2008-08-07T22:32:23Z | [
"python",
"unicode"
] |
Python, Unicode, and the Windows console | 5,419 | <p>When I try to print a Unicode string in a Windows console, I get a <code>UnicodeEncodeError: 'charmap' codec can't encode character ....</code> error. I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? Is there any way I can make Python automatically print a <code>?</code> instead of failing in this situation?</p>
<p><strong>Edit:</strong> I'm using Python 2.5.</p>
<hr>
<p><strong>Note:</strong> @LasseV.Karlsen answer with the checkmark is sort of outdated (from 2008). Please use the solutions/answers/suggestions below with care!!</p>
<p><a href="http://stackoverflow.com/a/32176732/610569">@JFSebastian answer</a> is more relevant as of today (6 Jan 2016).</p>
| 72 | 2008-08-07T22:26:58Z | 8,020 | <p>The cause of your problem is <strong>NOT</strong> the Win console not willing to accept Unicode (as it does this since I guess Win2k by default). It is the default system encoding. Try this code and see what it gives you:</p>
<pre><code>import sys
sys.getdefaultencoding()
</code></pre>
<p>if it says ascii, there's your cause ;-)
You have to create a file called sitecustomize.py and put it under python path (I put it under /usr/lib/python2.5/site-packages, but that is differen on Win - it is c:\python\lib\site-packages or something), with the following contents:</p>
<pre><code>import sys
sys.setdefaultencoding('utf-8')
</code></pre>
<p>and perhaps you might want to specify the encoding in your files as well:</p>
<pre><code># -*- coding: UTF-8 -*-
import sys,time
</code></pre>
<p>Edit: more info can be found <a href="http://www.diveintopython.net/xml_processing/unicode.html" rel="nofollow">in excellent the Dive into Python book</a></p>
| -1 | 2008-08-11T17:58:28Z | [
"python",
"unicode"
] |
Python, Unicode, and the Windows console | 5,419 | <p>When I try to print a Unicode string in a Windows console, I get a <code>UnicodeEncodeError: 'charmap' codec can't encode character ....</code> error. I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? Is there any way I can make Python automatically print a <code>?</code> instead of failing in this situation?</p>
<p><strong>Edit:</strong> I'm using Python 2.5.</p>
<hr>
<p><strong>Note:</strong> @LasseV.Karlsen answer with the checkmark is sort of outdated (from 2008). Please use the solutions/answers/suggestions below with care!!</p>
<p><a href="http://stackoverflow.com/a/32176732/610569">@JFSebastian answer</a> is more relevant as of today (6 Jan 2016).</p>
| 72 | 2008-08-07T22:26:58Z | 2,013,263 | <p>The below code will make Python output to console as UTF-8 even on Windows. </p>
<p>The console will display the characters well on Windows 7 but on Windows XP it will not display them well, but at least it will work and most important you will have a consistent output from your script on all platforms. You'll be able to redirect the output to a file.</p>
<p>Below code was tested with Python 2.6 on Windows.</p>
<pre><code>
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import codecs, sys
reload(sys)
sys.setdefaultencoding('utf-8')
print sys.getdefaultencoding()
if sys.platform == 'win32':
try:
import win32console
except:
print "Python Win32 Extensions module is required.\n You can download it from https://sourceforge.net/projects/pywin32/ (x86 and x64 builds are available)\n"
exit(-1)
# win32console implementation of SetConsoleCP does not return a value
# CP_UTF8 = 65001
win32console.SetConsoleCP(65001)
if (win32console.GetConsoleCP() != 65001):
raise Exception ("Cannot set console codepage to 65001 (UTF-8)")
win32console.SetConsoleOutputCP(65001)
if (win32console.GetConsoleOutputCP() != 65001):
raise Exception ("Cannot set console output codepage to 65001 (UTF-8)")
#import sys, codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)
print "This is an Ðä¹Î±mpÙ¡È
testing Unicode support using Arabic, Latin, Cyrillic, Greek, Hebrew and CJK code points.\n"
</code></pre>
| 7 | 2010-01-06T13:38:39Z | [
"python",
"unicode"
] |
Python, Unicode, and the Windows console | 5,419 | <p>When I try to print a Unicode string in a Windows console, I get a <code>UnicodeEncodeError: 'charmap' codec can't encode character ....</code> error. I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? Is there any way I can make Python automatically print a <code>?</code> instead of failing in this situation?</p>
<p><strong>Edit:</strong> I'm using Python 2.5.</p>
<hr>
<p><strong>Note:</strong> @LasseV.Karlsen answer with the checkmark is sort of outdated (from 2008). Please use the solutions/answers/suggestions below with care!!</p>
<p><a href="http://stackoverflow.com/a/32176732/610569">@JFSebastian answer</a> is more relevant as of today (6 Jan 2016).</p>
| 72 | 2008-08-07T22:26:58Z | 4,637,795 | <p>Despite the other plausible-sounding answers that suggest changing the code page to 65001, that <a href="http://bugs.python.org/issue1602">does not work</a>. (Also, changing the default encoding using <code>sys.setdefaultencoding</code> is <a href="http://stackoverflow.com/questions/3578685/how-to-display-utf-8-in-windows-console/3580165#3580165">not a good idea</a>.)</p>
<p>See <a href="http://stackoverflow.com/questions/878972/windows-cmd-encoding-change-causes-python-crash/3259271">this question</a> for details and code that does work.</p>
| 19 | 2011-01-09T05:07:56Z | [
"python",
"unicode"
] |
Python, Unicode, and the Windows console | 5,419 | <p>When I try to print a Unicode string in a Windows console, I get a <code>UnicodeEncodeError: 'charmap' codec can't encode character ....</code> error. I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? Is there any way I can make Python automatically print a <code>?</code> instead of failing in this situation?</p>
<p><strong>Edit:</strong> I'm using Python 2.5.</p>
<hr>
<p><strong>Note:</strong> @LasseV.Karlsen answer with the checkmark is sort of outdated (from 2008). Please use the solutions/answers/suggestions below with care!!</p>
<p><a href="http://stackoverflow.com/a/32176732/610569">@JFSebastian answer</a> is more relevant as of today (6 Jan 2016).</p>
| 72 | 2008-08-07T22:26:58Z | 10,667,978 | <p>If you're not interested in getting a reliable representation of the bad character(s) you might use something like this (working with python >= 2.6, including 3.x):</p>
<pre><code>from __future__ import print_function
import sys
def safeprint(s):
try:
print(s)
except UnicodeEncodeError:
if sys.version_info >= (3,):
print(s.encode('utf8').decode(sys.stdout.encoding))
else:
print(s.encode('utf8'))
safeprint(u"\N{EM DASH}")
</code></pre>
<p>The bad character(s) in the string will be converted in a representation which is printable by the Windows console.</p>
| 10 | 2012-05-19T18:48:28Z | [
"python",
"unicode"
] |
Python, Unicode, and the Windows console | 5,419 | <p>When I try to print a Unicode string in a Windows console, I get a <code>UnicodeEncodeError: 'charmap' codec can't encode character ....</code> error. I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? Is there any way I can make Python automatically print a <code>?</code> instead of failing in this situation?</p>
<p><strong>Edit:</strong> I'm using Python 2.5.</p>
<hr>
<p><strong>Note:</strong> @LasseV.Karlsen answer with the checkmark is sort of outdated (from 2008). Please use the solutions/answers/suggestions below with care!!</p>
<p><a href="http://stackoverflow.com/a/32176732/610569">@JFSebastian answer</a> is more relevant as of today (6 Jan 2016).</p>
| 72 | 2008-08-07T22:26:58Z | 32,176,732 | <p><strong>Update:</strong> <a href="https://docs.python.org/3.6/whatsnew/3.6.html#pep-528-change-windows-console-encoding-to-utf-8" rel="nofollow">Python 3.6</a> implements <a href="https://www.python.org/dev/peps/pep-0528/" rel="nofollow">PEP 528: Change Windows console encoding to UTF-8</a>: <em>the default console on Windows will now accept all Unicode characters.</em> Internally, it uses the same Unicode API as <a href="https://github.com/Drekin/win-unicode-console" rel="nofollow">the <code>win-unicode-console</code> package mentioned below</a>. <code>print(unicode_string)</code> should just work now.</p>
<hr>
<blockquote>
<p>I get a <code>UnicodeEncodeError: 'charmap' codec can't encode character...</code> error. </p>
</blockquote>
<p>The error means that Unicode characters that you are trying to print can't be represented using the current (<code>chcp</code>) console character encoding. The codepage is often 8-bit encoding such as <code>cp437</code> that can represent only ~0x100 characters from ~1M Unicode characters:</p>
<pre>>>> u"\N{EURO SIGN}".encode('cp437')
Traceback (most recent call last):
...
UnicodeEncodeError: 'charmap' codec can't encode character '\u20ac' in position 0:
character maps to </pre>
<blockquote>
<p>I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? </p>
</blockquote>
<p>Windows console does accept Unicode characters and it can even display them (BMP only) <strong>if the corresponding font is configured</strong>. <code>WriteConsoleW()</code> API should be used as suggested in <a href="http://stackoverflow.com/a/4637795/4279">@Daira Hopwood's answer</a>. It can be called transparently i.e., you don't need to and should not modify your scripts if you use <a href="https://github.com/Drekin/win-unicode-console" rel="nofollow"><code>win-unicode-console</code> package</a>:</p>
<pre><code>T:\> py -mpip install win-unicode-console
T:\> py -mrun your_script.py
</code></pre>
<p>See <a href="http://stackoverflow.com/a/30551552/4279">What's the deal with Python 3.4, Unicode, different languages and Windows?</a></p>
<blockquote>
<p>Is there any way I can make Python
automatically print a <code>?</code> instead of failing in this situation?</p>
</blockquote>
<p>If it is enough to replace all unencodable characters with <code>?</code> in your case then you could set <a href="https://docs.python.org/3/using/cmdline.html#envvar-PYTHONIOENCODING" rel="nofollow"><code>PYTHONIOENCODING</code> envvar</a>:</p>
<pre><code>T:\> set PYTHONIOENCODING=:replace
T:\> python3 -c "print(u'[\N{EURO SIGN}]')"
[?]
</code></pre>
<p>In Python 3.6+, the encoding specified by <code>PYTHONIOENCODING</code> envvar is ignored for interactive console buffers unless <code>PYTHONLEGACYWINDOWSIOENCODING</code> envvar is set to a non-empty string. </p>
| 13 | 2015-08-24T07:35:32Z | [
"python",
"unicode"
] |
Python, Unicode, and the Windows console | 5,419 | <p>When I try to print a Unicode string in a Windows console, I get a <code>UnicodeEncodeError: 'charmap' codec can't encode character ....</code> error. I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? Is there any way I can make Python automatically print a <code>?</code> instead of failing in this situation?</p>
<p><strong>Edit:</strong> I'm using Python 2.5.</p>
<hr>
<p><strong>Note:</strong> @LasseV.Karlsen answer with the checkmark is sort of outdated (from 2008). Please use the solutions/answers/suggestions below with care!!</p>
<p><a href="http://stackoverflow.com/a/32176732/610569">@JFSebastian answer</a> is more relevant as of today (6 Jan 2016).</p>
| 72 | 2008-08-07T22:26:58Z | 34,306,583 | <p>Kind of related on the answer by J. F. Sebastian, but more direct.</p>
<p>If you are having this problem when printing to the console/terminal, then do this:</p>
<pre><code>>set PYTHONIOENCODING=UTF-8
</code></pre>
| -1 | 2015-12-16T07:53:43Z | [
"python",
"unicode"
] |
Python, Unicode, and the Windows console | 5,419 | <p>When I try to print a Unicode string in a Windows console, I get a <code>UnicodeEncodeError: 'charmap' codec can't encode character ....</code> error. I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? Is there any way I can make Python automatically print a <code>?</code> instead of failing in this situation?</p>
<p><strong>Edit:</strong> I'm using Python 2.5.</p>
<hr>
<p><strong>Note:</strong> @LasseV.Karlsen answer with the checkmark is sort of outdated (from 2008). Please use the solutions/answers/suggestions below with care!!</p>
<p><a href="http://stackoverflow.com/a/32176732/610569">@JFSebastian answer</a> is more relevant as of today (6 Jan 2016).</p>
| 72 | 2008-08-07T22:26:58Z | 35,903,736 | <p>Like Giampaolo Rodolà 's answer, but even more dirty: I really, really intend to spend a long time (soon) understanding the whole subject of encodings and how they apply to Windoze consoles, </p>
<p>For the moment I just wanted sthg which would mean my program would NOT CRASH, and which I understood ... and also which didn't involve importing too many exotic modules (in particular I'm using Jython, so half the time a Python module turns out not in fact to be available).</p>
<pre><code>def pr(s):
try:
print(s)
except UnicodeEncodeError:
for c in s:
try:
print( c, end='')
except UnicodeEncodeError:
print( '?', end='')
</code></pre>
<p>NB "pr" is shorter to type than "print" (and quite a bit shorter to type than "safeprint")...!</p>
| 1 | 2016-03-09T22:14:15Z | [
"python",
"unicode"
] |
Python, Unicode, and the Windows console | 5,419 | <p>When I try to print a Unicode string in a Windows console, I get a <code>UnicodeEncodeError: 'charmap' codec can't encode character ....</code> error. I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? Is there any way I can make Python automatically print a <code>?</code> instead of failing in this situation?</p>
<p><strong>Edit:</strong> I'm using Python 2.5.</p>
<hr>
<p><strong>Note:</strong> @LasseV.Karlsen answer with the checkmark is sort of outdated (from 2008). Please use the solutions/answers/suggestions below with care!!</p>
<p><a href="http://stackoverflow.com/a/32176732/610569">@JFSebastian answer</a> is more relevant as of today (6 Jan 2016).</p>
| 72 | 2008-08-07T22:26:58Z | 37,229,972 | <p>James Sulak asked,</p>
<blockquote>
<p>Is there any way I can make Python automatically print a ? instead of failing in this situation?</p>
</blockquote>
<p>Other solutions recommend we attempt to modify the Windows environment or replace Python's <code>print()</code> function. The answer below comes closer to fulfilling Sulak's request.</p>
<p>Under Windows 7, Python 3.5 can be made to print Unicode without throwing a <code>UnicodeEncodeError</code> as follows:</p>
<p> In place of:
<code>print(text)</code><br>
substitute:
<code>print(str(text).encode('utf-8'))</code></p>
<p>Instead of throwing an exception, Python now displays unprintable Unicode characters as <em>\xNN</em> hex codes, e.g.:</p>
<p> <em>Halmalo n\xe2\x80\x99\xc3\xa9tait plus qu\xe2\x80\x99un point noir</em></p>
<p>Instead of</p>
<p> <em>Halmalo nâétait plus quâun point noir</em></p>
<p>Granted, the latter is preferable <em>ceteris paribus</em>, but otherwise the former is completely accurate for diagnostic messages. Because it displays Unicode as literal byte values the former may also assist in diagnosing encode/decode problems.</p>
<p><strong>Note:</strong> The <code>str()</code> call above is needed because otherwise <code>encode()</code> causes Python to reject a Unicode character as a tuple of numbers.</p>
| -1 | 2016-05-14T17:47:35Z | [
"python",
"unicode"
] |
Get size of a file before downloading in Python | 5,909 | <p>I'm downloading an entire directory from a web server. It works OK, but I can't figure how to get the file size before download to compare if it was updated on the server or not. Can this be done as if I was downloading the file from a FTP server?</p>
<pre><code>import urllib
import re
url = "http://www.someurl.com"
# Download the page locally
f = urllib.urlopen(url)
html = f.read()
f.close()
f = open ("temp.htm", "w")
f.write (html)
f.close()
# List only the .TXT / .ZIP files
fnames = re.findall('^.*<a href="(\w+(?:\.txt|.zip)?)".*$', html, re.MULTILINE)
for fname in fnames:
print fname, "..."
f = urllib.urlopen(url + "/" + fname)
#### Here I want to check the filesize to download or not ####
file = f.read()
f.close()
f = open (fname, "w")
f.write (file)
f.close()
</code></pre>
<hr>
<p>@Jon: thank for your quick answer. It works, but the filesize on the web server is slightly less than the filesize of the downloaded file. </p>
<p>Examples:</p>
<pre><code>Local Size Server Size
2.223.533 2.115.516
664.603 662.121
</code></pre>
<p>It has anything to do with the CR/LF conversion?</p>
| 28 | 2008-08-08T13:35:19Z | 5,927 | <p>The size of the file is sent as the Content-Length header. Here is how to get it with urllib:</p>
<pre><code>>>> site = urllib.urlopen("http://python.org")<br>>>> meta = site.info()<br>>>> print meta.getheaders("Content-Length")<br>['16535']<br>>>><br></code></pre> | 6 | 2008-08-08T13:41:43Z | [
"python",
"urllib"
] |
Get size of a file before downloading in Python | 5,909 | <p>I'm downloading an entire directory from a web server. It works OK, but I can't figure how to get the file size before download to compare if it was updated on the server or not. Can this be done as if I was downloading the file from a FTP server?</p>
<pre><code>import urllib
import re
url = "http://www.someurl.com"
# Download the page locally
f = urllib.urlopen(url)
html = f.read()
f.close()
f = open ("temp.htm", "w")
f.write (html)
f.close()
# List only the .TXT / .ZIP files
fnames = re.findall('^.*<a href="(\w+(?:\.txt|.zip)?)".*$', html, re.MULTILINE)
for fname in fnames:
print fname, "..."
f = urllib.urlopen(url + "/" + fname)
#### Here I want to check the filesize to download or not ####
file = f.read()
f.close()
f = open (fname, "w")
f.write (file)
f.close()
</code></pre>
<hr>
<p>@Jon: thank for your quick answer. It works, but the filesize on the web server is slightly less than the filesize of the downloaded file. </p>
<p>Examples:</p>
<pre><code>Local Size Server Size
2.223.533 2.115.516
664.603 662.121
</code></pre>
<p>It has anything to do with the CR/LF conversion?</p>
| 28 | 2008-08-08T13:35:19Z | 5,935 | <p>Using the returned-urllib-object method <code>info()</code>, you can get various information on the retrived document. Example of grabbing the current Google logo:</p>
<pre><code>>>> import urllib<br>>>> d = urllib.urlopen("http://www.google.co.uk/logos/olympics08_opening.gif")<br>>>> print d.info()<br><br>Content-Type: image/gif<br>Last-Modified: Thu, 07 Aug 2008 16:20:19 GMT <br>Expires: Sun, 17 Jan 2038 19:14:07 GMT <br>Cache-Control: public <br>Date: Fri, 08 Aug 2008 13:40:41 GMT <br>Server: gws <br>Content-Length: 20172 <br>Connection: Close<br></code></pre>
<p>It's a dict, so to get the size of the file, you do <code>urllibobject.info()['Content-Length']</code></p>
<pre><code>print f.info()['Content-Length']<br></code></pre>
<p>And to get the size of the local file (for comparison), you can use the os.stat() command:</p>
<pre><code>os.stat("/the/local/file.zip").st_size<br></code></pre> | 16 | 2008-08-08T13:47:26Z | [
"python",
"urllib"
] |
Get size of a file before downloading in Python | 5,909 | <p>I'm downloading an entire directory from a web server. It works OK, but I can't figure how to get the file size before download to compare if it was updated on the server or not. Can this be done as if I was downloading the file from a FTP server?</p>
<pre><code>import urllib
import re
url = "http://www.someurl.com"
# Download the page locally
f = urllib.urlopen(url)
html = f.read()
f.close()
f = open ("temp.htm", "w")
f.write (html)
f.close()
# List only the .TXT / .ZIP files
fnames = re.findall('^.*<a href="(\w+(?:\.txt|.zip)?)".*$', html, re.MULTILINE)
for fname in fnames:
print fname, "..."
f = urllib.urlopen(url + "/" + fname)
#### Here I want to check the filesize to download or not ####
file = f.read()
f.close()
f = open (fname, "w")
f.write (file)
f.close()
</code></pre>
<hr>
<p>@Jon: thank for your quick answer. It works, but the filesize on the web server is slightly less than the filesize of the downloaded file. </p>
<p>Examples:</p>
<pre><code>Local Size Server Size
2.223.533 2.115.516
664.603 662.121
</code></pre>
<p>It has anything to do with the CR/LF conversion?</p>
| 28 | 2008-08-08T13:35:19Z | 5,938 | <p>Also if the server you are connecting to supports it, look at <a href="http://en.wikipedia.org/wiki/HTTP_ETag" rel="nofollow">Etags</a> and the <a href="http://en.wikipedia.org/wiki/List_of_HTTP_headers#Requests" rel="nofollow">If-Modified-Since</a> and <a href="http://en.wikipedia.org/wiki/List_of_HTTP_headers#Requests" rel="nofollow">If-None-Match</a> headers.</p>
<p>Using these will take advantage of the webserver's caching rules and will return a <a href="http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_Redirection" rel="nofollow">304 Not Modified</a> status code if the content hasn't changed.</p> | 4 | 2008-08-08T13:51:23Z | [
"python",
"urllib"
] |
Get size of a file before downloading in Python | 5,909 | <p>I'm downloading an entire directory from a web server. It works OK, but I can't figure how to get the file size before download to compare if it was updated on the server or not. Can this be done as if I was downloading the file from a FTP server?</p>
<pre><code>import urllib
import re
url = "http://www.someurl.com"
# Download the page locally
f = urllib.urlopen(url)
html = f.read()
f.close()
f = open ("temp.htm", "w")
f.write (html)
f.close()
# List only the .TXT / .ZIP files
fnames = re.findall('^.*<a href="(\w+(?:\.txt|.zip)?)".*$', html, re.MULTILINE)
for fname in fnames:
print fname, "..."
f = urllib.urlopen(url + "/" + fname)
#### Here I want to check the filesize to download or not ####
file = f.read()
f.close()
f = open (fname, "w")
f.write (file)
f.close()
</code></pre>
<hr>
<p>@Jon: thank for your quick answer. It works, but the filesize on the web server is slightly less than the filesize of the downloaded file. </p>
<p>Examples:</p>
<pre><code>Local Size Server Size
2.223.533 2.115.516
664.603 662.121
</code></pre>
<p>It has anything to do with the CR/LF conversion?</p>
| 28 | 2008-08-08T13:35:19Z | 5,985 | <p>I have reproduced what you are seeing:</p>
<pre><code>import urllib, os<br>link = "http://python.org"<br>print "opening url:", link<br>site = urllib.urlopen(link)<br>meta = site.info()<br>print "Content-Length:", meta.getheaders("Content-Length")[0]<br><br>f = open("out.txt", "r")<br>print "File on disk:",len(f.read())<br>f.close()<br><br><br>f = open("out.txt", "w")<br>f.write(site.read())<br>site.close()<br>f.close()<br><br>f = open("out.txt", "r")<br>print "File on disk after download:",len(f.read())<br>f.close()<br><br>print "os.stat().st_size returns:", os.stat("out.txt").st_size<br></code></pre>
<p>Outputs this:</p>
<pre><code>opening url: http://python.org<br>Content-Length: 16535<br>File on disk: 16535<br>File on disk after download: 16535<br>os.stat().st_size returns: 16861<br></code></pre>
<p>What am I doing wrong here? Is os.stat().st_size not returning the correct size?</p>
<hr>
<p>Edit:
OK, I figured out what the problem was:</p>
<pre><code>import urllib, os<br>link = "http://python.org"<br>print "opening url:", link<br>site = urllib.urlopen(link)<br>meta = site.info()<br>print "Content-Length:", meta.getheaders("Content-Length")[0]<br><br>f = open("out.txt", "rb")<br>print "File on disk:",len(f.read())<br>f.close()<br><br><br>f = open("out.txt", "wb")<br>f.write(site.read())<br>site.close()<br>f.close()<br><br>f = open("out.txt", "rb")<br>print "File on disk after download:",len(f.read())<br>f.close()<br><br>print "os.stat().st_size returns:", os.stat("out.txt").st_size<br></code></pre>
<p>this outputs:</p>
<pre><code>$ python test.py<br>opening url: http://python.org<br>Content-Length: 16535<br>File on disk: 16535<br>File on disk after download: 16535<br>os.stat().st_size returns: 16535<br></code></pre>
<p>Make sure you are opening both files for binary read/write.</p>
<pre><code>// open for binary write<br>open(filename, "wb")<br>// open for binary read<br>open(filename, "rb")<br></code></pre> | 19 | 2008-08-08T14:21:51Z | [
"python",
"urllib"
] |
Get size of a file before downloading in Python | 5,909 | <p>I'm downloading an entire directory from a web server. It works OK, but I can't figure how to get the file size before download to compare if it was updated on the server or not. Can this be done as if I was downloading the file from a FTP server?</p>
<pre><code>import urllib
import re
url = "http://www.someurl.com"
# Download the page locally
f = urllib.urlopen(url)
html = f.read()
f.close()
f = open ("temp.htm", "w")
f.write (html)
f.close()
# List only the .TXT / .ZIP files
fnames = re.findall('^.*<a href="(\w+(?:\.txt|.zip)?)".*$', html, re.MULTILINE)
for fname in fnames:
print fname, "..."
f = urllib.urlopen(url + "/" + fname)
#### Here I want to check the filesize to download or not ####
file = f.read()
f.close()
f = open (fname, "w")
f.write (file)
f.close()
</code></pre>
<hr>
<p>@Jon: thank for your quick answer. It works, but the filesize on the web server is slightly less than the filesize of the downloaded file. </p>
<p>Examples:</p>
<pre><code>Local Size Server Size
2.223.533 2.115.516
664.603 662.121
</code></pre>
<p>It has anything to do with the CR/LF conversion?</p>
| 28 | 2008-08-08T13:35:19Z | 25,502,448 | <p>In Python3:</p>
<pre><code>>>> import urllib.request
>>> site = urllib.request.urlopen("http://python.org")
>>> print("FileSize: ", site.length)
</code></pre>
| 1 | 2014-08-26T09:31:46Z | [
"python",
"urllib"
] |
Best way to abstract season/show/episode data | 5,966 | <p>Basically, I've written an API to www.thetvdb.com in Python. The current code can be found <a href="http://github.com/dbr/tvdb_api/tree/master/tvdb_api.py">here</a>.</p>
<p>It grabs data from the API as requested, and has to store the data somehow, and make it available by doing:</p>
<pre><code>print tvdbinstance[1][23]['episodename'] # get the name of episode 23 of season 1<br></code></pre>
<p>What is the "best" way to abstract this data within the Tvdb() class?</p>
<p>I originally used a extended Dict() that automatically created sub-dicts (so you could do <code>x[1][2][3][4] = "something"</code> without having to do <code>if x[1].has_key(2): x[1][2] = []</code> and so on)</p>
<p>Then I just stored the data by doing <code>self.data[show_id][season_number][episode_number][attribute_name] = "something"</code></p>
<p>This worked okay, but there was no easy way of checking if x[3][24] was supposed to exist or not (so I couldn't raise the season_not_found exception)</p>
<p>Currently it's using four classes. ShowContainer, Show, Season and Episode. Each one is a very basic dict, which I can easily add extra functionality in (the search() function on Show() for example). Each has a <code>__setitem__</code>, <code>__getitem_</code> and <code>has_key</code></p>
<p>This works mostly fine, I can check in Shows if it has that season in it's self.data dict, if not, raise season_not_found. Check in Season() if it has that episode and so on.</p>
<p>The problem now is it's presenting itself as a dict, but doesn't have all the functionality, and because I'm overriding the <em>_getitem_</em> and <em>_setitem_</em> functions, it's easy to accidently recursively call <em>_getitem_</em> (so I'm not sure if extending the Dict class will cause problems)</p>
<p>The other slight problem is adding data into the dict is a lot more work than the old Ddict method (which was <code>self.data[seas_no][ep_no]['attribute'] = 'something'</code>). See _setItem and _setData. It's not too bad, since it's currently only a read-only API interface (so the users of the API should only ever retrieve data, not add more), but it's hardly.. elegant..</p>
<p>I think the series-of-classes system is probably the best way, but does anyone have a better idea for storing the data? And would extending the ShowContainer/etc classes with Dict cause problems?</p> | 10 | 2008-08-08T14:05:45Z | 6,125 | <p>Why not use SQLite? There is good support in Python and you can write SQL queries to get the data out. Here is the Python docs for <a href="http://docs.python.org/lib/module-sqlite3.html" rel="nofollow">sqlite3</a></p>
<hr>
<p>If you don't want to use SQLite you could do an array of dicts.</p>
<pre><code>episodes = []<br>episodes.append({'season':1, 'episode': 2, 'name':'Something'})<br>episodes.append({'season':1, 'episode': 2, 'name':'Something', 'actors':['Billy Bob', 'Sean Penn']})<br></code></pre>
<p>That way you add metadata to any record and search it very easily</p>
<pre><code>season_1 = [e for e in episodes if e['season'] == 1]<br>billy_bob = [e for e in episodes if 'actors' in e and 'Billy Bob' in e['actors']]<br><br>for episode in billy_bob:<br> print "Billy bob was in Season %s Episode %s" % (episode['season'], episode['episode'])<br></code></pre> | 3 | 2008-08-08T16:45:50Z | [
"python",
"data-structures"
] |
Best way to abstract season/show/episode data | 5,966 | <p>Basically, I've written an API to www.thetvdb.com in Python. The current code can be found <a href="http://github.com/dbr/tvdb_api/tree/master/tvdb_api.py">here</a>.</p>
<p>It grabs data from the API as requested, and has to store the data somehow, and make it available by doing:</p>
<pre><code>print tvdbinstance[1][23]['episodename'] # get the name of episode 23 of season 1<br></code></pre>
<p>What is the "best" way to abstract this data within the Tvdb() class?</p>
<p>I originally used a extended Dict() that automatically created sub-dicts (so you could do <code>x[1][2][3][4] = "something"</code> without having to do <code>if x[1].has_key(2): x[1][2] = []</code> and so on)</p>
<p>Then I just stored the data by doing <code>self.data[show_id][season_number][episode_number][attribute_name] = "something"</code></p>
<p>This worked okay, but there was no easy way of checking if x[3][24] was supposed to exist or not (so I couldn't raise the season_not_found exception)</p>
<p>Currently it's using four classes. ShowContainer, Show, Season and Episode. Each one is a very basic dict, which I can easily add extra functionality in (the search() function on Show() for example). Each has a <code>__setitem__</code>, <code>__getitem_</code> and <code>has_key</code></p>
<p>This works mostly fine, I can check in Shows if it has that season in it's self.data dict, if not, raise season_not_found. Check in Season() if it has that episode and so on.</p>
<p>The problem now is it's presenting itself as a dict, but doesn't have all the functionality, and because I'm overriding the <em>_getitem_</em> and <em>_setitem_</em> functions, it's easy to accidently recursively call <em>_getitem_</em> (so I'm not sure if extending the Dict class will cause problems)</p>
<p>The other slight problem is adding data into the dict is a lot more work than the old Ddict method (which was <code>self.data[seas_no][ep_no]['attribute'] = 'something'</code>). See _setItem and _setData. It's not too bad, since it's currently only a read-only API interface (so the users of the API should only ever retrieve data, not add more), but it's hardly.. elegant..</p>
<p>I think the series-of-classes system is probably the best way, but does anyone have a better idea for storing the data? And would extending the ShowContainer/etc classes with Dict cause problems?</p> | 10 | 2008-08-08T14:05:45Z | 6,805 | <P>I have done something similar in the past and used an in-memory XML document as a quick and dirty hierachical database for storage. You can store each show/season/episode as an element (nested appropriately) and attributes of these things as xml attributes on the elements. Then you can use XQuery to get info back out.</P>
<P><STRONG>NOTE:</STRONG> I'm not a Python guy so I don't know what your xml support is like.</P>
<P><STRONG>NOTE 2:</STRONG> You'll want to profile this because it'll be bigger and slower than the solution you've already got. Likely enough if you are doing some high-volume processing then XML is probably not going to be your friend.</P> | 0 | 2008-08-09T15:13:14Z | [
"python",
"data-structures"
] |
Best way to abstract season/show/episode data | 5,966 | <p>Basically, I've written an API to www.thetvdb.com in Python. The current code can be found <a href="http://github.com/dbr/tvdb_api/tree/master/tvdb_api.py">here</a>.</p>
<p>It grabs data from the API as requested, and has to store the data somehow, and make it available by doing:</p>
<pre><code>print tvdbinstance[1][23]['episodename'] # get the name of episode 23 of season 1<br></code></pre>
<p>What is the "best" way to abstract this data within the Tvdb() class?</p>
<p>I originally used a extended Dict() that automatically created sub-dicts (so you could do <code>x[1][2][3][4] = "something"</code> without having to do <code>if x[1].has_key(2): x[1][2] = []</code> and so on)</p>
<p>Then I just stored the data by doing <code>self.data[show_id][season_number][episode_number][attribute_name] = "something"</code></p>
<p>This worked okay, but there was no easy way of checking if x[3][24] was supposed to exist or not (so I couldn't raise the season_not_found exception)</p>
<p>Currently it's using four classes. ShowContainer, Show, Season and Episode. Each one is a very basic dict, which I can easily add extra functionality in (the search() function on Show() for example). Each has a <code>__setitem__</code>, <code>__getitem_</code> and <code>has_key</code></p>
<p>This works mostly fine, I can check in Shows if it has that season in it's self.data dict, if not, raise season_not_found. Check in Season() if it has that episode and so on.</p>
<p>The problem now is it's presenting itself as a dict, but doesn't have all the functionality, and because I'm overriding the <em>_getitem_</em> and <em>_setitem_</em> functions, it's easy to accidently recursively call <em>_getitem_</em> (so I'm not sure if extending the Dict class will cause problems)</p>
<p>The other slight problem is adding data into the dict is a lot more work than the old Ddict method (which was <code>self.data[seas_no][ep_no]['attribute'] = 'something'</code>). See _setItem and _setData. It's not too bad, since it's currently only a read-only API interface (so the users of the API should only ever retrieve data, not add more), but it's hardly.. elegant..</p>
<p>I think the series-of-classes system is probably the best way, but does anyone have a better idea for storing the data? And would extending the ShowContainer/etc classes with Dict cause problems?</p> | 10 | 2008-08-08T14:05:45Z | 8,165 | <p>I don't get this part here:</p>
<blockquote>
<p>This worked okay, but there was no easy way of checking if x[3][24] was supposed to exist or not (so I couldn't raise the season<em>not</em>found exception)</p>
</blockquote>
<p>There is a way to do it - called <strong>in</strong>:</p>
<pre><code>>>>x={}
>>>x[1]={}
>>>x[1][2]={}
>>>x
{1: {2: {}}}
>>> 2 in x[1]
True
>>> 3 in x[1]
False
</code></pre>
<p>what seems to be the problem with that?</p>
| 0 | 2008-08-11T20:07:59Z | [
"python",
"data-structures"
] |
Best way to abstract season/show/episode data | 5,966 | <p>Basically, I've written an API to www.thetvdb.com in Python. The current code can be found <a href="http://github.com/dbr/tvdb_api/tree/master/tvdb_api.py">here</a>.</p>
<p>It grabs data from the API as requested, and has to store the data somehow, and make it available by doing:</p>
<pre><code>print tvdbinstance[1][23]['episodename'] # get the name of episode 23 of season 1<br></code></pre>
<p>What is the "best" way to abstract this data within the Tvdb() class?</p>
<p>I originally used a extended Dict() that automatically created sub-dicts (so you could do <code>x[1][2][3][4] = "something"</code> without having to do <code>if x[1].has_key(2): x[1][2] = []</code> and so on)</p>
<p>Then I just stored the data by doing <code>self.data[show_id][season_number][episode_number][attribute_name] = "something"</code></p>
<p>This worked okay, but there was no easy way of checking if x[3][24] was supposed to exist or not (so I couldn't raise the season_not_found exception)</p>
<p>Currently it's using four classes. ShowContainer, Show, Season and Episode. Each one is a very basic dict, which I can easily add extra functionality in (the search() function on Show() for example). Each has a <code>__setitem__</code>, <code>__getitem_</code> and <code>has_key</code></p>
<p>This works mostly fine, I can check in Shows if it has that season in it's self.data dict, if not, raise season_not_found. Check in Season() if it has that episode and so on.</p>
<p>The problem now is it's presenting itself as a dict, but doesn't have all the functionality, and because I'm overriding the <em>_getitem_</em> and <em>_setitem_</em> functions, it's easy to accidently recursively call <em>_getitem_</em> (so I'm not sure if extending the Dict class will cause problems)</p>
<p>The other slight problem is adding data into the dict is a lot more work than the old Ddict method (which was <code>self.data[seas_no][ep_no]['attribute'] = 'something'</code>). See _setItem and _setData. It's not too bad, since it's currently only a read-only API interface (so the users of the API should only ever retrieve data, not add more), but it's hardly.. elegant..</p>
<p>I think the series-of-classes system is probably the best way, but does anyone have a better idea for storing the data? And would extending the ShowContainer/etc classes with Dict cause problems?</p> | 10 | 2008-08-08T14:05:45Z | 9,080 | <p>Bartosz/To clarify "This worked okay, but there was no easy way of checking if x[3][24] was supposed to exist or not"</p>
<p><code>x['some show'][3][24]</code> would return season 3, episode 24 of "some show". If there was no season 3, I want the pseudo-dict to raise tvdb<em>seasonnotfound, if "some show" doesn't exist, then raise tvdb</em>shownotfound</p>
<p>The current system of a series of classes, each with a <code>__getitem__</code> - Show checks <code>if self.seasons.has_key(requested_season_number)</code>, the Season class checks <code>if self.episodes.has_key(requested_episode_number)</code> and so on.</p>
<p>It works, but it there seems to be a lot of repeated code (each class is basically the same, but raises a different error)</p>
| 0 | 2008-08-12T17:55:22Z | [
"python",
"data-structures"
] |
Best way to abstract season/show/episode data | 5,966 | <p>Basically, I've written an API to www.thetvdb.com in Python. The current code can be found <a href="http://github.com/dbr/tvdb_api/tree/master/tvdb_api.py">here</a>.</p>
<p>It grabs data from the API as requested, and has to store the data somehow, and make it available by doing:</p>
<pre><code>print tvdbinstance[1][23]['episodename'] # get the name of episode 23 of season 1<br></code></pre>
<p>What is the "best" way to abstract this data within the Tvdb() class?</p>
<p>I originally used a extended Dict() that automatically created sub-dicts (so you could do <code>x[1][2][3][4] = "something"</code> without having to do <code>if x[1].has_key(2): x[1][2] = []</code> and so on)</p>
<p>Then I just stored the data by doing <code>self.data[show_id][season_number][episode_number][attribute_name] = "something"</code></p>
<p>This worked okay, but there was no easy way of checking if x[3][24] was supposed to exist or not (so I couldn't raise the season_not_found exception)</p>
<p>Currently it's using four classes. ShowContainer, Show, Season and Episode. Each one is a very basic dict, which I can easily add extra functionality in (the search() function on Show() for example). Each has a <code>__setitem__</code>, <code>__getitem_</code> and <code>has_key</code></p>
<p>This works mostly fine, I can check in Shows if it has that season in it's self.data dict, if not, raise season_not_found. Check in Season() if it has that episode and so on.</p>
<p>The problem now is it's presenting itself as a dict, but doesn't have all the functionality, and because I'm overriding the <em>_getitem_</em> and <em>_setitem_</em> functions, it's easy to accidently recursively call <em>_getitem_</em> (so I'm not sure if extending the Dict class will cause problems)</p>
<p>The other slight problem is adding data into the dict is a lot more work than the old Ddict method (which was <code>self.data[seas_no][ep_no]['attribute'] = 'something'</code>). See _setItem and _setData. It's not too bad, since it's currently only a read-only API interface (so the users of the API should only ever retrieve data, not add more), but it's hardly.. elegant..</p>
<p>I think the series-of-classes system is probably the best way, but does anyone have a better idea for storing the data? And would extending the ShowContainer/etc classes with Dict cause problems?</p> | 10 | 2008-08-08T14:05:45Z | 10,778 | <p>OK, what you need is <code>classobj</code> from new module. That would allow you to construct exception classes dynamically (<code>classobj</code> takes a string as an argument for the class name). </p>
<pre><code>import new
myexc=new.classobj("ExcName",(Exception,),{})
i=myexc("This is the exc msg!")
raise i
</code></pre>
<p>this gives you:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.ExcName: This is the exc msg!
</code></pre>
<p>remember that you can always get the class name through:</p>
<pre><code>self.__class__.__name__
</code></pre>
<p>So, after some string mangling and concatenation, you should be able to obtain appropriate exception class name and construct a class object using that name and then raise that exception.</p>
<p>P.S. - you can also raise strings, but this is deprecated.</p>
<pre><code>raise(self.__class__.__name__+"Exception")
</code></pre>
| 5 | 2008-08-14T07:08:19Z | [
"python",
"data-structures"
] |
Pylons error - 'MySQL server has gone away' | 8,154 | <p>[I hope this isn't too obscure… I'll ask the newsgroup if nobody knows here]</p>
<p>I'm using Pylons (a python framework) to serve a simple web application, but it seems to die from time to time, with this in the error log: <code>(2006, 'MySQL server has gone away')</code></p>
<p>I did a bit of checking, and saw that this was because the connections to MySQL were not being renewed. This shouldn't be a problem though, because the <code>sqlalchemy.pool_recycle</code> in the config file should automatically keep it alive. The default was <code>3600</code>, but I dialed it back to <code>1800</code> because of this problem. It helped a bit, but <code>3600</code> <em>should</em> be fine according to the docs. The errors still happen semi-regularly. I don't want to lower it too much though and DOS my own database :).</p>
<p>Maybe something in my MySQL config is goofy? Not sure where to look exactly.</p>
<p>Other relevant details:</p>
<pre><code> Python 2.5
Pylons: 0.9.6.2 (w/ sql_alchemy)
MySQL: 5.0.51
</code></pre>
| 10 | 2008-08-11T19:59:32Z | 15,261 | <p>You might want to check MySQL's timeout variables:</p>
<pre><code>show variables like '%timeout%';
</code></pre>
<p>You're probably interested in <code>wait_timeout</code> (less likely but possible: <code>interactive_timeout</code>). On Debian and Ubuntu, the defaults are 28800 (MySQL kills connections after 8 hours), but maybe the default for your platform is different or whoever administrates the server has configured things differently.</p>
<p>AFAICT, <code>pool_recycle</code> doesn't actually keep the connections alive, it expires them on its own before MySQL kills them. I'm not familiar with pylons, but if causing the connections to intermittently do a <code>SELECT 1;</code> is an option, that will keep them alive at the cost of basically no server load and minimal network traffic. One final thought: are you somehow managing to use a connection that pylons thinks it has expired?</p>
| 2 | 2008-08-18T21:35:39Z | [
"python",
"mysql",
"pylons"
] |
Pylons error - 'MySQL server has gone away' | 8,154 | <p>[I hope this isn't too obscure… I'll ask the newsgroup if nobody knows here]</p>
<p>I'm using Pylons (a python framework) to serve a simple web application, but it seems to die from time to time, with this in the error log: <code>(2006, 'MySQL server has gone away')</code></p>
<p>I did a bit of checking, and saw that this was because the connections to MySQL were not being renewed. This shouldn't be a problem though, because the <code>sqlalchemy.pool_recycle</code> in the config file should automatically keep it alive. The default was <code>3600</code>, but I dialed it back to <code>1800</code> because of this problem. It helped a bit, but <code>3600</code> <em>should</em> be fine according to the docs. The errors still happen semi-regularly. I don't want to lower it too much though and DOS my own database :).</p>
<p>Maybe something in my MySQL config is goofy? Not sure where to look exactly.</p>
<p>Other relevant details:</p>
<pre><code> Python 2.5
Pylons: 0.9.6.2 (w/ sql_alchemy)
MySQL: 5.0.51
</code></pre>
| 10 | 2008-08-11T19:59:32Z | 46,442 | <p>I think I fixed it. It's turns out I had a simple config error. My ini file read:</p>
<pre><code>sqlalchemy.default.url = [connection string here]
sqlalchemy.pool_recycle = 1800
</code></pre>
<p>The problem is that my <code>environment.py</code> file declared that the engine would only map keys with the prefix: <code>sqlalchemy.default</code> so <code>pool_recycle</code> was ignored.</p>
<p>The solution is to simply change the second line in the ini to:</p>
<pre><code>sqlalchemy.default.pool_recycle = 1800
</code></pre>
| 6 | 2008-09-05T18:07:50Z | [
"python",
"mysql",
"pylons"
] |
How to use Xpath in Python? | 8,692 | <p>What is the library? Is there a full implementation? How is the library used? Where is its website?</p>
| 164 | 2008-08-12T11:28:36Z | 8,699 | <p>The <a href="http://lxml.de/">lxml package</a> supports xpath. It seems to work pretty well, although I've had some trouble with the self:: axis. There's also <a href="http://pypi.python.org/pypi/Amara/1.1.6">Amara</a>, but I haven't used it personally.</p>
| 74 | 2008-08-12T11:40:13Z | [
"python",
"xml",
"dom",
"xpath",
"nodes"
] |
How to use Xpath in Python? | 8,692 | <p>What is the library? Is there a full implementation? How is the library used? Where is its website?</p>
| 164 | 2008-08-12T11:28:36Z | 9,171 | <p><a href="http://pyxml.sourceforge.net" rel="nofollow" title="PyXML">PyXML</a> works well. </p>
<p>You didn't say what platform you're using, however if you're on Ubuntu you can get it with <code>sudo apt-get install python-xml</code>. I'm sure other Linux distros have it as well. </p>
<p>If you're on a Mac, xpath is already installed but not immediately accessible. You can set <code>PY_USE_XMLPLUS</code> in your environment or do it the Python way before you import xml.xpath:</p>
<pre><code>if sys.platform.startswith('darwin'):
os.environ['PY_USE_XMLPLUS'] = '1'
</code></pre>
<p>In the worst case you may have to build it yourself. This package is no longer maintained but still builds fine and works with modern 2.x Pythons. Basic docs are <a href="http://pyxml.sourceforge.net/topics/howto/section-XPath.html" rel="nofollow">here</a>.</p>
| 2 | 2008-08-12T19:34:44Z | [
"python",
"xml",
"dom",
"xpath",
"nodes"
] |
How to use Xpath in Python? | 8,692 | <p>What is the library? Is there a full implementation? How is the library used? Where is its website?</p>
| 164 | 2008-08-12T11:28:36Z | 10,846 | <p>The latest version of <a href="http://effbot.org/zone/element-xpath.htm">elementtree</a> supports XPath pretty well. Not being an XPath expert I can't say for sure if the implementation is full but it has satisfied most of my needs when working in Python. I've also use lxml and PyXML and I find etree nice because it's a standard module.</p>
<p>NOTE: I've since found lxml and for me it's definitely the best XML lib out there for Python. It does XPath nicely as well (though again perhaps not a full implementation).</p>
| 7 | 2008-08-14T09:48:59Z | [
"python",
"xml",
"dom",
"xpath",
"nodes"
] |
How to use Xpath in Python? | 8,692 | <p>What is the library? Is there a full implementation? How is the library used? Where is its website?</p>
| 164 | 2008-08-12T11:28:36Z | 27,974 | <p><a href="http://xmlsoft.org/python.html">libxml2</a> has a number of advantages:</p>
<ol>
<li>Compliance to the <a href="http://www.w3.org/TR/xpath">spec</a></li>
<li>Active development and a community participation </li>
<li>Speed. This is really a python wrapper around a C implementation. </li>
<li>Ubiquity. The libxml2 library is pervasive and thus well tested.</li>
</ol>
<p>Downsides include:</p>
<ol>
<li>Compliance to the <a href="http://www.w3.org/TR/xpath">spec</a>. It's strict. Things like default namespace handling are easier in other libraries.</li>
<li>Use of native code. This can be a pain depending on your how your application is distributed / deployed. RPMs are available that ease some of this pain.</li>
<li>Manual resource handling. Note in the sample below the calls to freeDoc() and xpathFreeContext(). This is not very Pythonic.</li>
</ol>
<p>If you are doing simple path selection, stick with <a href="http://effbot.org/zone/element-xpath.htm">ElementTree</a> ( which is included in Python 2.5 ). If you need full spec compliance or raw speed and can cope with the distribution of native code, go with libxml2.</p>
<p><strong>Sample of libxml2 XPath Use</strong></p>
<hr>
<pre><code>import libxml2
doc = libxml2.parseFile("tst.xml")
ctxt = doc.xpathNewContext()
res = ctxt.xpathEval("//*")
if len(res) != 2:
print "xpath query: wrong node set size"
sys.exit(1)
if res[0].name != "doc" or res[1].name != "foo":
print "xpath query: wrong node set value"
sys.exit(1)
doc.freeDoc()
ctxt.xpathFreeContext()
</code></pre>
<p><strong>Sample of ElementTree XPath Use</strong></p>
<hr>
<pre><code>from elementtree.ElementTree import ElementTree
mydoc = ElementTree(file='tst.xml')
for e in mydoc.findall('/foo/bar'):
print e.get('title').text</code></pre>
<hr>
| 106 | 2008-08-26T13:06:39Z | [
"python",
"xml",
"dom",
"xpath",
"nodes"
] |
How to use Xpath in Python? | 8,692 | <p>What is the library? Is there a full implementation? How is the library used? Where is its website?</p>
| 164 | 2008-08-12T11:28:36Z | 1,732,475 | <p>Use LXML. LXML uses the full power of libxml2 and libxslt, but wraps them in more "Pythonic" bindings than the Python bindings that are native to those libraries. As such, it gets the full XPath 1.0 implementation. Native ElemenTree supports a limited subset of XPath, although it may be good enough for your needs.</p>
| 35 | 2009-11-13T23:11:17Z | [
"python",
"xml",
"dom",
"xpath",
"nodes"
] |
How to use Xpath in Python? | 8,692 | <p>What is the library? Is there a full implementation? How is the library used? Where is its website?</p>
| 164 | 2008-08-12T11:28:36Z | 2,122,709 | <p>Another option is <a href="http://code.google.com/p/py-dom-xpath/">py-dom-xpath</a>, it works seamlessly with minidom and is pure Python so works on appengine.</p>
<pre><code>import xpath
xpath.find('//item', doc)
</code></pre>
| 23 | 2010-01-23T09:30:19Z | [
"python",
"xml",
"dom",
"xpath",
"nodes"
] |
How to use Xpath in Python? | 8,692 | <p>What is the library? Is there a full implementation? How is the library used? Where is its website?</p>
| 164 | 2008-08-12T11:28:36Z | 3,547,727 | <p>Another library is 4Suite: <a href="http://sourceforge.net/projects/foursuite/" rel="nofollow">http://sourceforge.net/projects/foursuite/</a></p>
<p>I do not know how spec-compliant it is. But it has worked very well for my use. It looks abandoned.</p>
| 3 | 2010-08-23T12:57:47Z | [
"python",
"xml",
"dom",
"xpath",
"nodes"
] |
How to use Xpath in Python? | 8,692 | <p>What is the library? Is there a full implementation? How is the library used? Where is its website?</p>
| 164 | 2008-08-12T11:28:36Z | 3,547,741 | <p>You can use:</p>
<p><strong>PyXML</strong>:</p>
<pre><code>from xml.dom.ext.reader import Sax2
from xml import xpath
doc = Sax2.FromXmlFile('foo.xml').documentElement
for url in xpath.Evaluate('//@Url', doc):
print url.value
</code></pre>
<p><strong>libxml2</strong>:</p>
<pre><code>import libxml2
doc = libxml2.parseFile('foo.xml')
for url in doc.xpathEval('//@Url'):
print url.content
</code></pre>
| 9 | 2010-08-23T13:00:01Z | [
"python",
"xml",
"dom",
"xpath",
"nodes"
] |
How to use Xpath in Python? | 8,692 | <p>What is the library? Is there a full implementation? How is the library used? Where is its website?</p>
| 164 | 2008-08-12T11:28:36Z | 13,504,511 | <p>Sounds like an lxml advertisement in here. ;) ElementTree is included in the std library. Under 2.6 and below its xpath is pretty weak, but in <a href="http://docs.python.org/2/library/xml.etree.elementtree.html#xpath-support">2.7 much improved</a>:</p>
<pre class="lang-py prettyprint-override"><code>import xml.etree.ElementTree as ET
root = ET.parse(filename)
result = ''
for elem in root.findall('.//child/grandchild'):
# How to make decisions based on attributes even in 2.6:
if elem.attrib.get('name') == 'foo':
result = elem.text
break
</code></pre>
| 30 | 2012-11-22T01:05:52Z | [
"python",
"xml",
"dom",
"xpath",
"nodes"
] |
How to use Xpath in Python? | 8,692 | <p>What is the library? Is there a full implementation? How is the library used? Where is its website?</p>
| 164 | 2008-08-12T11:28:36Z | 33,716,764 | <p>You can use the simple <code>soupparser</code> from <code>lxml</code></p>
<h2>Example:</h2>
<pre><code>from lxml.html.soupparser import fromstring
tree = fromstring("<a>Find me!</a>")
print tree.xpath("//a/text()")
</code></pre>
| 3 | 2015-11-15T05:31:21Z | [
"python",
"xml",
"dom",
"xpath",
"nodes"
] |
Accessing mp3 Meta-Data with Python | 8,948 | <p>What is the best way to retrieve mp3 metadata in python? I've seen a couple frameworks out there, but I'm unsure as to which would be the best to use.... Any ideas?</p>
| 81 | 2008-08-12T15:16:00Z | 8,972 | <p><a href="http://www.dotfunk.com/projects/mp3/" rel="nofollow">This toolkit</a> may do what you need. I can't say if it's the "best", but really, if it does what you need, that's all that matters, right?</p>
<p>HTH</p>
| 1 | 2008-08-12T15:32:05Z | [
"python",
"mp3",
"metadata"
] |
Accessing mp3 Meta-Data with Python | 8,948 | <p>What is the best way to retrieve mp3 metadata in python? I've seen a couple frameworks out there, but I'm unsure as to which would be the best to use.... Any ideas?</p>
| 81 | 2008-08-12T15:16:00Z | 8,974 | <p>A simple example from the book Dive Into Python works ok for me, <a href="http://www.diveintopython.org/download/diveintopython-examples-5.4.zip" rel="nofollow">this</a> is the download link, the example is fileinfo.py. Don't know if it's the best, but it can do the basic job.</p>
<p>The entire book is available online <a href="http://www.diveintopython.org/" rel="nofollow">here</a>.</p>
| 6 | 2008-08-12T15:37:24Z | [
"python",
"mp3",
"metadata"
] |
Accessing mp3 Meta-Data with Python | 8,948 | <p>What is the best way to retrieve mp3 metadata in python? I've seen a couple frameworks out there, but I'm unsure as to which would be the best to use.... Any ideas?</p>
| 81 | 2008-08-12T15:16:00Z | 8,976 | <p>It can depend on exactly what you want to do in addition to reading the metadata. If it is just simply the bitrate / name etc. that you need, and nothing else, something lightweight is probably best.</p>
<p>If you're manipulating the mp3 past that PyMedia may be suitable.</p>
<p>There are quite a few, whatever you do get, make sure and test it out on plenty of sample media. There are a few different versions of ID3 tags in particular, so make sure it's not too out of date. </p>
<p>Personally I've used this small MP3Info class with luck. It is quite old though.</p>
<p><a href="http://www.omniscia.org/~vivake/python/MP3Info.py" rel="nofollow">http://www.omniscia.org/~vivake/python/MP3Info.py</a></p>
| 1 | 2008-08-12T15:37:59Z | [
"python",
"mp3",
"metadata"
] |
Accessing mp3 Meta-Data with Python | 8,948 | <p>What is the best way to retrieve mp3 metadata in python? I've seen a couple frameworks out there, but I'm unsure as to which would be the best to use.... Any ideas?</p>
| 81 | 2008-08-12T15:16:00Z | 9,358 | <p>What you're after is the <a href="http://id3-py.sourceforge.net/">ID3</a> module. It's very simple and will give you exactly what you need. Just copy the ID3.py file into your site-packages directory and you'll be able to do something like the following:</p>
<pre><code>from ID3 import *
try:
id3info = ID3('file.mp3')
print id3info
# Change the tags
id3info['TITLE'] = "Green Eggs and Ham"
id3info['ARTIST'] = "Dr. Seuss"
for k, v in id3info.items():
print k, ":", v
except InvalidTagError, message:
print "Invalid ID3 tag:", message
</code></pre>
| 11 | 2008-08-13T00:44:26Z | [
"python",
"mp3",
"metadata"
] |
Accessing mp3 Meta-Data with Python | 8,948 | <p>What is the best way to retrieve mp3 metadata in python? I've seen a couple frameworks out there, but I'm unsure as to which would be the best to use.... Any ideas?</p>
| 81 | 2008-08-12T15:16:00Z | 10,845 | <p>I've used <a href="https://bitbucket.org/lazka/mutagen">mutagen</a> to edit tags in media files before. The nice thing about mutagen is that it can handle other formats, such as mp4, FLAC etc. I've written several scripts with a lot of success using this API.</p>
| 25 | 2008-08-14T09:46:21Z | [
"python",
"mp3",
"metadata"
] |
Accessing mp3 Meta-Data with Python | 8,948 | <p>What is the best way to retrieve mp3 metadata in python? I've seen a couple frameworks out there, but I'm unsure as to which would be the best to use.... Any ideas?</p>
| 81 | 2008-08-12T15:16:00Z | 28,711 | <p>If you can use IronPython, there is TagLibSharp. <a href="http://stackoverflow.com/questions/28664/what-is-the-besta-very-good-meta-data-reader-library#28687">It can be used from any .NET language</a>.</p>
| 0 | 2008-08-26T17:48:49Z | [
"python",
"mp3",
"metadata"
] |
Accessing mp3 Meta-Data with Python | 8,948 | <p>What is the best way to retrieve mp3 metadata in python? I've seen a couple frameworks out there, but I'm unsure as to which would be the best to use.... Any ideas?</p>
| 81 | 2008-08-12T15:16:00Z | 102,285 | <p>I used <a href="http://eyed3.nicfit.net/">eyeD3</a> the other day with a lot of success. I found that it could add artwork to the ID3 tag which the other modules I looked at couldn't. You'll have to download the tar and execute <code>python setup.py install</code> from the source folder. </p>
<p>Relevant examples from the website are below.</p>
<p>Reading the contents of an mp3 file containing either v1 or v2 tag info:</p>
<pre><code> import eyeD3
tag = eyeD3.Tag()
tag.link("/some/file.mp3")
print tag.getArtist()
print tag.getAlbum()
print tag.getTitle()
</code></pre>
<p>Read an mp3 file (track length, bitrate, etc.) and access it's tag:</p>
<pre><code>if eyeD3.isMp3File(f):
audioFile = eyeD3.Mp3AudioFile(f)
tag = audioFile.getTag()
</code></pre>
<p>Specific tag versions can be selected:</p>
<pre><code> tag.link("/some/file.mp3", eyeD3.ID3_V2)
tag.link("/some/file.mp3", eyeD3.ID3_V1)
tag.link("/some/file.mp3", eyeD3.ID3_ANY_VERSION) # The default.
</code></pre>
<p>Or you can iterate over the raw frames:</p>
<pre><code> tag = eyeD3.Tag()
tag.link("/some/file.mp3")
for frame in tag.frames:
print frame
</code></pre>
<p>Once a tag is linked to a file it can be modified and saved:</p>
<pre><code> tag.setArtist(u"Cro-Mags")
tag.setAlbum(u"Age of Quarrel")
tag.update()
</code></pre>
<p>If the tag linked in was v2 and you'd like to save it as v1:</p>
<pre><code> tag.update(eyeD3.ID3_V1_1)
</code></pre>
<p>Read in a tag and remove it from the file:</p>
<pre><code> tag.link("/some/file.mp3")
tag.remove()
tag.update()
</code></pre>
<p>Add a new tag:</p>
<pre><code> tag = eyeD3.Tag()
tag.link('/some/file.mp3') # no tag in this file, link returned False
tag.header.setVersion(eyeD3.ID3_V2_3)
tag.setArtist('Fugazi')
tag.update()
</code></pre>
| 75 | 2008-09-19T14:30:41Z | [
"python",
"mp3",
"metadata"
] |
Accessing mp3 Meta-Data with Python | 8,948 | <p>What is the best way to retrieve mp3 metadata in python? I've seen a couple frameworks out there, but I'm unsure as to which would be the best to use.... Any ideas?</p>
| 81 | 2008-08-12T15:16:00Z | 1,936,720 | <p>I looked the above answers and found out that they are not good for my project because of licensing problems with GPL.</p>
<p>And I found out this: <a href="http://pyid3lib.sourceforge.net/" rel="nofollow">PyID3Lib</a>, while that particular <em>python binding</em> release date is old, it uses the <a href="http://id3lib.sourceforge.net/" rel="nofollow">ID3Lib</a>, which itself is up to date.</p>
<p>Notable to mention is that both are <strong>LGPL</strong>, and are good to go.</p>
| 4 | 2009-12-20T19:32:11Z | [
"python",
"mp3",
"metadata"
] |
Accessing mp3 Meta-Data with Python | 8,948 | <p>What is the best way to retrieve mp3 metadata in python? I've seen a couple frameworks out there, but I'm unsure as to which would be the best to use.... Any ideas?</p>
| 81 | 2008-08-12T15:16:00Z | 4,559,380 | <p>check this one out:</p>
<p><a href="https://github.com/Ciantic/songdetails">https://github.com/Ciantic/songdetails</a></p>
<p>Usage example:</p>
<pre><code>>>> import songdetails
>>> song = songdetails.scan("data/song.mp3")
>>> print song.duration
0:03:12
</code></pre>
<p>Saving changes:</p>
<pre><code>>>> import songdetails
>>> song = songdetails.scan("data/commit.mp3")
>>> song.artist = "Great artist"
>>> song.save()
</code></pre>
| 7 | 2010-12-30T01:40:52Z | [
"python",
"mp3",
"metadata"
] |