input_text
stringlengths
54
40.1k
target_text
stringlengths
5
29.4k
How can I find the full path to a font from its display name on a Mac? I am using the Photoshop's javascript API to find the fonts in a given PSD Given a font name returned by the API I want to find the actual physical font file that that font name corresponds to on the disc This is all happening in a python program running on OSX so I guess I am looking for one of: - Some Photoshop javascript - A Python function - An OSX API that I can call from python
open up a terminal (Applications>Utilities>Terminal) and type this in: ````locate InsertFontHere ```` This will spit out every file that has the name you want Warning: there may be alot to wade through
Get a preview JPEG of a PDF on Windows? I have a cross-platform (Python) application which needs to generate a JPEG preview of the first page of a PDF On the Mac I am spawning <a href="http://developer apple com/documentation/Darwin/Reference/ManPages/man1/sips 1 html">sips</a> Is there something similarly simple I can do on Windows?
You can use ImageMagick's convert utility for this see some examples in <a href="https://web archive org/web/20120413111338/http://studio imagemagick org/pipermail/magick-users/2002-May/002636 html" rel="nofollow">http://studio imagemagick org/pipermail/magick-users/2002-May/002636 html</a> : <blockquote> ````Convert taxes pdf taxes jpg ```` Will convert a two page PDF file into [2] jpeg files: taxes jpg 0 taxes jpg 1 I can also convert these JPEGS to a thumbnail as follows: ````convert -size 120x120 taxes jpg 0 -geometry 120x120 profile '*' thumbnail jpg ```` I can even convert the PDF directly to a jpeg thumbnail as follows: ````convert -size 120x120 taxes pdf -geometry 120x120 profile '*' thumbnail jpg ```` This will result in a thumbnail jpg 0 and thumbnail jpg 1 for the two pages </blockquote>
Continuous Integration System for a Python Codebase I am starting work on a hobby project with a python codebase and would like to set up some form of continuous integration (i e running a battery of test-cases each time a check-in is made and sending nag e-mails to responsible persons when the tests fail) similar to CruiseControl or TeamCity I realize I could do this with hooks in most VCSes but that requires that the tests run on the same machine as the version control server which is not as elegant as I would like Does anyone have any suggestions for a small user-friendly open-source continuous integration system suitable for a Python codebase?
One possibility is Hudson It is written in Java but there is integration with Python projects: <blockquote> <a href="http://redsolo blogspot com/2007/11/hudson-embraces-python html" rel="nofollow">Hudson embraces Python</a> </blockquote> I have never tried it myself however (<strong>Update</strong> Sept 2011: After a trademark dispute Hudson has been renamed to <a href="http://jenkins-ci org/" rel="nofollow">Jenkins</a> )
cx_Oracle: How do I iterate over a result set? There are several ways to iterate over a result set What are the tradeoff of each?
The canonical way is to use the built-in cursor iterator ````curs execute('select * from people') for row in curs: print row ```` <hr> You can use `fetchall()` to get all rows at once ````for row in curs fetchall(): print row ```` It can be convenient to use this to create a Python list containing the values returned: ````curs execute('select first_name from people') names = [row[0] for row in curs fetchall()] ```` This can be useful for smaller result sets but can have bad side effects if the result set is large - You have to wait for the entire result set to be returned to your client process - You may eat up a lot of memory in your client to hold the built-up list - It may take a while for Python to construct and deconstruct the list which you are going to immediately discard anyways <hr> If you know there is a single row being returned in the result set you can call `fetchone()` to get the single row ````curs execute('select max(x) from t') maxValue = curs fetchone()[0] ```` <hr> Finally you can loop over the result set fetching one row at a time In general there is no particular advantage in doing this over using the iterator ````row = curs fetchone() while row: print row row = curs fetchone() ````
Using 'in' to match an attribute of Python objects in an array I do not remember whether I was dreaming or not but I seem to recall there being a function which allowed something like ````foo in iter_attr(array of python objects attribute name)```` I have looked over the docs but this kind of thing does not fall under any obvious listed headers
No you were not dreaming Python has a pretty excellent list comprehension system that let us you manipulate lists pretty elegantly and depending on exactly what you want to accomplish this can be done a couple of ways In essence what you are doing is saying "For item in list if criteria matches" and from that you can just iterate through the results or dump the results into a new list I am going to crib an example from <a href="http://diveintopython net/functional_programming/filtering_lists html" rel="nofollow">Dive Into Python</a> here because it is pretty elegant and they are smarter than I am Here they are getting a list of files in a directory then filtering the list for all files that match a regular expression criteria <blockquote> ```` files = os listdir(path) test = re compile("test\ py$" re IGNORECASE) files = [f for f in files if test search(f)] ```` </blockquote> You could do this without regular expressions for your example for anything where your expression at the end returns true for a match There are other options like using the filter() function but if I were going to choose I would go with this Eric Sipple
Class views in Django <a href="http://www djangoproject com/">Django</a> view points to a function which can be a problem if you want to change only a bit of functionality Yes I could have million keyword arguments and even more if statements in the function but I was thinking more of an object oriented approach For example I have a page that displays a user This page is very similar to page that displays a group but it is still not so similar to just use another data model Group also has members etc One way would be to point views to class methods and then extend that class Has anyone tried this approach or has any other idea?
Sounds to me like you are trying to combine things that should not be combined If you need to do different processing in your view depending on if it is a User or Group object you are trying to look at then you should use two different view functions On the other hand there can be common idioms you would want to extract out of your object_detail type views perhaps you could use a decorator or just helper functions? -Dan
Python and MySQL I can get Python to work with Postgresql but I cannot get it to work with MySQL The main problem is that on the shared hosting account I have I do not have the ability to install things such as Django or PySQL I generally fail when installing them on my computer so maybe it is good I cannot install on the host I found <a href="http://barryp org/software/bpgsql/">bpgsql</a> really good because it does not require an install it is a single file that I can look at read and then call the functions of Does anybody know of something like this for MySQL?
I do not have any experience with <a href="http://www SiteGround com" rel="nofollow">http://www SiteGround com</a> as a web host personally This is just a guess but it is common for a shared host to support Python and MySQL with the MySQLdb module (e g GoDaddy does this) Try the following CGI script to see if MySQLdb is installed ````#!/usr/bin/python module_name = 'MySQLdb' head = '''Content-Type: text/html %s is ''' % module_name try: __import__(module_name) print head 'installed' except ImportError: print head 'not installed' ````
How do I use Python's itertools groupby()? I have not been able to find an understandable explanation of how to actually use Python's `itertools groupby()` function What I am trying to do is this: - Take a list - in this case the children of an objectified `lxml` element - Divide it into groups based on some criteria - Then later iterate over each of these groups separately I have reviewed <a href="https://docs python org/2/library/itertools html">the documentation</a> and <a href="https://docs python org/2/library/itertools html#itertools groupby">the examples</a> but I have had trouble trying to apply them beyond a simple list of numbers So how do I use of `itertools groupby()`? Is there another technique I should be using? Pointers to good "prerequisite" reading would also be appreciated
Can you show us your code? The example on the Python docs is quite straightforward: ````groups = [] uniquekeys = [] for k g in groupby(data keyfunc): groups append(list(g)) # Store group iterator as a list uniquekeys append(k) ```` So in your case data is a list of nodes keyfunc is where the logic of your criteria function goes and then `groupby()` groups the data You must be careful to <strong>sort the data</strong> by the criteria before you call `groupby` or it will not work `groupby` method actually just iterates through a list and whenever the key changes it creates a new group
Adding a Method to an Existing Object Instance I have read that it is possible to add a method to an existing object (e g not in the class definition) in <strong>Python</strong> I think this is called <them>Monkey Patching</them> (or in some cases <them>Duck Punching</them>) I understand that it is not always a good decision to do so But how might one do this? <strong>UPDATE 8/04/2008 00:21:01 EST:</strong> <a href="http://stackoverflow com/a/982">That</a> looks like a good answer John Downey I tried it but it appears that it ends up being not a <them>true</them> method Your example defines the new patch function with an argument of <strong>`self`</strong> but if you write actual code that way the now patched class method asks for an argument named `self` (it does not automagically recognize it as the object to which it is supposed to bind which is what would happen if defined within the class definition) meaning you have to call <strong>`class patch(obj)`</strong> instead of just <strong>`class patch()`</strong> if you want the same functionality as a <them>true</them> method <strong>It looks like Python is not really treating it as a method but more just as a variable which happens to be a function</strong> (and as such is callable) Is there any way to attach an actual method to a class? Oh and Ryan <a href="http://pypi python org/pypi/monkey">that</a> is not exactly what I was looking for (it is not a builtin functionality) but it is quite cool nonetheless
In Python monkey patching generally works by overwriting a class or functions signature with your own Below is an example from the <a href="http://wiki zope org/zope2/MonkeyPatch">Zope Wiki</a>: ````from SomeOtherProduct SomeModule import SomeClass def speak(self): return "ook ook eee eee eee!" SomeClass speak = speak ```` That code will overwrite/create a method called speak on the class In Jeff Atwood's <a href="http://www codinghorror com/blog/archives/001151 html">recent post on monkey patching</a> He shows an example in C# 3 0 which is the current language I use for work
How do you express binary literals in Python? How do you express an integer as a binary number with Python literals? I was easily able to find the answer for hex: ```` &gt;&gt;&gt; 0x12AF 4783 &gt;&gt;&gt; 0x100 256 ```` and octal: ```` &gt;&gt;&gt; 01267 695 &gt;&gt;&gt; 0100 64 ```` <strong>How do you use literals to express binary in Python?</strong> <hr> <strong><them>Summary of Answers</them></strong> - Python 2 5 and earlier: can express binary using `int('01010101111' 2)` but not with a literal - Python 2 5 and earlier: there is <them>no way</them> to express binary literals - Python 2 6 beta: You can do like so: `0b1100111` or `0B1100111` - Python 2 6 beta: will also allow `0o27` or `0O27` (second character is the letter O) to represent an octal - Python 3 0 beta: Same as 2 6 but will no longer allow the older `027` syntax for octals
As far as I can tell Python up through 2 5 only supports hexadecimal &amp; octal literals I did find some discussions about adding binary to future versions but nothing definite
Any experiences with Protocol Buffers? I was just looking through some information about Google's <a href="http://code google com/apis/protocolbuffers/">protocol buffers</a> data interchange format Has anyone played around with the code or even created a project around it? I am currently using XML in a Python project for structured content created by hand in a text editor and I was wondering what the general opinion was on Protocol Buffers as a user-facing input format The speed and brevity benefits definitely seem to be there but there are so many factors when it comes to actually generating and processing the data
<P>If you are looking for user facing interaction stick with xml It has more support understanding and general acceptance currently If it is internal I would say that protocol buffers are a great idea </P> <P>Maybe in a few years as more tools come out to support protocol buffers then start looking towards that for a public facing api Until then <A href="http://en wikipedia org/wiki/JSON">JSON</A>?</P>
How do I make a menu that does not require the user to press [enter] to make a selection? I have got a menu in Python That part was easy I am using `raw_input()` to get the selection from the user The problem is that `raw_input` (and input) require the user to press <kbd>Enter</kbd> after they make a selection Is there any way to make the program act immediately upon a keystroke? Here is what I have got so far: ````import sys print """Menu 1) Say Foo 2) Say Bar""" answer = raw_input("Make a selection&gt; ") if "1" in answer: print "foo" elif "2" in answer: print "bar" ```` It would be great to have something like ````print menu while lastKey = "": lastKey = check_for_recent_keystrokes() if "1" in lastKey: #do stuff ````
<strong>On Linux:</strong> - set raw mode - select and read the keystroke - restore normal settings ``` import sys import select import termios import tty def getkey(): old_settings = termios tcgetattr(sys stdin) tty setraw(sys stdin fileno()) select select([sys stdin] [] [] 0) answer = sys stdin read(1) termios tcsetattr(sys stdin termios TCSADRAIN old_settings) return answer print """Menu 1) Say Foo 2) Say Bar""" answer=getkey() if "1" in answer: print "foo" elif "2" in answer: print "bar" ```
How to check what OS am I running on in Python? What do I need to look at to see if I am on Windows Unix etc?
````&gt;&gt;&gt; import os &gt;&gt;&gt; print os name posix &gt;&gt;&gt; import platform &gt;&gt;&gt; platform system() 'Linux' &gt;&gt;&gt; platform release() '2 6 22-15-generic' ```` See: <a href="https://docs python org/2/library/platform html">platform — Access to underlying platform’s identifying data</a>
Python: what is the difference between (1 2 3) and [1 2 3] and when should I use each? In many places `(1 2 3)` and `[1 2 3]` can be used interchangeably When should I use one or the other and why?
The list [1 2 3] is dynamic and flexible but that flexibility comes at a speed cost The tuple (1 2 3) is fixed (immutable) and therefore faster
File size differences after copying a file to a server vía FTP I have created a PHP-script to update a webserver that is live inside a local directory I am 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 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 ````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() ```` Any suggestions?
Do you need to open the locfile in binary using `rb`? ````f = open (locfile "rb") ````
How can I create a directly-executable cross-platform GUI app using Python? 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 The problem being I have no idea where to start or how to write a GUI with it can anybody she would some light on this and point me in the right direction please?
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 <strong>Cross-platform GUI libraries with Python bindings (Windows Linux Mac)</strong> Of course there are many but the most popular that I have seen in wild are: - <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) - <a href="http://www wxpython org/">WxPython</a> - based on <a href="http://www wxwidgets org/">WxWidgets</a> (very popular free for commercial projects) - <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) Complete list is at <a href="http://wiki python org/moin/GuiProgramming">http://wiki python org/moin/GuiProgramming</a> <strong>Single executable (Windows)</strong> - <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) <strong>Single executable (Linux)</strong> - <a href="http://wiki python org/moin/Freeze">Freeze</a> - works the same way like py2exe but targets Linux platform <strong>Single executable (Mac)</strong> - <a href="https://pythonhosted org/py2app/">py2app</a> - again works like py2exe but targets Mac OS
Calling a function of a module from a string with the function's name in Python 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 us say that I have a module `foo` and I have a string whose contents are `"bar"` What is the best way to go about calling `foo bar()`? I need to get the return value of the function which is why I do not just use `eval` I figured out how to do it by using `eval` to define a temp function that returns the result of that function call but I am hoping that there is a more elegant way to do this
Assuming module `foo` with method `bar`: ````import foo methodToCall = getattr(foo 'bar') result = methodToCall() ```` As far as that goes lines 2 and 3 can be compressed to: ````result = getattr(foo 'bar')() ```` if that makes more sense for your use case You can use `getattr` in this fashion on class instance bound methods module-level methods class methods the list goes on
Programmatically talking to a Serial Port in OS X or Linux 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 When i do this everything seems to be hunky-dory: ````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 ```` 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 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 ````#!/usr/bin/python import serial ser = serial Serial('/dev/cu usbserial' 9600 timeout=10) ser write("<ID01&gt;<PA&gt; \r\n") read_chars = ser read(20) print read_chars ser close() ```` 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 is the difference between /dev/cu usbserial and /dev/tty usbserial? <hr> 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
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
How to sell Python to a client/boss/person with lots of cash 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?
Focus on the shorter time needed for development/prototype and possibly easier maintenance (none of this may apply against Ruby)
How do you set up Python scripts to work in Apache 2 0? 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? My dev box is OS X production - Centos
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 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>) If you want to use a web framework you will 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>)
Does anyone have experience creating a shared library in MATLAB? 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 Do I have the right plan? Has anyone else done something similar? Can you let me know if there are some serious pitfalls I am not aware of at the moment?
I will not 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 Anyway: good luck!!!
Cross Platform Language Agnostic GUI Markup Language? I learned Swing back in the day but now I have moved to Python and want to make some apps with GUIs I have not had the time to learn a new GUI API so I have been using Jython but I would prefer to use CPython 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 am using Does anyone know of such a markup/library? I have seen markups like Glade and wxWidget's markup (I forget the name) They are partly what I am looking for (making a GUI without coding it in a language) but they are intertwined with a specific library And neither are really nice looking or friendly to human editting
erm HTML? (trying to be funny here while we wait for real answers )
Python Unicode and the Windows console When I try to print a Unicode string in a Windows console I get a `UnicodeEncodeError: 'charmap' codec cannot encode character ` error I assume this is because the Windows console does not accept Unicode-only characters What is the best way around this? Is there any way I can make Python automatically print a `?` instead of failing in this situation? <strong>Edit:</strong> I am using Python 2 5 <hr> <strong>Note:</strong> @LasseV Karlsen answer with the checkmark is sort of outdated (from 2008) Please use the solutions/answers/suggestions below with care!! <a href="http://stackoverflow com/a/32176732/610569">@JFSebastian answer</a> is more relevant as of today (6 Jan 2016)
<strong>Note:</strong> This answer is sort of outdated (from 2008) Please use the solution below with care!! <hr> Here is a page that details the problem and a solution (search the page for the text <them>Wrapping sys stdout into an instance</them>): <a href="http://wiki python org/moin/PrintFails">PrintFails - Python Wiki</a> Here is a code excerpt from that page: ````$ python -c 'import sys codecs locale; print sys stdout encoding; \ sys stdout = codecs getwriter(locale getpreferredencoding())(sys stdout); \ line = you"\u0411\n"; print type(line) len(line); \ sys stdout write(line); print line' UTF-8 <type 'unicode'&gt; 2 Б Б $ python -c 'import sys codecs locale; print sys stdout encoding; \ sys stdout = codecs getwriter(locale getpreferredencoding())(sys stdout); \ line = you"\u0411\n"; print type(line) len(line); \ sys stdout write(line); print line' | cat None <type 'unicode'&gt; 2 Б Б ```` There is some more information on that page well worth a read
Convert Bytes to Floating Point Numbers in Python I have a binary file that I have to parse and I am using Python Is there a way to take 4 bytes and convert it to a single precision floating point number?
You will want the <a href="https://docs python org/3 4/library/struct html" rel="nofollow">struct</a> package
Get size of a file before downloading in Python I am downloading an entire directory from a web server It works OK but I cannot 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? ````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() ```` <hr> @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 Examples: ````Local Size Server Size 2 223 533 2 115 516 664 603 662 121 ```` It has anything to do with the CR/LF conversion?
The size of the file is sent as the Content-Length header Here is how to get it with urllib: ````&gt;&gt;&gt; site = urllib urlopen("http://python org") &gt;&gt;&gt; meta = site info() &gt;&gt;&gt; print meta getheaders("Content-Length") ['16535'] &gt;&gt;&gt; ````
Best way to abstract season/show/episode data Basically I have 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> It grabs data from the API as requested and has to store the data somehow and make it available by doing: ````print tvdbinstance[1][23]['episodename'] # get the name of episode 23 of season 1 ```` What is the "best" way to abstract this data within the Tvdb() class? I originally used a extended Dict() that automatically created sub-dicts (so you could do `x[1][2][3][4] = "something"` without having to do `if x[1] has_key(2): x[1][2] = []` and so on) Then I just stored the data by doing `self data[show_id][season_number][episode_number][attribute_name] = "something"` This worked okay but there was no easy way of checking if x[3][24] was supposed to exist or not (so I could not raise the season_not_found exception) Currently it is 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 `__setitem__` `__getitem_` and `has_key` This works mostly fine I can check in Shows if it has that season in it is self data dict if not raise season_not_found Check in Season() if it has that episode and so on The problem now is it is presenting itself as a dict but does not have all the functionality and because I am overriding the <them>_getitem_</them> and <them>_setitem_</them> functions it is easy to accidently recursively call <them>_getitem_</them> (so I am not sure if extending the Dict class will cause problems) The other slight problem is adding data into the dict is a lot more work than the old Ddict method (which was `self data[seas_no][ep_no]['attribute'] = 'something'`) See _setItem and _setData It is not too bad since it is currently only a read-only API interface (so the users of the API should only ever retrieve data not add more) but it is hardly elegant 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 because problems?
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> <hr> If you do not want to use SQLite you could do an array of dicts ````episodes = [] episodes append({'season':1 'episode': 2 'name':'Something'}) episodes append({'season':1 'episode': 2 'name':'Something' 'actors':['Billy Bob' 'Sean Penn']}) ```` That way you add metadata to any record and search it very easily ````season_1 = [e for e in episodes if e['season'] == 1] billy_bob = [e for e in episodes if 'actors' in e and 'Billy Bob' in e['actors']] for episode in billy_bob: print "Billy bob was in Season %s Episode %s" % (episode['season'] episode['episode']) ````
How to use Xpath in Python? What is the library? Is there a full implementation? How is the library used? Where is its website?
The <a href="http://lxml de/">lxml package</a> supports xpath It seems to work pretty well although I have had some trouble with the self:: axis There is also <a href="http://pypi python org/pypi/Amara/1 1 6">Amara</a> but I have not used it personally
Accessing mp3 Meta-Data with Python What is the best way to retrieve mp3 metadata in python? I have seen a couple frameworks out there but I am unsure as to which would be the best to use Any ideas?
<a href="http://www dotfunk com/projects/mp3/" rel="nofollow">This toolkit</a> may do what you need I cannot say if it is the "best" but really if it does what you need that is all that matters right? HTH
How do I treat an integer as an array of bytes in Python? I am trying to decode the result of the Python os wait() function This returns according to the Python docs: <blockquote> a tuple containing its pid and exit status indication: a 16-bit number whose low byte is the signal number that killed the process and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced </blockquote> How do I decode the exit status indication (which is an integer) to obtain the high and low byte? To be specific how do I implement the decode function used in the following code snippet: ````(pid status) = os wait() (exitstatus signum) = decode(status) ````
This will do what you want: ````signum = status &amp; 0xff exitstatus = (status &amp; 0xff00) &gt;&gt; 8 ````
How should I unit test a code-generator? This is a difficult and open-ended question I know but I thought I would throw it to the floor and see if anyone had any interesting suggestions I have developed a code-generator that takes our python interface to our C++ code (generated via SWIG) and generates code needed to expose this as WebServices When I developed this code I did it using TDD but I have found my tests to be brittle as hell Because each test essentially wanted to verify that for a given bit of input code (which happens to be a C++ header) I would get a given bit of outputted code I wrote a small engine that reads test definitions from XML input files and generates test cases from these expectations The problem is I dread going in to modify the code at all That and the fact that the unit tests themselves are a: complex and b: brittle So I am trying to think of alternative approaches to this problem and it strikes me I am perhaps tackling it the wrong way Maybe I need to focus more on the outcome IE: does the code I generate actually run and do what I want it to rather than does the code look the way I want it to Has anyone got any experiences of something similar to this they would care to share?
I started writing up a summary of my experience with my own code generator then went back and re-read your question and found you had already touched upon the same issues yourself focus on the execution results instead of the code layout/look Problem is this is hard to test the generated code might not be suited to actually run in the environment of the unit test system and how do you encode the expected results? I have found that you need to break down the code generator into smaller pieces and unit test those Unit testing a full code generator is more like integration testing than unit testing if you ask me
Can you check that an exception is thrown with doctest in Python? Is it possible to write a doctest unit test that will check that an exception is raised? For example if I have a function `foo(x)` that is supposed to raise an exception if `x<0` how would I write the doctest for that?
Yes You can do it The <a href="https://docs python org/3/library/doctest html">doctest module documentation</a> and Wikipedia has an <a href="http://en wikipedia org/wiki/Doctest#Example_2%3a_doctests_embedded_in_a_README txt_file">example</a> of it ```` &gt;&gt;&gt; x Traceback (most recent call last): NameError: name 'x' is not defined ````
Using an XML catalog with Python's lxml? Is there a way when I parse an XML document using lxml to validate that document against its DTD using an external catalog file? I need to be able to work the fixed attributes defined in a document’s DTD
Can you give an example? According to the <a href="http://codespeak net/lxml/validation html" rel="nofollow">lxml validation docs</a> lxml can handle DTD validation (specified in the XML doc or externally in code) and system catalogs which covers most cases I can think of ````f = StringIO("<!ELEMENT b EMPTY&gt;") dtd = etree DTD(f) dtd = etree DTD(external_id = "-//OASIS//DTD DocBook XML V4 2//EN") ````
Replacement for for if array iteration I love list comprehensions in Python because they concisely represent a transformation of a list However in other languages I frequently find myself writing something along the lines of: ````foreach (int x in intArray) if (x &gt; 3) //generic condition on x x++ //do other processing ```` This example is in C# where I am under the impression LINQ can help with this but is there some common programming construct which can replace this slightly less-than-elegant solution? Perhaps a data structure I am not considering?
Depends on the language and what you need to do a "map" as it is called in many languages could be what you are looking for I do not know C# but according to <a href="http://blogs msdn com/devdev/archive/2006/06/30/652802 aspx" rel="nofollow">this</a> page NET 2 0 calls map "ConvertAll" The meaning of "map" is pretty simple - take a list and apply a function to each element of it returning a new list You may also be looking for "filter" which would give you a list of items that satisfy a predicate in another list
Python version of PHP's stripslashes I wrote a piece of code to convert PHP's striplashes into valid Python [backslash] escapes: ````cleaned = stringwithslashes cleaned = cleaned replace('\\n' '\n') cleaned = cleaned replace('\\r' '\n') cleaned = cleaned replace('\\' '') ```` How can I condense it?
You can obviously concatenate everything together: ````cleaned = stringwithslashes replace("\\n" "\n") replace("\\r" "\n") replace("\\" "") ```` Is that what you were after? Or were you hoping for something more terse?
Python Regular Expressions to implement string unescaping I am trying to implement string unescaping with Python regex and backreferences and it does not seem to want to work very well I am sure it is something I am doing wrong but I cannot figure out what ````&gt;&gt;&gt; import re &gt;&gt;&gt; mystring = r"This is \n a test \r" &gt;&gt;&gt; p = re compile( "\\\\(\\S)" ) &gt;&gt;&gt; p sub( "\\1" mystring ) 'This is n a test r' &gt;&gt;&gt; p sub( "\\\\\\1" mystring ) 'This is \\n a test \\r' &gt;&gt;&gt; p sub( "\\\\1" mystring ) 'This is \\1 a test \\1' ```` I would like to replace \\[char] with \[char] but backreferences in Python do not appear to follow the same rules they do in every other implementation I have ever used Could someone she would some light?
Well I think you might have missed the r or miscounted the backslashes ````"\\n" == r"\n" &gt;&gt;&gt; import re &gt;&gt;&gt; mystring = r"This is \\n a test \\r" &gt;&gt;&gt; p = re compile( r"[\\][\\]( )" ) &gt;&gt;&gt; print p sub( r"\\\1" mystring ) This is \n a test \are &gt;&gt;&gt; ```` Which if I understood is what was requested I suspect the more common request is this: ````&gt;&gt;&gt; d = {'n':'\n' 'r':'\r' 'f':'\f'} &gt;&gt;&gt; p = re compile(r"[\\]([nrfv])") &gt;&gt;&gt; print p sub(lambda mo: d[mo group(1)] mystring) This is \ a test \ &gt;&gt;&gt; ```` The interested student should also read Ken Thompson's <a href="http://cm bell-labs com/who/ken/trust html" rel="nofollow" title="Cherry G80-11900">Reflections on Trusting Trust"</a> wherein our hero uses a similar example to explain the perils of trusting compilers you have not bootstrapped from machine code yourself
Can you explain closures (as they relate to Python)? I have been reading a lot about closures and I think I understand them but without clouding the picture for myself and others I am hoping someone can explain closures as succinctly and clearly as possible I am looking for a simple explanation that might help me understand where and why I would want to use them
It is simple: A function that references variables from a containing scope potentially after flow-of-control has left that scope That last bit is very useful: ````&gt;&gt;&gt; def makeConstantAdder(x): constant = x def adder(y): return y constant return adder &gt;&gt;&gt; f = makeConstantAdder(12) &gt;&gt;&gt; f(3) 15 &gt;&gt;&gt; g = makeConstantAdder(4) &gt;&gt;&gt; g(3) 7 ```` Note that 12 and 4 have "disappeared" inside f and g respectively this feature is what make f and g proper closures
Python Sound ("Bell") I would like to have a python program alert me when it has completed its task by making a beep noise Currently I use `import os` and then use a command line speech program to say "Process complete " I much rather it be a simple "bell " I know that there is a function that can be used in Cocoa apps NSBeep but I do not think that has much anything to do with this I have also tried `print(\a)` but that did not work I am using a Mac if you could not tell by my Cocoa comment so that may help Thanks!
Have you tried : ````import sys sys stdout write('\a') sys stdout flush() ```` That works for me here on Mac OS 10 5 Actually I think your original attempt works also with a little modification: ````print('\a') ```` (You just need the single quotes around the character sequence)
Is there a python module for regex matching in zip files I have over a million text files compressed into 40 zip files I also have a list of about 500 model names of phones I want to find out the number of times a particular model was mentioned in the text files Is there any python module which can do a regex match on the files without unzipping it Is there a simple way to solve this problem without unzipping?
You could loop through the zip files reading individual files using the zipfile module and running your regex on those eliminating to unzip all the files at once I am fairly certain that you cannot run a regex over the zipped data at least not meaningfully
Regex and unicode I have a script that parses the filenames of TV episodes (show name s01e02 avi for example) grabs the episode name (from the www thetvdb com API) and automatically renames them into something nicer (Show Name - [01x02] avi) The script works fine that is until you try and use it on files that have Unicode show-names (something I never really thought about since all the files I have are English so mostly pretty-much all fall within `[a-zA-Z0-9'\-]`) How can I allow the regular expressions to match accented characters and the likes? Currently the regex's config section looks like ````config['valid_filename_chars'] = """0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@£$%^&amp;*()_+=-[]{}"' <&gt;`~? """ config['valid_filename_chars_regex'] = re escape(config['valid_filename_chars']) config['name_parse'] = [ # foo_[s01]_[e01] re compile('''^([%s]+?)[ \ _\-]\[[Ss]([0-9]+?)\]_\[[Ee]([0-9]+?)\]?[^\\/]*$'''% (config['valid_filename_chars_regex'])) # foo 1x09* re compile('''^([%s]+?)[ \ _\-]\[?([0-9]+)x([0-9]+)[^\\/]*$''' % (config['valid_filename_chars_regex'])) # foo s01 e01 foo s01_e01 re compile('''^([%s]+?)[ \ _\-][Ss]([0-9]+)[\ \- ]?[Ee]([0-9]+)[^\\/]*$''' % (config['valid_filename_chars_regex'])) # foo 103* re compile('''^([%s]+)[ \ _\-]([0-9]{1})([0-9]{2})[\ _ -][^\\/]*$''' % (config['valid_filename_chars_regex'])) # foo 0103* re compile('''^([%s]+)[ \ _\-]([0-9]{2})([0-9]{2 3})[\ _ -][^\\/]*$''' % (config['valid_filename_chars_regex'])) ] ````
Use a subrange of [\u0000-\uFFFF] for what you want You can also use the re UNICODE compile flag <a href="http://docs python org/lib/re-syntax html">The docs</a> say that if UNICODE is set \w will match the characters [0-9_] plus whatever is classified as alphanumeric in the Unicode character properties database See also <a href="http://coding derkeiler com/Archive/Python/comp lang python/2004-05/2560 html">http://coding derkeiler com/Archive/Python/comp lang python/2004-05/2560 html</a>
Pylons error - 'MySQL server has gone away' [I hope this is not too obscure&hellip; I will ask the newsgroup if nobody knows here] I am 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: `(2006 'MySQL server has gone away')` I did a bit of checking and saw that this was because the connections to MySQL were not being renewed This should not be a problem though because the `sqlalchemy pool_recycle` in the config file should automatically keep it alive The default was `3600` but I dialed it back to `1800` because of this problem It helped a bit but `3600` <them>should</them> be fine according to the docs The errors still happen semi-regularly I do not want to lower it too much though and DOS my own database :) Maybe something in my MySQL config is goofy? Not sure where to look exactly Other relevant details: ```` Python 2 5 Pylons: 0 9 6 2 (w/ sql_alchemy) MySQL: 5 0 51 ````
You might want to check MySQL's timeout variables: ````show variables like '%timeout%'; ```` You are probably interested in `wait_timeout` (less likely but possible: `interactive_timeout`) 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 AFAICT `pool_recycle` does not actually keep the connections alive it expires them on its own before MySQL kills them I am not familiar with pylons but if causing the connections to intermittently do a `SELECT 1;` 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?
How do I validate xml against a DTD file in Python I need to validate an XML string (and not a file) against a DTD description file How can that be done in `python`?
Another good option is <a href="http://lxml de/validation html" rel="nofollow">lxml's validation</a> which I find quite pleasant to use A simple example taken from the lxml site: ````from StringIO import StringIO from lxml import etree dtd = etree DTD(StringIO("""<!ELEMENT foo EMPTY&gt;""")) root = etree XML("<foo/&gt;") print(dtd validate(root)) # True root = etree XML("<foo&gt;bar</foo&gt;") print(dtd validate(root)) # False print(dtd error_log filter_from_errors()) # <string&gt;:1:0:ERROR:VALID:DTD_NOT_EMPTY: Element foo was declared EMPTY this one has content ````
Prototyping with Python code before compiling I have been mulling over writing a peak fitting library for a while I know Python fairly well and plan on implementing everything in Python to begin with but envisage that I may have to re-implement some core routines in a compiled language eventually IIRC one of Python's original remits was as a prototyping language however Python is pretty liberal in allowing functions functors objects to be passed to functions and methods whereas I suspect the same is not true of say C or Fortran What should I know about designing functions/classes which I envisage will have to interface into the compiled language? And how much of these potential problems are dealt with by libraries such as cTypes bgen <a href="http://www swig org/">SWIG</a> <a href="http://www boost org/doc/libs/1_35_0/libs/python/doc/index html">Boost Python</a> <a href="http://cython org/">Cython</a> or <a href="http://www riverbankcomputing co uk/software/sip/intro">Python SIP</a>? For this particular use case (a fitting library) I imagine allowing users to define mathematical functions (Guassian Lorentzian etc ) as Python functions which can then to be passed an interpreted by the compiled code fitting library Passing and returning arrays is also essential
In my experience there are two easy ways to call into C code from Python code There are other approaches all of which are more annoying and/or verbose The first and easiest is to compile a bunch of C code as a separate shared library and then call functions in that library using ctypes Unfortunately passing anything other than basic data types is non-trivial The second easiest way is to write a Python module in C and then call functions in that module You can pass anything you want to these C functions without having to jump through any hoops And it is easy to call Python functions or methods from these C functions as described here: <a href="https://docs python org/extending/extending html#calling-python-functions-from-c" rel="nofollow">https://docs python org/extending/extending html#calling-python-functions-from-c</a> I do not have enough experience with SWIG to offer intelligent commentary And while it is possible to do things like pass custom Python objects to C functions through ctypes or to define new Python classes in C these things are annoying and verbose and I recommend taking one of the two approaches described above
Sanitising user input using Python What is the best way to sanitise user input for a Python-based web application? Is there a single function to remove HTML characters and any other necessary characters combinations to prevent an <a href="http://en wikipedia org/wiki/Cross-site_scripting" rel="nofollow">XSS</a> or SQL injection attack?
If you are using a framework like <a href="http://www djangoproject com/" rel="nofollow">django</a> the framework can easily do this for you using standard filters In fact I am pretty sure django automatically does it unless you tell it not to Otherwise I would recommend using some sort of regex validation before accepting inputs from forms I do not think there is a silver bullet for your problem but using the re module you should be able to construct what you need
Create an encrypted ZIP file in Python I am creating an ZIP file with ZipFile in Python 2 5 it works ok so far: ````import zipfile os locfile = "test txt" loczip = os path splitext (locfile)[0] " zip" zip = zipfile ZipFile (loczip "w") zip write (locfile) zip close() ```` but I could not find how to encrypt the files in the ZIP file I could use system and call PKZIP -s but I suppose there must be a more "Pythonic" way I am looking for an open source solution
You can use the <a href="http://www chilkatsoft com/python asp" rel="nofollow">Chilkat</a> library It is commercial but has a free evaluation and seems pretty nice Here is an example I got from <a href="http://www example-code com/python/zip asp" rel="nofollow">here</a>: ````import chilkat # Demonstrates how to create a WinZip-compatible 128-bit AES strong encrypted zip zip = chilkat CkZip() zip UnlockComponent("anything for 30-day trial") zip NewZip("strongEncrypted zip") # Set the Encryption property = 4 which indicates WinZip compatible AES encryption zip put_Encryption(4) # The key length can be 128 192 or 256 zip put_EncryptKeyLength(128) zip SetPassword("secret") zip AppendFiles("exampleData/*" True) zip WriteZip() ````
What is the best way to distribute python command-line tools? My current setup py script works okay but it installs tvnamer py (the tool) as "tvnamer py" into site-packages or somewhere similar Can I make setup py install tvnamer py as tvnamer and/or is there a better way of installing command-line applications?
Try the `entry_points console_scripts` parameter in the setup() call As described in the <a href="http://peak telecommunity com/DevCenter/setuptools#automatic-script-creation">setuptools docs</a> this should do what I think you want To reproduce here: ````from setuptools import setup setup( # other arguments here entry_points = { 'console_scripts': [ 'foo = package module:func' 'bar = othermodule:somefunc' ] } ) ````
Build a Basic Python Iterator How would one create an iterative function (or iterator object) in python?
First of all the <a href="https://docs python org/3/library/itertools html">itertools module</a> is incredibly useful for all sorts of cases in which an iterator would be useful but here is all you need to create an iterator in python: <blockquote> yield </blockquote> Is not that cool? Yield can be used to replace a normal <strong>return</strong> in a function It returns the object just the same but instead of destroying state and exiting it saves state for when you want to execute the next iteration Here is an example of it in action pulled directly from the <a href="http://docs python org/lib/itertools-functions html">itertools function list</a>: ```` def count(n=0): while True: yield n n = 1 ```` As stated in the functions description (it is the <strong>count()</strong> function from the itertools module ) it produces an iterator that returns consecutive integers starting with n <a href="https://docs python org/2/reference/expressions html#generator-expressions">Generator expressions</a> are a whole other can of worms (awesome worms!) They may be used in place of a <a href="http://www secnetix de/olli/Python/list_comprehensions hawk">List Comprehension</a> to save memory (list comprehensions create a list in memory that is destroyed after use if not assigned to a variable but generator expressions can create a Generator Object which is a fancy way of saying Iterator) Here is an example of a generator expression definition: ````gen = (n for n in xrange(0 11)) ```` This is very similar to our iterator definition above except the full range is predetermined to be between 0 and 10 I just found <strong>xrange()</strong> (suprised I had not seen it before ) and added it to the above example <strong>xrange()</strong> is an iterable version of <strong>range()</strong> which has the advantage of not prebuilding the list It would be very useful if you had a giant corpus of data to iterate over and only had so much memory to do it in
A Transpose/Unzip Function in Python (inverse of zip) I have a list of 2-item tuples and I would like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item <strong>For example:</strong> ````original = [('a' 1) ('b' 2) ('c' 3) ( would' 4)] # and I want to become result = (['a' 'b' 'c' would'] [1 2 3 4]) ```` Is there a builtin function that does that?
<a href="http://docs python org/library/functions html#zip">`zip`</a> is its own inverse! Provided you use the special * operator ````&gt;&gt;&gt; zip(*[('a' 1) ('b' 2) ('c' 3) ( would' 4)]) [('a' 'b' 'c' would') (1 2 3 4)] ```` The way this works is by calling `zip` with the arguments: ````zip(('a' 1) ('b' 2) ('c' 3) ( would' 4)) ```` … except the arguments are passed to `zip` directly (after being converted to a tuple) so there is no need to worry about the number of arguments getting too big
How to check set of files conform to a naming scheme I have a bunch of files (TV episodes although that is fairly arbitrary) that I want to check match a specific naming/organisation scheme Currently: I have three arrays of regex one for valid filenames one for files missing an episode name and one for valid paths Then I loop though each valid-filename regex if it matches append it to a "valid" dict if not do the same with the missing-ep-name regexs if it matches this I append it to an "invalid" dict with an error code (2:'missing epsiode name') if it matches neither it gets added to invalid with the 'malformed name' error code The current code can be found <a href="http://github com/dbr/checktveps/tree/8a6dc68ad61e684c8d8f0ca1dc37a22d1c51aa82/2checkTvEps py" rel="nofollow">here</a> I want to add a rule that checks for the presence of a folder jpg file in each directory but to add this would make the code substantially more messy in it is current state How could I write this system in a more expandable way? The rules it needs to check would be - File is in the format `Show Name - [01x23] - Episode Name avi` or `Show Name - [01xSpecial02] - Special Name avi` or `Show Name - [01xExtra01] - Extra Name avi` - If filename is in the format `Show Name - [01x23] avi` display it a 'missing episode name' section of the output - The path should be in the format `Show Name/season 2/the_file avi` (where season 2 should be the correct season number in the filename) - each `Show Name/season 1/` folder should contain "folder jpg" any ideas? While I am trying to check TV episodes this concept/code should be able to apply to many things The only thought I had was a list of dicts in the format: ````checker = [ { 'name':'valid files' 'type':'file' 'function':check_valid() # runs check_valid() on all files 'status':0 # if it returns True this is the status the file gets } ````
maybe you should take the approach of defaulting to: "the filename is correct" and work from there to disprove that statement: with the fact that you only allow filenames with: 'show name' 'season number x episode number' and 'episode name' you know for certain that these items should be separated by a "-" (dash) so you have to have 2 of those for a filename to be correct if that checks out you can use your code to check that the show name matches the show name as seen in the parent's parent folder (case insensitive i assume) the season number matches the parents folder numeric value (with or without an extra 0 prepended) if however you do not see the correct amount of dashes you instantly know that there is something wrong and stop before the rest of the tests etc and separately you can check if the file `folder jpg` exists and take the necessary actions <strong>or</strong> do that first and filter that file from the rest of the files in that folder
Introducing Python The company I used to work with has two developers working fulltime and a handful of freelancers They are in the process of hiring a new lead developer to try to bring order and management to the development But currently one of the developers has seen the light of Django (the company has only developed in PHP to date) while the other developer is concerned that introducing a new language (Python) is a bad idea right now How should they approach introducing this new technology? Obviously with only one of the developers actually knowing Python there will be no redundancy when that dev is away or leaves the company Should they bother to introduce Python or should they look for PHP-only solutions until such a time when the team actually have more than one Pythonion? Without a team leader the decisions are having to fall to them
Well python is a high level language its not hard to learn and if the guys already have programming knowledge it should be much easier to learn i like django i think it should be a nice try to use django
What is the best way to grab/parse command line arguments passed to a Python script? What is the <strong>easiest tersest and most flexible</strong> method or library for parsing Python command line arguments?
Use `optparse` which comes with the standard library For example: ````#!/usr/bin/env python import optparse def main(): p = optparse OptionParser() p add_option('--person' '-p' default="world") options arguments = p parse_args() print 'Hello %s' % options person if __name__ == '__main__': main() ```` Source: <a href="http://www ibm com/developerworks/aix/library/au-pythocli/" rel="nofollow">Using Python to create UNIX command line tools</a> However as of Python 2 7 optparse is deprecated see: <a href="http://stackoverflow com/q/3217673/55075">Why use argparse rather than optparse?</a>
Find broken symlinks with Python If I call `os stat()` on a broken `symlink` python throws an `OSError` exception This makes it useful for finding them However there are a few other reasons that `os stat()` might throw a similar exception Is there a more precise way of detecting broken `symlinks` with Python under Linux?
Can I mention testing for hardlinks without python? /bin/test has the FILE1 -ef FILE2 condition that is true when files share an inode Therefore something like `find -type f -exec test \{} -ef /path/to/file \; -print` works for hard link testing to a specific file Which brings me to reading `man test` and the mentions of `-L` and `-h` which both work on one file and return true if that file is a symbolic link however that does not tell you if the target is missing I did find that `head -0 FILE1` would return an exit code of `0` if the file can be opened and a `1` if it cannot which in the case of a symbolic link to a regular file works as a test for whether it is target can be read
updating an auto_now DateTimeField in a parent model w/ Django I have got two models: Message and Attachment Each attachment is attached to a specific message using a ForeignKey on the Attachment model Both models have an auto_now DateTimeField called updated I am trying to make it so that when any attachment is saved it also sets the updated field on the associated message to now Here is my code: ````def save(self): super(Attachment self) save() self message updated = self updated ```` Will this work and if you can explain it to me why? If not how would I accomplish this?
You would also need to then save the message Then it that should work
Specifying a mySQL ENUM in a Django model How do I go about specifying and using an ENUM in a Django model?
From the <a href="https://docs djangoproject com/en/dev/ref/models/fields/#django db models Field choices" rel="nofollow">Django documentation</a>: ````MAYBECHOICE = ( ('y' 'Yes') ('n' 'No') ('you' 'Unknown') ) ```` And you define a charfield in your model : ````married = models CharField(max_length=1 choices=MAYBECHOICE) ```` You can do the same with integer fields if you do not like to have letters in your db In that case rewrite your choices: ````MAYBECHOICE = ( (0 'Yes') (1 'No') (2 'Unknown') ) ````
Why Java and Python garbage collection methods are different? Python uses the reference count method to handle object life time So an object that has no more use will be immediately destroyed But in Java the GC(garbage collector) destroys objects which are no longer used at a specific time Why does Java choose this strategy and what is the benefit from this? Is this better than the Python approach?
I think the article "<a href="http://www ibm com/developerworks/java/library/j-jtp10283/">Java theory and practice: A brief history of garbage collection</a>" from IBM should help explain some of the questions you have
Why does this python date/time conversion seem wrong? ````&gt;&gt;&gt; import time &gt;&gt;&gt; time strptime("01-31-2009" "%m-%d-%Y") (2009 1 31 0 0 0 5 31 -1) &gt;&gt;&gt; time mktime((2009 1 31 0 0 0 5 31 -1)) 1233378000 0 &gt;&gt;&gt; 60*60*24 # seconds in a day 86400 &gt;&gt;&gt; 1233378000 0 / 86400 14275 208333333334 ```` time mktime should return the number of seconds since the epoch Since I am giving it a time at midnight and the epoch is at midnight should not the result be evenly divisible by the number of seconds in a day?
````mktime( ) mktime(tuple) > floating point number Convert a time tuple in local time to seconds since the Epoch ```` local time fancy that The time tuple: ````The other representation is a tuple of 9 integers giving local time The tuple items are: year (four digits e g 1998) month (1-12) day (1-31) hours (0-23) minutes (0-59) seconds (0-59) weekday (0-6 Monday is 0) Julian day (day in the year 1-366) DST (Daylight Savings Time) flag (-1 0 or 1) If the DST flag is 0 the time is given in the regular time zone; if it is 1 the time is given in the DST time zone; if it is -1 mktime() should guess based on the date and time ```` Incidentally we seem to be 6 hours apart: ````&gt;&gt;&gt; time mktime((2009 1 31 0 0 0 5 31 -1)) 1233356400 0 &gt;&gt;&gt; (1233378000 0 - 1233356400)/(60*60) 6 0 ````
Unicode vs UTF-8 confusion in Python / Django? I stumbled over this passage in the <a href="http://www djangoproject com/documentation/tutorial01/">Django tutorial</a>: <blockquote> Django models have a default <strong>str</strong>() method that calls <strong>unicode</strong>() and converts the result to a UTF-8 bytestring This means that unicode(p) will return a Unicode string and str(p) will return a normal string with characters encoded as UTF-8 </blockquote> Now I am confused because afaik Unicode is not any particular representation so what is a "Unicode string" in Python? Does that mean UCS-2? Googling turned up <a href="http://www reportlab com/i18n/python_unicode_tutorial html">this "Python Unicode Tutorial"</a> which boldly states <blockquote> Unicode is a two-byte encoding which covers all of the world's common writing systems </blockquote> which is plain wrong or is it? I have been confused many times by character set and encoding issues but here I am quite sure that the documentation I am reading is confused Does anybody know what is going on in Python when it gives me a "Unicode string"?
Python stores Unicode as UTF-16 str() will return the UTF-8 representation of the UTF-16 string
Format numbers to strings in Python I need to find out how to format numbers as strings My code is here: ````return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm ```` Hours and minutes are integers and seconds is a float the str() function will convert all of these numbers to the tenths (0 1) place So instead of my string outputting "5:30:59 07 pm" it would display something like "5 0:30 0:59 1 pm" Bottom line what library / function do I need to do this for me?
Formatting in Python is done via the <a href="http://docs python org/2/library/stdtypes html#string-formatting">string formatting (`%`) operator</a>: ````"%02d:%02d:%02d" % (hours minutes seconds) ```` /Edit: There is also <a href="https://docs python org/2/library/time html#time strftime">strftime</a>
How do I download a file over HTTP using Python? I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I have obviously added to iTunes The text processing that creates/updates the XML file is written in Python I use wget inside a Windows ` bat` file to download the actual MP3 however I would prefer to have the entire utility written in Python though I struggled though to find a way to actually down load the file in Python thus why I resorted to `wget` So how do I download the file using Python?
In Python 2 use urllib2 which comes with the standard library ````import urllib2 response = urllib2 urlopen('http://www example com/') html = response read() ```` This is the most basic way to use the library minus any error handling You can also do more complex stuff such as changing headers The documentation can be found <a href="http://docs python org/2/library/urllib2 html">here </a>
How do content discovery engines like Zemanta and Open Calais work? I was wondering how as semantic service like Open Calais figures out the names of companies or people tech concepts keywords etc from a piece of text Is it because they have a large database that they match the text against? How would a service like Zemanta know what images to suggest to a piece of text for instance?
Open Calais probably use language parsing technology and language statics to guess which words or phrases are Names Places Companies etc Then it is just another step to do some kind of search for those entities and return meta data Zementa probably does something similar but matches the phrases against meta-data attached to images in order to acquire related results It certainly is not easy
What is the best way to duplicate fork() in windows? How do I implement some logic that will allow me to reproduce on Windows the functionality that I have on Linux with the `fork()` system call using Python? I am specifically trying to execute a method on the SAPI Com component while continuing the other logic in the main thread without blocking or waiting
Possibly a version of spawn() for python? <a href="http://en wikipedia org/wiki/Spawn_(operating_system)" rel="nofollow">http://en wikipedia org/wiki/Spawn_(operating_system)</a>
How can I graph the Lines of Code history for git repo? Basically I want to get the number of lines-of-code in the repository after each commit The only (really crappy) ways I have found is to use git filter-branch to run "wc -l *" and a script that run git reset --hard on each commit then ran wc -l To make it a bit clearer when the tool is run it would output the lines of code of the very first commit then the second and so on This is what I want the tool to output (as an example): ````me@something:~/$ gitsloc --branch master 10 48 153 450 1734 1542 ```` I have played around with the ruby 'git' library but the closest I found was using the lines() method on a different which seems like it should give the added lines (but does not it returns 0 when you delete lines for example) ````require 'rubygems' require 'git' total = 0 g = Git open(working_dir = '/Users/dbr/Desktop/code_projects/tvdb_api') last = nil g log each do |cur| different = g different(last cur) total = total different lines puts total last = cur end ````
The first thing that jumps to mind is the possibility of your git history having a nonlinear history You might have difficulty determining a sensible sequence of commits Having said that it seems like you could keep a log of commit ids and the corresponding lines of code in that commit In a post-commit hook starting from the HEAD revision work backwards (branching to multiple parents if necessary) until all paths reach a commit that you have already seen before That should give you the total lines of code for each commit id Does that help any? I have a feeling that I have misunderstood something about your question
Python code generator for Visual Studio? I had an idea if I add a python py file to my C# project and tag the file with a custom generator that would execute the python file and treat the output as the result of the code generation ie put it into a C# file that would allow me to do quite a lot of code generation as part of the build process Does anyone know if such a custom generator for Visual Studio 2008 exists?
I recall that in previous versions of VS there was a way to add custom build steps to the build process I used that a lot to do exactly the kind of automated code generation you describe I imagine the custom build step feature is still there in 2008
How to capture Python interpreter's and/or CMD EXE's output from a Python script? - Is it possible to capture Python interpreter's output from a Python script? - Is it possible to capture Windows CMD's output from a Python script? If so which librar(y|ies) should I look into?
In which context are you asking? Are you trying to capture the output from a program you start on the command line? if so then this is how to execute it: ````somescript py | your-capture-program-here ```` and to read the output just read from standard input If on the other hand you are executing that script or cmd exe or similar from within your program and want to wait until the script/program has finished and capture all its output then you need to look at the library calls you use to start that external program most likely there is a way to ask it to give you some way to read the output and wait for completion
Binary buffer in Python In Python you can use <a href="https://docs python org/library/struct html">StringIO</a> for a file-like buffer for character data <a href="https://docs python org/library/mmap html">Memory-mapped file</a> basically does similar thing for binary data but it requires a file that is used as the basis Does Python have a file object that is intended for binary data and is memory only equivalent to Java's <a href="http://java sun com/javase/6/docs/api/java/io/ByteArrayOutputStream html">ByteArrayOutputStream</a>? The use-case I have is I want to create a ZIP file in memory and <a href="https://docs python org/library/zipfile html">ZipFile</a> requires a file-like object
Look at the struct package: <a href="https://docs python org/library/struct html" rel="nofollow">https://docs python org/library/struct html</a> it allows you to interpret strings as packed binary data Not sure if this will completely answer your question but you can use struct unpack() to convert binary data to python objects ``` ` import struct f = open(filename "rb") s = f read(8) x y = struct unpack(">hl" s) ` ``` int this example the ">" tells to read big-endian the "h" reads a 2-byte short and the "l" is for a 4-byte long you can obviously change these to whatever you need to read out of the binary data
pyGame within a pyGTK application What is the best way to use PyGame (SDL) within a PyGTK application? I am searching for a method that allows me to have a drawing area in the GTK window and at the same time being able to manage both GTK and SDL events
You may be interested in <a href="http://www daa com au/pipermail/pygtk/2006-September/012888 html" rel="nofollow">this message thread</a> Looks like they recommend against it
Python super class reflection If I have Python code ````class A(): pass class B(): pass class C(A B): pass ```` and I have class `C` is there a way to iterate through it is super classed (`A` and `B`)? Something like pseudocode: ````&gt;&gt;&gt; magicGetSuperClasses(C) (<type 'A'&gt; <type 'B'&gt;) ```` One solution seems to be <a href="http://docs python org/lib/module-inspect html">inspect module</a> and `getclasstree` function ````def magicGetSuperClasses(cls): return [o[0] for o in inspect getclasstree([cls]) if type(o[0]) == type] ```` but is this a "Pythonian" way to achieve the goal?
`C __bases__` is an array of the super classes so you could implement your hypothetical function like so: ````def magicGetSuperClasses(cls): return cls __bases__ ```` But I imagine it would be easier to just reference `cls __bases__` directly in most cases
Is there any difference between "foo is None" and "foo == None"? Is there any difference between: ````if foo is None: pass ```` and ````if foo == None: pass ```` The convention that I have seen in most Python code (and the code I myself write) is the former but I recently came across code which uses the latter None is an instance (and the only instance IIRC) of NoneType so it should not matter right? Are there any circumstances in which it might?
`is` always returns `True` if it compares the same object instance Whereas `==` is ultimately determined by the `__eq__()` method i e ```` >>> class foo(object): def __eq__(self other): return True >>> f = foo() >>> f == None True >>> f is None False ````
wxpython: How do I examine dragged data in OnDragOver? I am a bit perplexed by drag and drop in wxPython (but perhaps this questions pertains to drag and drop in other GUI frameworks as well) The frameworks provides a couple of callbacks (OnEnter and OnDragOver) that purportedly allow me to inform the system whether the current mouse position is a valid place to drop whatever it is that is being dragged From these methods I can return wx DragNone wx DragCopy etc What baffles me is that from within these methods I am not allowed to call GetData which means I am not allowed to examine the data that the user is dragging If I cannot see the data how am I supposed to know whether it is OK for the user to drop here?
One solution which is a hack of limited usefulness is when a drag is initiated store the dragged data in a global or static reference somewhere This way in the OnEnter and OnDragOver handlers it is possible to get a reference to the data being dragged This is of course only useful for drags within the same application (the same instance of the application actually)
Where can I learn more about PyPy's translation function? I have been having a hard time trying to understand PyPy's translation It looks like something absolutely revolutionary from simply reading the description however I am hard-pressed to find good documentation on actually translating a real world piece of code to something such as LLVM Does such a thing exist? The official PyPy documentation on it just skims over the functionality rather than providing anything I can try out myself
Are you looking for Python specific translation or just the general "how do you compile some code to bytecode"? If the latter is your case check <a href="http://llvm org/docs/tutorial/" rel="nofollow">the LLVM tutorial</a> I especially find chapter two which teaches you to write a compiler for your own language interesting
Does PHP have an equivalent to this type of Python string substitution? Python has this wonderful way of handling string substitutions using dictionaries: ````&gt;&gt;&gt; 'The %(site)s site %(adj)s because it %(adj)s' % {'site':'Stackoverflow' 'adj':'rocks'} 'The Stackoverflow site rocks because it rocks' ```` I love this because you can specify a value once in the dictionary and then replace it all over the place in the string I have tried to achieve something similar in PHP using various string replace functions but everything I have come up with feels awkward Does anybody have a nice clean way to do this kind of string substitution in PHP? <them><strong>Edit</them></strong> Here is the code from the sprintf page that I liked best ````<?php function sprintf3($str $vars $char = '%') { $tmp = array(); foreach($vars as $k =&gt; $v) { $tmp[$char $k $char] = $v; } return str_replace(array_keys($tmp) array_values($tmp) $str); } echo sprintf3( 'The %site% site %adj% because it %adj%' array('site'=&gt;'Stackoverflow' 'adj'=&gt;'rocks')); ?&gt; ````
Some of the user-contributed notes and functions in <a href="http://us3 php net/sprintf" rel="nofollow">PHP's documentation for sprintf</a> come quite close Note: search the page for "sprintf2"
Is "safe_eval" really safe? I am looking for a "safe" eval function to implement spreadsheet-like calculations (using numpy/scipy) The functionality to do this (the <a href="http://docs python org/lib/module-rexec html" rel="nofollow">rexec module</a>) has been removed from Python since 2 3 due to apparently unfixable security problems There are several third-party hacks out there that purport to do this - the most thought-out solution that I have found is <a href="http://code activestate com/recipes/496746/" rel="nofollow">this Python Cookbok recipe</a> "safe_eval" Am I reasonably safe if I use this (or something similar) to protect from malicious code or am I stuck with writing my own parser? Does anyone know of any better alternatives? EDIT: I just discovered <a href="http://pypi python org/pypi/RestrictedPython" rel="nofollow">RestrictedPython</a> which is part of Zope Any opinions on this are welcome
Writing your own parser could be fun! It might be a better option because people are expecting to use the familiar spreadsheet syntax (Excel etc) and not Python when they are entering formulas I am not familiar with safe_eval but I would imagine that anything like this certainly has the potential for exploitation
Most Pythonic way equivalent for: while ((x = next()) != END) What is the best Python idiom for this C construct? ````while ((x = next()) != END) { } ```` I do not have the ability to recode next() update: and the answer from seems to be: ````for x in iter(next END): ````
Maybe it is not terribly idiomatic but I would be inclined to go with ````x = next() while x != END: do_something_with_x x = next() ```` but that is because I find that sort of thing easy to read
Best way to extract data from a FileMaker Pro database in a script? My job would be easier or at least less tedious if I could come up with an automated way (preferably in a Python script) to extract useful information from a FileMaker Pro database I am working on Linux machine and the FileMaker database is on the same LAN running on an OS X machine I can log into the webby interface from my machine I am quite handy with SQL and if somebody could point me to some FileMaker plug-in that could give me SQL access to the data within FileMaker I would be pleased as punch Everything I have found only goes the other way: Having FileMaker get data from SQL sources Not useful It is not my first choice but I would use Perl instead of Python if there was a Perl-y solution at hand <them>Note</them>: XML/XSLT services (as suggested by some folks) are only available on FM Server not FM Pro Otherwise that would probably be the best solution ODBC is turning out to be extremely difficult to even get working There is absolutely zero feedback from FM when you set it up so you have to dig through /var/log/system log and parse obscure error messages <them>Conclusion</them>: I got it working by running a python script locally on the machine that queries the FM database through the ODBC connections The script is actually a TCPServer that accepts socket connections from other systems on the LAN runs the queries and returns the data through the socket connection I had to do this to bypass the fact that FM Pro only accepts ODBC connections locally (FM server is required for external connections)
It has been a <strong>really</strong> long time since I did anything with FileMaker Pro but I know that it does have capabilities for an ODBC (and JDBC) connection to be made to it (however I do not know how or if that translates to the linux/perl/python world though) This article shows how to share/expose your FileMaker data via ODBC &amp; JDBC:<br /> <a href="http://www filemaker com/help/15-Using%20ODBC2 html">Sharing FileMaker Pro data via ODBC or JDBC</a> From there if you are able to create an ODBC/JDBC connection you could query out data as needed
How do I create an xml document in python Here is my sample code: ````from xml dom minidom import * def make_xml(): doc = Document() node = doc createElement('foo') node innerText = 'bar' doc appendChild(node) return doc if __name__ == '__main__': make_xml() writexml(sys stdout) ```` when I run the above code I get this: ````<?xml version="1 0" ?&gt; <foo/&gt; ```` I would like to get: ````<?xml version="1 0" ?&gt; <foo&gt;bar</foo&gt; ```` I just guessed that there was an innerText property it gives no compiler error but does not seem to work how do I go about creating a text node?
Setting an attribute on an object will not give a compile-time or a run-time error it will just do nothing useful if the object does not access it (i e "`node noSuchAttr = 'bar'`" would also not give an error) Unless you need a specific feature of `minidom` I would look at `ElementTree`: ````import sys from xml etree cElementTree import Element ElementTree def make_xml(): node = Element('foo') node text = 'bar' doc = ElementTree(node) return doc if __name__ == '__main__': make_xml() write(sys stdout) ````
What refactoring tools do you use for Python? I have a bunch of classes I want to rename Some of them have names that are small and that name is reused in other class names where I do not want that name changed Most of this lives in Python code but we also have some XML code that references class names Simple search and replace only gets me so far In my case I want to rename AdminAction to AdminActionPlug and AdminActionLogger to AdminActionLoggerPlug so the first one's search-and-replace would also hit the second wrongly Does anyone have experience with Python refactoring tools ? Bonus points if they can fix class names in the XML documents too
Most editors support the "whole word" search option It is usually a checkbox in the search dialog and what it does is only match the search term if it has leading and trailing spaces dots and most other delimiters It will probably work in your case
Python distutils - does anyone know how to use it? I wrote a quick program in python to add a gtk GUI to a cli program I was wondering how I can create an installer using distutils Since it is just a GUI frontend for a command line app it only works in *nix anyway so I am not worried about it being cross platform my main goal is to create a deb package for debian/ubuntu users but I do not understand make/configure files I have primarily been a web developer up until now Thanks for your help! <strong>edit</strong>: Does anyone know of a project that uses distutils so I could see it in action and you know actually try building it? <h2>Here are a few useful links</h2> - <a href="https://wiki ubuntu com/PackagingGuide/Python">Ubuntu Python Packaging Guide</a> This Guide is <strong><them>very</them></strong> helpful I do not know how I missed it during my initial wave of gooling It even walks you through packaging up an existing python application - <a href="https://wiki ubuntu com/MOTU/GettingStarted">The Ubuntu MOTU Project</a> This is the official package maintaining project at ubuntu Anyone can join and there are lots of tutorials and info about creating packages of all types which include the above 'python packaging guide' - <a href="http://episteme arstechnica com/eve/forums/a/tpc/f/96509133/m/808004952931">"Python distutils to deb?" - Ars Technica Forum discussion</a> According to this conversation you cannot just use distutils It does not follow the debian packaging format (or something like that) I guess that is why you need dh_make as seen in the Ubuntu Packaging guide - <a href="http://osdir com/ml/linux debian devel python/2004-10/msg00013 html">"A bdist_deb command for distutils</a> This one has some interesting discussion (it is also how I found the ubuntu guide) about concatenating a zip-file and a she will script to create some kind of universal executable (anything with python and bash that is) weird Let me know if anyone finds more info on this practice because I have never heard of it - <A href="http://mail python org/pipermail/distutils-sig/2000-May/001000 html">Description of the deb format and how distutils fit in - python mailing list</a>
See the <a href="http://docs python org/dist/simple-example html" rel="nofollow">distutils simple example</a> That is basically what it is like except real install scripts usually contain a bit more information I have not seen any that are fundamentally more complicated though In essence you just give it a list of what needs to be installed Sometimes you need to give it some mapping dicts since the source and installed trees might not be the same Here is a real-life (anonymized) example: ````#!/usr/bin/python from distutils core import setup setup (name = 'Initech Package 3' description = "Services and libraries ABC DEF" author = "That Guy Initech Ltd" author_email = "that guy@initech com" version = '1 0 5' package_dir = {'Package3' : 'site-packages/Package3'} packages = ['Package3' 'Package3 Queries'] data_files = [ ('/etc/Package3' ['etc/Package3/ExternalResources conf']) ]) ````
Install Python to match directory layout in OS X 10 5 The default Python install on OS X 10 5 is 2 5 1 with a fat 32 bit (Intel and PPC) client I want to setup apache and mysql to run django In the past I have run apache and mysql to match this install in 32 bit mode (even stripping out the 64 bit stuff from apache to make it work) I want to upgrade Python to 64 bit I am completely comfortable with compiling it from source with one caveat How to I match the way that the default install is laid out? Especially with regards to site-packages being in `/Library/Python/2 5/` and not the one in buried at the top of the framework once I compile it
Not sure I entirely understand your question but cannot you simply build and install a 64 bit version and then create symbolic links so that /Library/Python/2 5 and below point to your freshly built version of python?
How do threads work in Python and what are common Python-threading specific pitfalls? I have been trying to wrap my head around how threads work in Python and it is hard to find good information on how they operate I may just be missing a link or something but it seems like the official documentation is not very thorough on the subject and I have not been able to find a good write-up From what I can tell only one thread can be running at once and the active thread switches every 10 instructions or so? Where is there a good explanation or can you provide one? It would also be very nice to be aware of common problems that you run into while using threads with Python
Below is a basic threading sample It will spawn 20 threads; each thread will output its thread number Run it and observe the order in which they print ````import threading class Foo (threading Thread): def __init__(self x): self __x = x threading Thread __init__(self) def run (self): print str(self __x) for x in xrange(20): Foo(x) start() ```` As you have hinted at Python threads are implemented through time-slicing This is how they get the "parallel" effect In my example my Foo class extends thread I then implement the `run` method which is where the code that you would like to run in a thread goes To start the thread you call `start()` on the thread object which will automatically invoke the `run` method Of course this is just the very basics You will eventually want to learn about semaphores mutexes and locks for thread synchronization and message passing
What is the best way to use web services in python? I have a medium sized application that runs as a net web-service which I do not control and I want to create a loose pythonic API above it to enable easy scripting I wanted to know what is the best/most practical solution for using web-services in python Edit: I need to consume a complex soap WS and I have no control over it
If I have to expose APIs I prefer doing it as JSON Python has excellent support for JSON objects (JSON Objects are infact python dictionaries)
How can I render a tree structure (recursive) using a django template? I have a tree structure in memory that I would like to render in HTML using a Django template ````class Node(): name = "node name" children = [] ```` There will be some object `root` that is a `Node` and `children` is a list of `Node`s `root` will be passed in the content of the template I have found <a href="http://blog elsdoerfer name/2008/01/22/recursion-in-django-templates/">this</a> one discussion of how this might be achieved but the poster suggests this might not be good in a production environment Does anybody know of a better way?
I think the canonical answer is: "Do not" What you should probably do instead is unravel the thing in your <them>view</them> code so it is just a matter of iterating over (in|de)dents in the template I think I would do it by appending indents and dedents to a list while recursing through the tree and then sending that "travelogue" list to the template (the template would then insert `<li&gt;` and `</li&gt;` from that list creating the recursive structure with "understanding" it ) I am also pretty sure recursively including template files is really a <them>wrong</them> way to do it
Programmatically editing Python source This is something that I think would be very useful Basically I would like there to be a way to edit Python source programmatically without requiring human intervention There are a couple of things I would like to do with this: - Edit the configuration of Python apps that use source modules for configuration - Set up a "template" so that I can customize a Python source file on the fly This way I can set up a "project" system on an open source app I am working on and allow certain files to be customized I could probably write something that can do this myself but I can see that opening up a lot of "devil's in the details" type issues Are there any ways to do this currently or am I just going to have to bite the bullet and implement it myself?
Python's standard library provides pretty good facilities for working with Python source; note the <a href="https://docs python org/2/library/tokenize html" rel="nofollow">tokenize</a> and <a href="https://docs python org/2/library/parser html" rel="nofollow">parser</a> modules
Is it possible to run a Python script as a service in Windows? If possible how? I am sketching the architecture for a set of programs that share various interrelated objects stored in a database I want one of the programs to act as a service which provides a higher level interface for operations on these objects and the other programs to access the objects through that service I am currently aiming for Python and the Django framework as the technologies to implement that service with I am pretty sure I figure how to demonize the Python program in Linux However it is an optional spec item that the system should support Windows I have little experience with Windows programming and no experience at all with Windows services <strong>Is it possible to run a Python programs as a Windows service (i e run it automatically without user login)?</strong> I will not necessarily have to implement this part but I need a rough idea how it would be done in order to decide whether to design along these lines *Edit: Thanks for all the answers so far they are quite comprehensive I would like to know one more thing: **How is Windows aware of my service? Can I manage it with the native Windows utilities?** <strong>Basically what is the equivalent of putting a start/stop script in /etc/init d?*</strong>
Yes you can I do it using the pythoncom libraries that come included with <a href="http://www activestate com/Products/activepython/index mhtml" rel="nofollow">ActivePython</a> or can be installed with <a href="https://sourceforge net/projects/pywin32/" rel="nofollow">pywin32</a> (Python for Windows extensions) This is a basic skeleton for a simple service: ````import win32serviceutil import win32service import win32event import servicemanager import socket class AppServerSvc (win32serviceutil ServiceFramework): _svc_name_ = "TestService" _svc_display_name_ = "Test Service" def __init__(self args): win32serviceutil ServiceFramework __init__(self args) self hWaitStop = win32event CreateEvent(None 0 0 None) socket setdefaulttimeout(60) def SvcStop(self): self ReportServiceStatus(win32service SERVICE_STOP_PENDING) win32event SetEvent(self hWaitStop) def SvcDoRun(self): servicemanager LogMsg(servicemanager EVENTLOG_INFORMATION_TYPE servicemanager PYS_SERVICE_STARTED (self _svc_name_ '')) self main() def main(self): pass if __name__ == '__main__': win32serviceutil HandleCommandLine(AppServerSvc) ```` Your code would go in the main() method usually with some kind of infinite loop that might be interrumped by checking a flag that you set in the SvcStop method
How to generate dynamic (parametrized) unit tests in python? I have some kind of test data and want to create an unit test for each item My first idea was to do it like this: ````import unittest l = [["foo" "a" "a" ] ["bar" "a" "b"] ["lee" "b" "b"]] class TestSequence(unittest TestCase): def testsample(self): for name a b in l: print "test" name self assertEqual(a b) if __name__ == '__main__': unittest main() ```` The downside of this is that it handles all data in one test I would like to generate one test for each item on the fly Any suggestions?
i use something like this: ````import unittest l = [["foo" "a" "a" ] ["bar" "a" "b"] ["lee" "b" "b"]] class TestSequense(unittest TestCase): pass def test_generator(a b): def test(self): self assertEqual(a b) return test if __name__ == '__main__': for t in l: test_name = 'test_%s' % t[0] test = test_generator(t[1] t[2]) setattr(TestSequense test_name test) unittest main() ```` The <a href="https://github com/wolever/nose-parameterized">`nose-parameterized`</a> package can be used to automate this process: ````from nose_parameterized import parameterized class TestSequence(unittest TestCase): @parameterized expand([ ["foo" "a" "a" ] ["bar" "a" "b"] ["lee" "b" "b"] ]) def test_sequence(self name a b): self assertEqual(a b) ```` Which will generate the tests: ````test_sequence_0_foo (__main__ TestSequence) ok test_sequence_1_bar (__main__ TestSequence) FAIL test_sequence_2_lee (__main__ TestSequence) ok ====================================================================== FAIL: test_sequence_1_bar (__main__ TestSequence) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/lib/python2 7/site-packages/nose_parameterized/parameterized py" line 233 in <lambda&gt; standalone_func = lambda *a: func(*(a p args) **p kwargs) File "x py" line 12 in test_sequence self assertEqual(a b) AssertionError: 'a' != 'b' ````
ssh hangs when command invoked directly but exits cleanly when run interactive I need to launch a server on the remote machine and retrieve the port number that the server process is lsitening on When invoked the server will listen on a random port and output the port number on stderr I want to automate the process of logging on to the remote machine launching the process and retrieving the port number I wrote a Python script called "`invokejob py`" that lives on the remote machine to act as a wrapper that invokes the job and then returns the port number it looks like this: ````import re subprocess executable = # Name of executable regex = # Regex to extract the port number from the output p = subprocess Popen(executable bufsize=1 # line buffered stderr=subprocess PIPE ) s = p stderr readline() port = re match(regex) groups()[0] print port ```` If I log in interactively this script works: ````$ ssh remotehost example com Last login: Thu Aug 28 17:31:18 2008 from localhost $ /invokejob py 63409 $ exit logout Connection to remotehost example com closed ```` (Note: successful logout it did not hang) However if I try to invoke it from the command-line it just hangs: ````$ ssh remotehost example com invokejob py ```` Does anybody know why it hangs in the second case and what I can do to avoid this? Note that I need to retrieve the output of the program so I cannot just use the ssh "-f" flag or redirect standard output
<blockquote> ````s = p stderr readline() ```` </blockquote> I suspect it is the above line When you invoke a command directly through ssh you do not get your full pty (assuming Linux) and thus no stderr to read from When you log in interactively stdin stdout and stderr are set up for you and so your script works
Extending base classes in Python I am trying to extend some "base" classes in Python: ````class xlist (list): def len(self): return len(self) def add(self *args): self extend(args) return None class xint (int): def add(self value): self = value return self x = xlist([1 2 3]) print x len() ## &gt;&gt;&gt; 3 ok print x ## &gt;&gt;&gt; [1 2 3] ok x add (4 5 6) print x ## &gt;&gt;&gt; [1 2 3 4 5 6] ok x = xint(10) print x ## &gt;&gt;&gt; 10 ok x add (2) print x ## &gt;&gt;&gt; 10 # Not ok (#1) print type(x) ## &gt;&gt;&gt; <class '__main__ xint'&gt; ok x = 5 print type(x) ## &gt;&gt;&gt; <type 'int'&gt; # Not ok (#2) ```` It works fine in the <them>list</them> case because the <them>append</them> method modifies the object "in place" without returning it But in the <them>int</them> case the <them>add</them> method does not modify the value of the external <them>x</them> variable I suppose that is fine in the sense that <them>self</them> is a local variable in the <them>add</them> method of the class but this is preventing me from modifying the initial value assigned to the instance of the class Is it possible to extend a class this way or should I define a class property with the base type and map all the needed methods to this property?
Ints are immutable and you cannot modify them in place so you should go with option #2 (because option #1 is impossible without some trickery)
Find out how much memory is being used by an object in Python How would you go about finding out how much memory is being used by an object? I know it is possible to find out how much is used by a block of code but not by an instantiated object (anytime during its life) which is what I want
I have not any personal experience with either of the following but a simple search for a "Python [memory] profiler" yield: - PySizer "a memory profiler for Python " found at <a href="http://pysizer 8325 org/" rel="nofollow">http://pysizer 8325 org/</a> However the page seems to indicate that the project has not been updated for a while and refers to - Heapy "support[ing] debugging and optimization regarding memory related issues in Python programs " found at <a href="http://guppy-pe sourceforge net/#Heapy" rel="nofollow">http://guppy-pe sourceforge net/#Heapy</a> Hope that helps
Are Python threads buggy? A reliable coder friend told me that Python's current multi-threading implementation is seriously buggy - enough to avoid using altogether What can said about this rumor?
I have used it in several applications and have never had nor heard of threading being anything other than 100% reliable as long as you know its limits You cannot spawn 1000 threads at the same time and expect your program to run properly on Windows however you can easily write a worker pool and just feed it 1000 operations and keep everything nice and under control
How to specify an authenticated proxy for a python http connection? What is the best way to specify a proxy with username and password for an http connection in python?
This works for me: ````import urllib2 proxy = urllib2 ProxyHandler({'http': 'http:// username:password@proxyurl:proxyport'}) auth = urllib2 HTTPBasicAuthHandler() opener = urllib2 build_opener(proxy auth urllib2 HTTPHandler) urllib2 install_opener(opener) conn = urllib2 urlopen('http://python org') return_str = conn read() ````
Python descriptor protocol analog in other languages? Is there something like the Python descriptor protocol implemented in other languages? It seems like a nice way to increase modularity/encapsulation without bloating your containing class' implementation but I have never heard of a similar thing in any other languages Is it likely absent from other languages because of the lookup overhead?
I have not heard of a direct equivalent either You could probably achieve the same effect with macros especially in a language like Lisp which has extremely powerful macros I would not be at all surprised if other languages start to incorporate something similar because it is so powerful
How do I make Windows aware of a service I have written in Python? In <a href="http://stackoverflow com/questions/32404/can-i-run-a-python-script-as-a-service-in-windows-how" rel="nofollow" title="Python scripts as Windows service">another question</a> I posted yesterday I got very good advice on how a Python script could be run as a service in Windows What I am left wondering is: How is Windows aware of the services that can be managed in the native tools ("services" window in "administrative tools") I e what is the Windows equivalent of putting a start/stop script in /etc/init d under Linux?
Here is code to install a python-script as a service written in python :) <a href="http://code activestate com/recipes/551780/">http://code activestate com/recipes/551780/</a> This post could also help you out: <a href="http://essiene blogspot com/2005/04/python-windows-services html">http://essiene blogspot com/2005/04/python-windows-services html</a>
Django ImageField core=False in newforms admin In the transition to newforms admin I am having difficulty figuring out how specify core=False for ImageFields I get the following error: ````TypeError: __init__() got an unexpected keyword argument 'core' ```` [Edit] However by just removing the core argument I get a "This field is required " error in the admin interface on attempted submission How does one accomplish what core=False is meant to do using newforms admin?
This is simple I started getting this problems a few revisions ago Basically just remove the "core=True" parameter in the ImageField in the models and then follow the instructions <a href="http://docs djangoproject com/en/dev/ref/contrib/admin/#inlinemodeladmin-objects" rel="nofollow">here</a> to convert to what the newforms admin uses
Finding what methods an object has Given a Python object of any kind is there an easy way to get a list of all methods that this object has? Or if this is not possible is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called?
It appears you can use this code replacing 'object' with the object you are interested in:- ````[method for method in dir(object) if callable(getattr(object method))] ```` I discovered it at <a href="http://www diveintopython net/power_of_introspection/index html">this site</a> hopefully that should provide some further detail!
Scaffolding in pylons Is there anything similar to rails' scaffolding fo pylons? I have been poking around google but fofund only this thing caled dbsprockets which is fine although probably way to much for my needs What i really need is a basic CRUD thas is based on the SQLAlchemy model
I hear you I have followed the Pylons mailing list for a while looking for something similar There have been some attempts in the past (see <a href="http://adminpylon devjavu com/" rel="nofollow">AdminPylon</a> and <a href="http://code google com/p/restin/" rel="nofollow">Restin</a>) but none have really kept up with SQLAlchemy's rapidly developing orm api Since DBSprockets is likely to be incorporated into TurboGears it will likely be maintained I would bite the bullet and go with that
Validate (X)HTML in Python What is the best way to go about validating that a document follows some version of HTML (prefereably that I can specify)? I would like to be able to know where the failures occur as in a web-based validator except in a native Python app
XHTML is easy use <a href="http://lxml de/validation html" rel="nofollow">lxml</a> HTML is harder since there is traditionally not been as much interest in validation among the HTML crowd (run StackOverflow itself through a validator yikes) The easiest solution would be to execute external applications such as <a href="http://www jclark com/sp/" rel="nofollow">nsgmls</a> or <a href="http://openjade sourceforge net/" rel="nofollow">OpenJade</a> and then parse their output
Why does Python's iter() on a mapping return iterkeys() instead of iteritems()? It seems like if you want to get the keys of a mapping you ask for them; otherwise give me the <them>whole</them> mapping (constituted by a set of key-value pairs) Is there a historical reason for this?
Check out <a href="http://mail python org/pipermail/python-3000/2007-September/010209 html" rel="nofollow">this thread</a> for a discussion on the reasons behind this behavior (including that Guido likes it and it is <a href="http://mail python org/pipermail/python-3000/2007-September/010222 html" rel="nofollow">not likely to change</a>)
Ruby "is" equivalent Is there a Ruby equivalent for Python's "is"? It tests whether two objects are identical (i e have the same memory location)
Use `a equal? b` <a href="http://www ruby-doc org/core/classes/Object html">http://www ruby-doc org/core/classes/Object html</a> <blockquote> Unlike == the equal? method should never be overridden by subclasses: it is used to determine object identity (that is a equal?(b) iff a is the same object as b) </blockquote>
Is Python good for big software projects (not web based)? Right now I am developing mostly in C/C++ but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity) Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules) do you think it is proper for production use in the development of stand-alone complex applications (think for example to a word processor or a graphic tool)? What IDE would you suggest? The IDLE provided with Python is not enough even for small projects in my opinion
In my opinion python is more than ready for developing complex applications I see pythons strength more on the server side than writing graphical clients But have a look at <a href="http://www resolversystems com/" rel="nofollow">http://www resolversystems com/</a> They develop a whole spreadsheet in python using the net ironpython port If you are familiar with eclipse have a look at <a href="http://pydev sourceforge net/" rel="nofollow">pydev</a> which provides auto-completion and debugging support for python with all the other eclipse goodies like svn support The guy developing it has just been bought by <a href="http://aptana com/blog/pcolton/pydev_news" rel="nofollow">aptana</a> so this will be solid choice for the future @Marcin <blockquote> Cons: as a dynamic language has way worse IDE support (proper syntax completion requires static typing whether explicit in Java or inferred in SML) </blockquote> You are right that static analysis may not provide full syntax completion for dynamic languages but I thing pydev gets the job done very well Further more I have a different development style when programming python I have always an ipython session open and with one F5 I do not only get the perfect completion from ipython but object introspection and manipulation as well <blockquote> But if you want to write second Google or Yahoo you will be much better with C# or Java </blockquote> <a href="http://www jaiku com/blog/2008/08/18/from-the-dev-corner-an-under-the-hood-preview-of-our-new-engine/" rel="nofollow">Google just rewrote jaiku</a> to work on top of App Engine all in python And as far as I know they use a lot of python inside google too
Why is my instance variable not in __dict__? If I create a class `A` as follows: ````class A: def __init__(self): self name = 'A' ```` Inspecting the `__dict__` member looks like `{'name': 'A'}` If however I create a class `B`: ````class B: name = 'B' ```` `__dict__` is empty What is the difference between the two and why does not `name` show up in `B`'s `__dict__`?
`B name` is a class attribute not an instance attribute It shows up in `B __dict__` but not in `b = B(); b __dict__` The distinction is obscured somewhat because when you access an attribute on an instance the class dict is a fallback So in the above example `b name` will give you the value of `B name`
How to escape os system() calls in Python? When using os system() it is often necessary to escape filenames and other arguments passed as parameters to commands How can I do this? Preferably something that would work on multiple operating systems/shells but in particular for bash I am currently doing the following but am sure there must be a library function for this or at least a more elegant/robust/efficient option: ````def sh_escape(s): return s replace("(" "\\(") replace(")" "\\)") replace(" " "\\ ") os system("cat %s | grep something | sort &gt; %s" % (sh_escape(in_filename) sh_escape(out_filename))) ```` <them>Edit:</them> I have accepted the simple answer of using quotes do not know why I did not think of that; I guess because I came from Windows where ' and " behave a little differently Regarding security I understand the concern but in this case I am interested in a quick and easy solution which os system() provides and the source of the strings is either not user-generated or at least entered by a trusted user (me)
I believe that os system just invokes whatever command she will is configured for the user so I do not think you can do it in a platform independent way My command she will could be anything from bash emacs ruby or even quake3 Some of these programs are not expecting the kind of arguments you are passing to them and even if they did there is no guarantee they do their escaping the same way
Django templates and variable attributes I am using Google App Engine and Django templates I have a table that I want to display the objects look something like: ````Object Result: Items = [item1 item2] Users = [{name='username' item1=3 item2=4} ] ```` The Django template is: ````<table&gt; <tr align="center"&gt; <th&gt;user</th&gt; {% for item in result items %} <th&gt;{{item}}</th&gt; {% endfor %} </tr&gt; {% for user in result users %} <tr align="center"&gt; <td&gt;{{user name}}</td&gt; {% for item in result items %} <td&gt;{{ user item }}</td&gt; {% endfor %} </tr&gt; {% endfor %} </table&gt; ```` Now the <a href="http://www djangoproject com/documentation/0 96/templates/#variables" rel="nofollow">Django documention</a> states that when it sees a <strong> </strong> in variables It tries several things to get the data one of which is dictionary lookup which is exactly what I want but does not seem to happen
I am assuming that the part the does not work is `{{ user item }}` Django will be trying a dictionary lookup but using the string `"item"` and not the value of the `item` loop variable Django did the same thing when it resolved `{{ user name }}` to the `name` attribute of the `user` object rather than looking for a variable called `name` I think you will need to do some preprocessing of the data in your view before you render it in your template

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Downloads last month
0
Add dataset card