input_text
stringlengths
54
40.1k
target_text
stringlengths
5
29.4k
How can I consume a WSDL (SOAP) web service in Python? I want to use a WSDL SOAP based web service in Python I have looked at the <a href="http://diveintopython net/soap_web_services/">Dive Into Python</a> code but the SOAPpy module does not work under Python 2 5 I have tried using <a href="https://fedorahosted org/suds">suds</a> which works partly but breaks with certain types (suds TypeNotFound: Type not found: 'item') I have also looked at <a href="http://trac optio webfactional com/wiki">Client</a> but this does not appear to support WSDL And I have looked at <a href="http://pywebsvcs sourceforge net/zsi html">ZSI</a> but it looks very complex Does anyone have any sample code for it? The WSDL is <a href="https://ws pingdom com/soap/PingdomAPI wsdl">https://ws pingdom com/soap/PingdomAPI wsdl</a> and works fine with the PHP 5 SOAP client
Right now (as of 2008) all the SOAP libraries available for Python suck I recommend avoiding SOAP if possible The last time we where forced to use a SOAP web service from Python we wrote a wrapper in C# that handled the SOAP on one side and spoke COM out the other
Which is more pythonic factory as a function in a module or as a method on the class it creates? I have some Python code that creates a Calendar object based on parsed VEvent objects from and iCalendar file The calendar object just has a method that adds events as they get parsed Now I want to create a factory function that creates a calendar from a file object path or URL I have been using the <a href="http://codespeak net/icalendar/" rel="nofollow">iCalendar python module</a> which implements a factory function as a class method directly on the Class that it returns an instance of: ````cal = icalendar Calendar from_string(data) ```` From what little I know about Java this is a common pattern in Java code though I seem to find more references to a factory method being on a different class than the class you actually want to instantiate instances from The question is is this also considered Pythonic ? Or is it considered more pythonic to just create a module-level method as the factory function ?
It is pythonic not to think about esoteric difference in some pattern you read somewhere and now want to use everywhere like the factory pattern Most of the time you would think of a @staticmethod as a solution it is probably better to use a module function except when you stuff multiple classes in one module and each has a different implementation of the same interface then it is better to use a @staticmethod Ultimately weather you create your instances by a @staticmethod or by module function makes little difference I would probably use the initializer ( __init__ ) of a class because one of the more accepted "patterns" in python is that the factory for a class is the class initialization
How do I configure the ip address with CherryPy? I am using python and CherryPy to create a simple internal website that about 2 people use I use the built in webserver with CherryPy quickstart and never messed with the config files I recently changed machines so I installed the latest Python and cherrypy and when I run the site I can access it from localhost:8080 but not through the IP or the windows machine name It could be a machine configuration difference or a newer version of CherryPy or Python Any ideas how I can bind to the correct IP address? Edit: to make it clear I currently do not have a config file at all
That depends on how you are running the cherrypy init If using cherrypy 3 1 syntax that wold do it: ````cherrypy server socket_host = 'www machinename com' cherrypy engine start() cherrypy engine block() ```` Of course you can have something more fancy like subclassing the server class or using config files Those uses are covered in <a href="http://www cherrypy org/wiki/ServerAPI">the documentation</a> But that should be enough If not just tell us what you are doing and cherrypy version and I will edit this answer
Convert mysql timestamp to epoch time in python Convert mysql timestamp to epoch time in python - is there an easy way to do this?
Why not let MySQL do the hard work? select unix_timestamp(fieldname) from tablename;
What would be the simplest way to daemonize a python script in Linux? What would be the simplest way to daemonize a python script in Linux ? I need that this works with every flavor of Linux so it should only use python based tools
<a href="http://en wikipedia org/wiki/Nohup" rel="nofollow">nohup</a> <a href="http://code activestate com/recipes/278731/" rel="nofollow">Creating a daemon the Python way</a>
Using Pylint with Django I would very much like to integrate <a href="http://www logilab org/857">pylint</a> into the build process for my python projects but I have run into one show-stopper: One of the error types that I find extremely useful--:`E1101: *%s %r has no %r member*`--constantly reports errors when using common django fields for example: ````E1101:125:get_user_tags: Class 'Tag' has no 'objects' member ```` which is caused by this code: ````def get_user_tags(username): """ Gets all the tags that username has used Returns a query set """ return Tag objects filter( ## This line triggers the error tagownership__users__username__exact=username) distinct() # Here is the Tag class models Model is provided by Django: class Tag(models Model): """ Model for user-defined strings that help categorize Events on on a per-user basis """ name = models CharField(max_length=500 null=False unique=True) def __unicode__(self): return self name ```` How can I tune Pylint to properly take fields such as objects into account? (I have also looked into the Django source and I have been unable to find the implementation of `objects` so I suspect it is not "just" a class field On the other hand I am fairly new to python so I may very well have overlooked something ) <strong>Edit:</strong> The only way I have found to tell pylint to not warn about these warnings is by blocking all errors of the type (E1101) which is not an acceptable solution since that is (in my opinion) an extremely useful error If there is another way without augmenting the pylint source please point me to specifics :) See <a href="http://creswick github io/blog/2008/09/05/wrestling-python/">here</a> for a summary of the problems I have had with `pychecker` and `pyflakes` -- they have proven to be far to unstable for general use (In pychecker's case the crashes originated in the pychecker code -- not source it was loading/invoking )
Because of how pylint works (it examines the source itself without letting Python actually execute it) it is very hard for pylint to figure out how metaclasses and complex baseclasses actually affect a class and its instances The 'pychecker' tool is a bit better in this regard because it <them>does</them> actually let Python execute the code; it imports the modules and examines the resulting objects However that approach has other problems because it does actually let Python execute the code :-) You could extend pylint to teach it about the magic Django uses or to make it understand metaclasses or complex baseclasses better or to just ignore such cases after detecting one or more features it does not quite understand I do not think it would be particularly easy You can also just tell pylint to not warn about these things through special comments in the source command-line options or a pylintrc file
What is the simplest way to offer/consume web services in jython? I have an application for Tomcat which needs to offer/consume web services Since Java web services are a nightmare (xml code generation etc ) compared with what is possible in Python I would like to learn from your experience using jython instead of java for offerring/consuming web services What I have done so far involves adapting <a href="http://pywebsvcs sourceforge net/">http://pywebsvcs sourceforge net/</a> to <a href="http://www jython org">Jython</a> I still get errors (namespaces types and so) although some of it is succesful for the simplest services
<a href="http://www jython org/docs/api/org/python/util/PyServlet html" rel="nofollow">PyServlet</a> helps you configure Tomcat to serve up Jython scripts from a URL You could use this is a "REST-like" way to do some basic web services without much effort (It is also described <a href="http://www informit com/articles/article aspx?p=26865&amp;seqNum=6" rel="nofollow">here</a> ) We used a similar home grown framework to provide a variety of data services in a large multiple web application very successfully
How can I search a word in a Word 2007 docx file? I would like to search a Word 2007 file ( docx) for a text string e g "some special phrase" that could/would be found from a search within Word Is there a way from Python to see the text? I have no interest in formatting - I just want to classify documents as having or not having "some special phrase"
A docx is just a zip archive with lots of files inside Maybe you can look at some of the contents of those files? Other than that you probably have to find a lib that understands the word format so that you can filter out things you are not interested in A second choice would be to interop with word and do the search through it
python regular expression to split paragraphs How would one write a regular expression to use in python to split paragraphs? A paragraph is defined by 2 linebreaks (\n) But one can have any ammount of spaces/tabs together with the line breaks and it still should be considered as a paragraph I am using python so the solution can use python's <a href="http://docs python org/lib/re-syntax html" rel="nofollow" title="Python re syntax">regular expression syntax</a> which is extended (can make use of `(?P )` stuff) <h1>Examples:</h1> ````the_str = 'paragraph1\n\nparagraph2' # splitting should yield ['paragraph1' 'paragraph2'] the_str = 'p1\n\t\np2\t\n\tstill p2\t \n \n\tp3' # should yield ['p1' 'p2\t\n\tstill p2' 'p3'] the_str = 'p1\n\n\n\tp2' # should yield ['p1' '\n\tp2'] ```` The best I could come with is: `r'[ \t\r\f\v]*\n[ \t\r\f\v]*\n[ \t\r\f\v]*'` but that is ugly Anything better? <strong>EDIT</strong>: <h1>Suggestions rejected:</h1> `r'\s*?\n\s*?\n\s*?'` -> That would make example 2 and 3 fail since `\s` includes `\n` so it would allow paragraph breaks with more than 2 `\n`s
Almost the same but using non-greedy quantifiers and taking advantage of the whitespace sequence ````\s*?\n\s*?\n\s*? ````
How do you create an osx application/dmg from a python package? I want to create a mac osx application from python package and then put it in a disk image Because I load some resources out of the package the package should <strong>not</strong> reside in a zip file The resulting disk image should display the background picture to "drag here -> applications" for installation
I do not know the correct way to do it but this manual method is the approach I have used for simple scripts which seems to have preformed suitably I will assume that whatever directory I am in the Python files for my program are in the relative `src/` directory and that the file I want to execute (which has the proper shebang and execute permissions) is named `main py` ``` $ mkdir -p MyApplication app/Contents/MacOS $ mv src/* MyApplication app/Contents/MacOS $ cd MyApplication app/Contents/MacOS $ mv main py MyApplication ``` At this point we have an application bundle which as far as I know should work on any Mac OS system with Python installed (which I think it has by default) It does not have an icon or anything that requires adding some more metadata to the package which is unnecessary for my purposes and I am not familiar with To create the drag-and-drop installer is quite simple Use Disk Utility to create a New Disk Image of approximately the size you require to store your application Open it up copy your application and an alias of `/Applications` to the drive then use View Options to position them as you want The drag-and-drop message is just a background of the disk image which you can also specify in View Options I have not done it before but I would assume that after you whip up an image in your editor of choice you could copy it over set it as the background and then use `chflags hidden` to prevent it from cluttering up your nice window I know these are not the clearest simplest or most detailed instructions out there but I hope somebody may find them useful
Best practices for manipulating database result sets in Python? I am writing a simple Python web application that consists of several pages of business data formatted for the iPhone I am comfortable programming Python but I am not very familiar with Python "idiom " especially regarding classes and objects Python's object oriented design differs somewhat from other languages I have worked with So even though my application is working I am curious whether there is a better way to accomplish my goals Specifics: How does one typically implement the request-transform-render database workflow in Python? Currently I am using pyodbc to fetch data copying the results into attributes on an object performing some calculations and merges using a list of these objects then rendering the output from the list of objects (Sample code below SQL queries redacted ) Is this sane? Is there a better way? Are there any specific "gotchas" I have stumbled into in my relative ignorance of Python? I am particularly concerned about how I have implemented the list of rows using the empty "Record" class ````class Record(object): pass def calculate_pnl(records node_prices): for record in records: try: # fill RT and DA prices from the hash retrieved above if hasattr(record 'sink') and record sink: record da = node_prices[record sink][0] - node_prices[record id][0] record rt = node_prices[record sink][1] - node_prices[record id][1] else: record da = node_prices[record id][0] record rt = node_prices[record id][1] # calculate dependent values: RT-DA and PNL record rtda = record rt - record da record pnl = record rtda * record mw except: print sys exc_info() def map_rows(cursor mappings callback=None): records = [] for row in cursor: record = Record() for field attr in mappings iteritems(): setattr(record attr getattr(row field None)) if not callback or callback(record): records append(record) return records def get_positions(cursor): # get the latest position time cursor execute("SELECT latest data time") time = cursor fetchone() time hour = eelib util get_hour_ending(time) # fetch the current positions cursor execute("SELECT stuff FROM atable" (hour)) # read the rows nodes = {} def record_callback(record): if abs(record mw) &gt; 0: if record id: nodes[record id] = None return True else: return False records = util map_rows(cursor { 'id': 'id' 'name': 'name' 'mw': 'mw' } record_callback) # query prices for node_id in nodes: # RT price row = cursor execute("SELECT price WHERE ? ? ?" (node_id time time)) fetchone() rt5 = row lmp if row else None # DA price row = cursor execute("SELECT price WHERE ? ? ?" (node_id hour hour)) fetchone() da = row da_lmp if row else None # update the hash value nodes[node_id] = (da rt5) # calculate the position pricing calculate_pnl(records nodes) # sort records sort(key=lambda r: r name) # return the records return records ````
Have you considered using an ORM? <a href="http://www sqlalchemy org/features html" rel="nofollow" title="SQL Alchemy features">SQLAlchemy</a> is pretty good and <a href="http://elixir ematia de/trac/wiki" rel="nofollow" title="Elixir Wiki">Elixir</a> makes it beautiful It can really reduce the ammount of boilerplate code needed to deal with databases Also a lot of the <them>gotchas</them> mentioned have already shown up and the SQLAlchemy developers dealt with them
How to Retrieve name of current Windows User (AD or local) using Python? How can I retrieve the name of the currently logged in user using a python script? The function should work regardless of whether it is a domain/ad user or a local user
Try this: ````import os; print os environ get( "USERNAME" ) ```` That should do the job
What is the scope for imported classes in python? Please excuse the vague title If anyone has a suggestion please let me know! Also please retag with more appropriate tags! <strong>The Problem</strong> I want to have an instance of an imported class be able to view things in the scope (globals locals) of the importer Since I am not sure of the exact mechanism at work here I can describe it much better with snippets than words ````## File 1 def f1(): print "go f1!" class C1(object): def do_eval(self x): # maybe this should be do_evil given what happens print "evaling" eval(x) eval(x globals() locals()) ```` Then run this code from an iteractive session there there will be lots of `NameErrors` ````## interactive class C2(object): def do_eval(self x): # maybe this should be do_evil given what happens print "evaling" eval(x) eval(x globals() locals()) def f2(): print "go f2!" from file1 import C1 import file1 C1() do_eval('file1 f1()') C1() do_eval('f1()') C1() do_eval('f2()') file1 C1() do_eval('file1 f1()') file1 C1() do_eval('f1()') file1 C1() do_eval('f2()') C2() do_eval('f2()') C2() do_eval('file1 f1()') C2() do_eval('f1()') ```` Is there a common idiom / pattern for this sort of task? Am I barking up the wrong tree entirely?
Functions are always executed in the scope they are defined in as are methods and class bodies They are never executed in another scope Because importing is just another assignment statement and everything in Python is a reference the functions classes and modules do not even know where they are imported to You can do two things: explicitly pass the 'environment' you want them to use or use stack hackery to access their caller's namespace The former is vastly preferred over the latter as it is not as implementation-dependent and fragile as the latter You may wish to look at the string Template class which tries to do something similar
Python and POST data In PHP I simply write: ````$bob = $_POST['bob']; ```` How do I do the same in Python? And yes I do normally check that it exists etc I am just stripping it down specifically to the functionality I am after <hr> Edit: I am not using a framework
The simplest method is the 'cgi' module: ````import cgi data = cgi FieldStorage() data['bob'] ```` But the context you are executing in (frameworks you are using WSGI or even (heaven forbid) mod_python) may have different more efficient or more direct methods of access
How do I get a decimal value when using the division operator in Python? For example the standard division symbol '/' rounds to zero: ````&gt;&gt;&gt; 4 / 100 0 ```` However I want it to return 0 04 What do I use?
Try 4 0/100
How to update a Tix ComboBox's text? I have a Tix ComboBox with an editable text field How do I force the variable holding the value for the text to update? Let me give a more concrete explanation I have a combo box and a button When I click the button it pops up a message box with the value of the combo box Let us say the combo box text field currently has the value "thing1" If I type "new" into the box and then click on the button with my mouse it will pops up the message "thing1" If I type "new" in the box and then tab focus away from the combo box and then click the button the pop up message says "new" Ho do I force the combo box to update it is value to new without requiring that I tab away from the combo box? I have included sample code ````import Tix import tkMessageBox class App(object): def __init__(self window): window winfo_toplevel() wm_title("test") self window = window self combo = Tix ComboBox(window) self combo insert(Tix END 'thing1') self combo insert(Tix END 'thing2') self combo entry['state'] = "normal" self combo['editable'] = True self combo pack() button = Tix Button(window) button['text'] = "Go" button['command'] = self go button pack() def go(self): tkMessageBox showinfo('info' self combo['value']) if __name__ == '__main__': root = Tix Tk() App(root) root mainloop() ````
woo! solved it on my own Use ````self combo['selection'] ```` instead of ````self combo['value'] ````
How do I use timezones with a datetime object in python? How do I properly represent a different timezone in my timezone? The below example only works because I know that EDT is one hour ahead of me so I can uncomment the subtraction of myTimeZone() ````import datetime re from datetime import tzinfo class myTimeZone(tzinfo): """docstring for myTimeZone""" def utfoffset(self dt): return timedelta(hours=1) def myDateHandler(aDateString): """you'Sat 6 Sep 2008 21:16:33 EDT'""" _my_date_pattern = re compile(r'\w+\ \s+(\d+)\s+(\w+)\s+(\d+)\s+(\d+)\:(\d+)\:(\d+)') day month year hour minute second = _my_date_pattern search(aDateString) groups() month = [ 'JAN' 'FEB' 'MAR' 'APR' 'MAY' 'JUN' 'JUL' 'AUG' 'SEP' 'OCT' 'NOV' 'DEC' ] index(month upper()) 1 dt = datetime datetime( int(year) int(month) int(day) int(hour) int(minute) int(second) ) # dt = dt - datetime timedelta(hours=1) # dt = dt - dt tzinfo utfoffset(myTimeZone()) return (dt year dt month dt day dt hour dt minute dt second 0 0 0) def main(): print myDateHandler("Sat 6 Sep 2008 21:16:33 EDT") if __name__ == '__main__': main() ````
The Python standard library does not contain timezone information because unfortunately timezone data changes a lot faster than Python You need a third-party module for this; the usual choice is <a href="http://pytz sourceforge net">pytz</a>
How do I use owfs to read an iButton temperature logger? I have installed <a href="http://www owfs org/" rel="nofollow">`owfs`</a> and am trying to read the data off a <a href="http://www maxim-ic com/quick_view2 cfm/qv_pk/4088" rel="nofollow">iButton temperature logger</a> `owfs` let us me mount the iButton as a fuse filesystem and I can see all the data I am having trouble figuring out what is the best way to access the data though I can get individual readings by `cat`ting the files e g `cat onewire/{deviceid}/log/temperature 1` but the `onewire/{deviceid}/log/temperature ALL` file is "broken" (possible too large as `histogram/temperature ALL` work fine) A python script to read all files seems to work but takes a very long time Is there a better way to do it? Does anyone have any examples? I am using Ubuntu 8 04 and could not get the java "one wire viewer" app to run <strong>Update</strong>: Using <a href="http://owfs sourceforge net/owpython html" rel="nofollow">`owpython`</a> (installed with owfs) I can get the current temperature but cannot figure out how to get access to the recorded logs: ````&gt;&gt;&gt; import ow &gt;&gt;&gt; ow init("you") # initialize USB &gt;&gt;&gt; ow Sensor("/") sensorList() [Sensor("/81 7FD921000000") Sensor("/21 C4B912000000")] &gt;&gt;&gt; x = ow Sensor("/21 C4B912000000") &gt;&gt;&gt; print x type x temperature DS1921 22 ```` `x log` gives an `AttributeError`
I do not think there is a clever way owpython does not support that telling from the API documentation I guess `/proc` is your safest bet Maybe have a look at the source of the owpython module and check if you can find out how it works
What is the Name of the Python Module that Formats arbitrary Text to nicely looking HTML? A while ago I came across a Python library that formats regular text to HTML similar to Markdown reStructuredText and Textile just that it had no syntax at all It detected indentatations quotes links and newlines/paragraphs only Unfortunately I lost the name of the library and was unable to Google it Anyone any ideas? <strong>Edit:</strong> reStructuredText aka rst == docutils That is not what I am looking for :)
<a href="http://sphinx pocoo org/" rel="nofollow">Sphinx</a> is a documentation generator using reStructuredText It is quite nice although I have not used it personally The website <a href="http://sphinx pocoo org/" rel="nofollow">Hazel Tree</a> which compiles python text uses Sphinx and so does the new Python documentation
Can you do LINQ-like queries in a language like Python or Boo? Take this simple C# LINQ query and imagine that 'db Numbers' is an SQL table with one column Number: var result = from n in db Numbers where n Number < 5 select n Number; This will run very efficiently in C# because it generates an SQL query something like "select Number from Numbers where Number < 5" What it <them>does not</them> do is select <them>all</them> the numbers from the database and then filter them in C# as it might appear to do at first Python supports a similar syntax: result = [n Number for n in Numbers if n Number < 5] But it the "if" clause here does the filtering on the client side rather than the server side which is much less efficient Is there something as efficient as LINQ in Python? (I am currently evaluating Python vs IronPython vs Boo so an answer that works in any of those languages is fine )
Look closely at <a href="http://www sqlalchemy org/" rel="nofollow">SQLAlchemy</a> This can probably do much of what you want It gives you Python syntax for plain-old SQL that runs on the server
Debug/Monitor middleware for python wsgi applications I am searching a wsgi middleware which I can warp around a wsgi applications and which let us me monitor incoming and outgoing http requests and header fields Something like firefox live headers but for the server side
That should not be too hard to write yourself as long as you only need the headers Try that: ````import sys def log_headers(app stream=None): if stream is None: stream = sys stdout def proxy(environ start_response): for key value in environ iteritems(): if key startswith('HTTP_'): stream write('%s: %s\n' % (key[5:] title() replace('_' '-') value)) return app(environ start_response) return proxy ````
How can i parse a comma delimited string into a list (caveat)? I need to be able to take a string like: ````'''foo bar "one two" three four''' ```` into: ````['foo' 'bar' 'one two' 'three four'] ```` I have an feeling (with hints from #python) that the solution is going to involve the shlex module
You may also want to consider the <a href="http://docs python org/lib/module-csv html" rel="nofollow">csv</a> module I have not tried it but it looks like your input data is closer to CSV than to she will syntax (which is what shlex parses)
Python Regex vs PHP Regex No not a competition it is instead me trying to find why a certain regex works in one but not the other ````(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\ (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\ (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\ (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) ```` That is my Regex and I am trying to run it on ````127 255 0 0 ```` Using Pythons regex I get nothing using PHP I match it below are the two calls I am making (just incase it is something to do with that) Essentially I am trying to work out why it works in PHP but not Python ````re findall(regex string) preg_match_all($regex $string $matches); ```` <hr> Solution found it was due to the way that I was iterating through the results this regex turned them into groups and then it did not want to print them out in the same way etc etc Thank you all for your help it is really appreciated :)
It works for me You must be doing something wrong ````&gt;&gt;&gt; re match(r'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\ (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\ (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\ (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)' '127 255 0 0') groups() ('127' '255' '0' '0') ```` Do not forget to escape the regex using raw strings: `r'regex_here'` as stated in the <a href="http://docs python org/dev/howto/regex html" rel="nofollow">Regex Howto</a>
What is the best dispatcher/callback library in Python? I need to allow other Python applications to register callback functions for events in my application These need to have priorities associated with them (so a callback with a priority of 10 runs before a callback with a priority of 1) and callback functions need to be able to signal errors to the dispatcher These are all lightweight callbacks running in the same process so I do not need to send signals across process boundaries Is there a good Python library to handle this or do I need to write my own?
Are these other applications running in another address space? If so you will need to use an interprocess communication library like <a href="http://www freedesktop org/wiki/Software/dbus" rel="nofollow">D-BUS</a> If you are just sending signals in the same process try <a href="http://pypi python org/pypi/PyDispatcher/2 0 1" rel="nofollow">PyDispatcher</a>
How to start IDLE (Python editor) without using the shortcut on Windows Vista? I am trying to teach Komodo to fire up <a href="http://en wikipedia org/wiki/IDLE%5F%28Python%29">IDLE</a> when I hit the right keystrokes I can use the exact path of the shortcut in start menu in the Windows Explorer location bar to launch IDLE so I was hoping Komodo would be able to use it as well But giving this path to Komodo causes it to say that 1 is returned This appears to be a failure as IDLE does not start up I thought I would avoid the shortcut and just use the exact path I go to the start menu find the shortcut for IDLE right click to look at the properties The target is grayed out but says "Python 2 5 2" The "Start in" is set to "C:\Python25\" The "Open File Location" button is also grayed out How do I find out where this shortcut is really pointing? I have tried starting python exe and pythonw exe both in C:\Python25 but neither starts up IDLE
There is a file called idle py in your Python installation directory in Lib\idlelib\idle py If you run that file with Python then IDLE should start <blockquote> c:\Python25\pythonw exe c:\Python25\Lib\idlelib\idle py </blockquote>
How do you use the ellipsis slicing syntax in Python? This came up in <a href="http://stackoverflow com/questions/101268/hidden-features-of-python">Hidden features of Python</a> but I cannot see good documentation or examples that explain how the feature works
You would use it in your own class since no builtin class makes use of it Numpy uses it as stated in the <a href="http://wiki scipy org/Numpy_Example_List_With_Doc#head-490d781b49b68b300eedaef32369fae7d58627fb">documentation</a> Some examples <a href="http://wiki scipy org/Tentative_NumPy_Tutorial#head-864862d3f2bb4c32f04260fac61eb4ef34788c4c">here</a> In your own class you would use it like this: ````&gt;&gt;&gt; class TestEllipsis(object): def __getitem__(self item): if item is Ellipsis: return "Returning all items" else: return "return %r items" % item &gt;&gt;&gt; x = TestEllipsis() &gt;&gt;&gt; print x[2] return 2 items &gt;&gt;&gt; print x[ ] Returning all items ```` Of course there is the <a href="https://docs python org/library/constants html#Ellipsis">python documentation</a> and <a href="https://docs python org/reference/expressions html#grammar-token-slicing">language reference</a> But those are not very helpful
How can I join a list into a string (caveat)? Along the lines of my previous <a href="http://stackoverflow com/questions/118096/how-can-i-parse-a-comma-delimited-string-into-a-list-caveat">question</a> how can i join a list of strings into a string such that values get quoted cleanly Something like: ````['a' 'one "two" three' 'foo bar' """both"'"""] ```` into: ````a 'one "two" three' "foo bar" "both\"'" ```` I suspect that the csv module will come into play here but i am not sure how to get the output I want
Using the `csv` module you can do that way: ````import csv writer = csv writer(open("some csv" "wb")) writer writerow(the_list) ```` If you need a string just use `StringIO` instance as a file: ````f = StringIO StringIO() writer = csv writer(f) writer writerow(the_list) print f getvalue() ```` The output: `a "one ""two"" three" "foo bar" "both""'"` `csv` will write in a way it can read back later You can fine-tune its output by defining a `dialect` just set `quotechar` `escapechar` etc as needed: ````class SomeDialect(csv excel): delimiter = ' ' quotechar = '"' escapechar = "\\" doublequote = False lineterminator = '\n' quoting = csv QUOTE_MINIMAL f = cStringIO StringIO() writer = csv writer(f dialect=SomeDialect) writer writerow(the_list) print f getvalue() ```` The output: `a one \"two\" three "foo bar" both\"'` The same dialect can be used with csv module to read the string back later to a list
How do I create a non-standard type with SOAPpy? I am calling <a href="http://www pingdom com/services/api-documentation/" rel="nofollow">a WSDL web service</a> from Python using <a href="http://pywebsvcs sourceforge net/" rel="nofollow">SOAPpy</a> The call I need to make is to the method <a href="http://www pingdom com/services/api-documentation/operation_login" rel="nofollow">Auth_login</a> This has 2 arguments - the first a string being the API key; the second a <a href="http://www pingdom com/services/api-documentation/class_CredentialsData" rel="nofollow">custom type containing username and password</a> The custom type is called Auth_credentialsData which contains 2 values as stings - one for the username and one for the password How can I create this custom type using SOAPpy? I tried passing a list and a dictionary none of which work Code so far: ````from SOAPpy import WSDL wsdlUrl = 'https://ws pingdom com/soap/PingdomAPI wsdl' client = WSDL Proxy(wsdlUrl) ```` Tried both: ````credentials = ['email@example com' 'password'] client Auth_login('key' credentials) ```` and ````credentials = {'username': 'email@example com' 'password': 'passsword'} client Auth_login('key' credentials) ```` both of which give an authentication failed error
The better method is to use the ZSI soap module which allows you to take a WDSL file and turn it into classes and methods that you can then use to call it The online documentation is <a href="http://pywebsvcs sourceforge net/zsi html#SECTION0012300000000000000000" rel="nofollow"> on their website</a> but the latest documentation is more easily found in the source package If you install in Debian/Ubuntu (package name python-zsi) the documentation is in /usr/share/doc/python-zsi in a pair of PDFs you can find in there
How do I read an Excel file into Python using xlrd? Can it read newer Office formats? My issue is below but would be interested comments from anyone with experience with xlrd I just found xlrd and it looks like the perfect solution but I am having a little problem getting started I am attempting to extract data programatically from an Excel file I pulled from Dow Jones with current components of the Dow Jones Industrial Average (link: <a href="http://www djindexes com/mdsidx/?event=showAverages">http://www djindexes com/mdsidx/?event=showAverages</a>) When I open the file unmodified I get a nasty BIFF error (binary format not recognized) However you can see in this screenshot that Excel 2008 for Mac thinks it is in 'Excel 1997-2004' format (screenshot: <a href="http://skitch com/alok/ssa3/componentreport-dji xls-properties">http://skitch com/alok/ssa3/componentreport-dji xls-properties</a>) If I instead open it in Excel manually and save as 'Excel 1997-2004' format explicitly then open in python usig xlrd everything is wonderful Remember Office thinks the file is already in 'Excel 1997-2004' format All files are xls Here is a pastebin of an ipython session replicating the issue: <a href="http://pastie textmate org/private/jbawdtrvlrruh88mzueqdq">http://pastie textmate org/private/jbawdtrvlrruh88mzueqdq</a> Any thoughts on: How to trick xlrd into recognizing the file so I can extract data? How to use python to automate the explicit 'save as' format to one that xlrd will accept? Plan B?
Well here is some code that I did: (look down the bottom): <a href="http://anonsvn labs jboss com/labs/jbossrules/trunk/drools-decisiontables/src/main/resources/python-dt/pydt py" rel="nofollow">here</a> Not sure about the newer formats - if xlrd cannot read it xlrd needs to have a new version released !
What is wrong with my snap to grid code? First of all I am fairly sure snapping to grid is fairly easy however I have run into some odd trouble in this situation and my maths are too weak to work out specifically what is wrong Here is the situation I have an abstract concept of a grid with Y steps exactly Y_STEP apart (the x steps are working fine so ignore them for now) The grid is in an abstract coordinate space and to get things to line up I have got a magic offset in there let us call it Y_OFFSET to snap to the grid I have got the following code (python) ````def snapToGrid(originalPos offset step): index = int((originalPos - offset) / step) #truncates the remainder away return index * gap offset ```` so I pass the cursor position Y_OFFSET and Y_STEP into that function and it returns me the nearest floored y position on the grid That appears to work fine in the original scenario however when I take into account the fact that the view is scrollable things get a little weird Scrolling is made as basic as I can get it I have got a viewPort that keeps count of the distance scrolled along the Y Axis and just offsets everything that goes through it Here is a snippet of the cursor's mouseMotion code: ````def mouseMotion(self event): pixelPos = event pos[Y] odePos = Scroll pixelPosToOdePos(pixelPos) self tool positionChanged(odePos) ```` So there is two things to look at there first the Scroll module's translation from pixel position to the abstract coordinate space then the tool's positionChanged function which takes the abstract coordinate space value and snaps to the nearest Y step Here is the relevant Scroll code ````def pixelPosToOdePos(pixelPos): offsetPixelPos = pixelPos - self viewPortOffset return pixelsToOde(offsetPixelPos) def pixelsToOde(pixels): return float(pixels) / float(pixels_in_an_ode_unit) ```` And the tools update code ````def positionChanged(self newPos): self snappedPos = snapToGrid(originalPos Y_OFFSET Y_STEP) ```` The last relevant chunk is when the tool goes to render itself It goes through the Scroll object which transforms the tool's snapped coordinate space position into an onscreen pixel position here is the code: ````#in Tool def render(self screen): Scroll render(screen self image self snappedPos) #in Scroll def render(self screen image odePos): pixelPos = self odePosToPixelPos(odePos) screen blit(image pixelPos) # screen is a surface from pygame for the curious def odePosToPixelPos(self odePos): offsetPos = odePos self viewPortOffset return odeToPixels(offsetPos) def odeToPixels(odeUnits): return int(odeUnits * pixels_in_an_ode_unit) ```` Whew that was a long explanation Hope you are still with me The problem I am now getting is that when I scroll up the drawn image loses alignment with the cursor <br /> It starts snapping to the Y step exactly 1 step below the cursor Additionally it appears to phase in and out of allignment <br /> At some scrolls it is out by 1 and other scrolls it is spot on <br /> It is never out by more than 1 and it is always snapping to a valid grid location Best guess I can come up with is that somewhere I am truncating some data in the wrong spot but no idea where or how it ends up with this behavior Anyone familiar with coordinate spaces scrolling and snapping?
Do you have a typo in positionChanged() ? ````def positionChanged(self newPos): self snappedPos = snapToGrid(newPos Y_OFFSET Y_STEP) ```` I guess you are off by one pixel because of the accuracy problems during float division Try changing your snapToGrid() to this: ````def snapToGrid(originalPos offset step): EPS = 1e-6 index = int((originalPos - offset) / step EPS) #truncates the remainder away return index * gap offset ````
How to express this Bash command in pure Python I have this line in a useful Bash script that I have not managed to translate into Python where 'a' is a user-input number of days' worth of files to archive: ````find ~/podcasts/current -mindepth 2 -mtime '+`a`+' -exec mv {} ~/podcasts/old \; ```` I am familiar with the os name and getpass getuser for the most general cross-platform elements I also have this function to generate a list of the full names of all the files in the equivalent of ~/podcasts/current: ````def AllFiles(filepath depth=1 flist=[]): fpath=os walk(filepath) fpath=[item for item in fpath] while depth < len(fpath): for item in fpath[depth][-1]: flist append(fpath[depth][0]+os sep+item) depth+=1 return flist ```` First off there must be a better way to do that any suggestion welcome Either way for example "AllFiles('/users/me/music/itunes/itunes music/podcasts')" gives the relevant list on Windows Presumably I should be able to go over this list and call os stat(list_member) st_mtime and move all the stuff older than a certain number in days to the archive; I am a little stuck on that bit Of course anything with the concision of the bash command would also be illuminating
That is not a Bash command it is a `find` command If you really want to port it to Python it is possible but you will never be able to write a Python version that is as concise `find` has been optimized over 20 years to be excellent at manipulating filesystems while Python is a general-purpose programming language
Is there a way to convert indentation in Python code to braces? I am a totally blind programmer who would like to learn Python Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into a properly indented representation that the Python interpreter could use?
I personally doubt that there currently is at the moment as a lot of the Python afficionados love the fact that Python is this way whitespace delimited I have never actually thought about that as an accessibility issue however Maybe it is something to put forward as a bug report to Python? I would assume that you use a screen reader here however for the output? So the tabs would seem "invisible" to you? With a Braille output it might be easier to read but I can understand exactly how confusing this could be In fact this is very interesting to me I wish that I knew enough to be able to write an app that will do this for you I think it is definately something that I will put in a bug report for unless you have already done so yourself or want to Edit: Also as <a href="http://stackoverflow com/questions/118643#118656">noted</a> by <a href="http://stackoverflow com/users/3560/john-millikin">John Millikin</a> There is also <a href="http://timhatch com/projects/pybraces/">PyBraces</a> Which might be a viable solution to you and may be possible to be hacked together dependant on your coding skills to be exactly what you need (and I hope that if that is the case you release it out for others like yourself to use) Edit 2: I have just <a href="http://bugs python org/issue3942">reported this</a> to the python bug tracker
Iron python beautiful soup win32 app Does beautiful soup work with iron python? If so with which version of iron python? How easy is it to distribute a windows desktop app on net 2 0 using iron python (mostly c# calling some python code for parsing html)?
I have not tested it but I would say it will most likely work with the latest IPy2 As for distribution it is very simple Use the -X:SaveAssemblies option to compile your Python code down to a binary and then ship it with your other DLLs and the IPy dependencies
How do I uninstall python from OSX Leopard so that I can use the MacPorts version? I want to use the macports version of python instead of the one that comes with Leopard
I have both installed: ````$ which python /usr/bin/python $ which python2 5 /opt/local/bin/python2 5 ```` I also added the following line to my ` profile`: ````export PATH=/opt/local/bin:/opt/local/sbin:$PATH ````
Adding code to __init__ py I am taking a look at how the model system in django works and I noticed something that I do not understand I know that you create an empty `__init__ py` file to specify that the current directory is a package And that you can set some variable in `__init__ py` so that import * works properly But django adds a bunch of from import statements and defines a bunch of classes in `__init__ py` Why? Does not this just make things look messy? Is there a reason that requires this code in `__init__ py`?
All imports in `__init__ py` are made available when you import the package (directory) that contains it Example: ` /dir/__init__ py`: ````import something ```` ` /test py`: ````import dir # can now use dir something ```` EDIT: forgot to mention the code in `__init__ py` runs the first time you import any module from that directory So it is normally a good place to put any package-level initialisation code EDIT2: dgrant pointed out to a possible confusion in my example In `__init__ py` `import something` can import any module not necessary from the package For example we can replace it with `import datetime` then in our top level `test py` both of these snippets will work: ````import dir print dir datetime datetime now() ```` and ````import dir some_module_in_dir print dir datetime datetime now() ```` The bottom line is: all names assigned in `__init__ py` be it imported modules functions or classes are automatically available in the package namespace whenever you import the package or a module in the package
Is it good to switch from c# to python? Currently I am developing in the Net environment using C# but I want to know whether it is worth learning python I am thinking of learning the Django framework What is better?
Depends on what you will use it for If you are making enterprise Windows forms applications I do not think switching to Python would be a good idea Also it is possible to still use Python on the NET CLR with IronPython
time length of an mp3 file What is the simplest way to determine the length (in seconds) of a given mp3 file <strong>without using outside libraries</strong>? (python source highly appreciated)
You can use <a href="http://spacepants org/src/pymad/">pymad</a> It is an external library but do not fall for the Not Invented Here trap Any particular reason you do not want any external libraries? ````import mad mf = mad MadFile("foo mp3") track_length_in_milliseconds = mf total_time() ```` Spotted <a href="http://simonwillison net/2003/Dec/4/mp3lengths/">here</a> -- If you really do not want to use an external library have a look <a href="http://ibofobi dk/stuff/mp3/">here</a> and check out how he is done it Warning: it is complicated
Tabs versus spaces in Python programming I have always used tabs for indentation when I do Python programming But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true? Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?
Because <a href="http://www python org/dev/peps/pep-0008/#tabs-or-spaces">PEP-8</a> tells us to use spaces :)
Find matching sequences in two binary files Let me start off with a bit of background This morning one of our users reported that Testuff's setup file has been reported as infected with a virus by the CA antivirus Confident that this was a false positive I looked on the web and found that users of another program (SpyBot) have reported the same problem A now for the actual question Assuming the antivirus is looking for a specific binary signature in the file I would like to find the matching sequences in both files and hopefully find a way to tweak the setup script to prevent that sequence from appearing I tried the following in Python but it is been running for a long time now and I was wondering if there was a better or faster way ````from difflib import SequenceMatcher spybot = open("spybotsd160 exe" "rb") read() testuff = open("TestuffSetup exe" "rb") read() s = SequenceMatcher(None spybot testuff) print s find_longest_match(0 len(spybot) 0 len(testuff)) ```` Is there a better library for Python or for another language that can do this? A completely different way to tackle the problem is welcome as well
Why do not you contact CA and ask them to tell them what they are searching for for that virus? Or you could copy the file and change each individual byte until the warning disappeared (may take a while depending on the size) It is possible the virus detection may be a lot more complicated than simply looking for a fixed string
Parse DICOM files in native Python What is the simplest and most-pythonic way to parse a DICOM file? A native Python implementation without the use of non-Python libraries would be much preferred DICOM is the standard file format in digital medical imaging (look <a href="http://en wikipedia org/wiki/Digital_Imaging_and_Communications_in_Medicine">here</a> for more information) There are some C/C++ libraries that support reading (a subset) of DICOM files Two or three of them even have Python bindings A native Python parser would serve two purposes for me: - No need to build any external C/C++ libraries - Learn about the DICOM file format
I wonder what the original poster tried and which methods worked and not worked for him I have never worked with DICOM but a quick google search for "DICOM python" gave several interesting results It seems that this project: <a href="http://www creatis univ-lyon1 fr/Public/Gdcm/" rel="nofollow">http://www creatis univ-lyon1 fr/Public/Gdcm/</a> should deliver what you want It has python bindings and a pretty active mailing list
Using **kwargs with SimpleXMLRPCServer in python I have a class that I wish to expose as a remote service using pythons SimpleXMLRPCServer The server startup looks like this: ````server = SimpleXMLRPCServer((serverSettings LISTEN_IP serverSettings LISTEN_PORT)) service = Service() server register_instance(service) server serve_forever() ```` I then have a ServiceRemote class that looks like this: ````def __init__(self ip port): self rpcClient = xmlrpclib Server('http://%s:%d' %(ip port)) def __getattr__(self name): # forward all calls to the rpc client return getattr(self rpcClient name) ```` So all calls on the ServiceRemote object will be forwarded to xmlrpclib Server which then forwards it to the remote server The problem is a method in the service that takes named varargs: ````@useDb def select(self db fields **kwargs): pass ```` The @useDb decorator wraps the function creating the db before the call and opening it then closing it after the call is done before returning the result When I call this method I get the error "<strong>call</strong>() got an unexpected keyword argument 'name'" So is it possible to call methods taking variable named arguments remotely? Or will I have to create an override for each method variation I need <hr> Thanks for the responses I changed my code around a bit so the question is no longer an issue However now I know this for future reference if I indeed do need to implement positional arguments and support remote invocation I think a combination of Thomas and praptaks approaches would be good Turning kwargs into positional args on the client through xmlrpclient and having a wrapper on methods serverside to unpack positional arguments
As far as I know the underlying protocol does not support named varargs (or any named args for that matter) The workaround for this is to create a wrapper that will take the **kwargs and pass it as an ordinary dictionary to the method you want to call Something like this Server side: ````def select_wrapper(self db fields kwargs): """accepts an ordinary dict which can pass through xmlrpc""" return select(self db fields **kwargs) ```` On the client side: ````def select(self db fields **kwargs): """you can call it with keyword arguments and they will be packed into a dict""" return self rpcClient select_wrapper(self db fields kwargs) ```` Disclaimer: the code shows the general idea you can do it a bit cleaner (for example writing a decorator to do that)
Dynamically create variables inside function I want to create variables inside function from dictionary Let Us say I have a dictionary ````bar = {'a': 1 'b': 2 'c': 3} ```` and function ````def foo(): pass ```` What I want to do is to create inside function "foo" variables with names of each dictionary item name and values as dictionary item values So in the end it should be similar to ````def foo(): a = 1 b = 2 c = 3 ```` Is it possible at all? And if it does how to do such thing?
Why would you want to do such a thing? Unless you actually do anything with the variables inside the function a function that just assigns several variables and then discards them is indistinguishable to def foo(): pass (An optimiser would be justified in generating exactly the same bytecode) If you also want to dynamically append code that uses the values then you could do this by using exec (though unless this is really user-input code there are almost certainly better ways to do what you want) eg: ````some_code = ' return a+b+c' exec "def foo():\n " '\n ' join('%s = %s' for k v in bar items()) '\n' some_code ```` (Note that your code must be indented to the same level ) On the other hand if you want to actually assign these values to the function <strong>object</strong> (so you can do foo a and get 1 - note that your sample code does not do this) you can do this by: ````for key val in bar items(): setattr(foo key val) ````
Fetch a Wikipedia article with Python I try to fetch a Wikipedia article with Python's urllib: ````f = urllib urlopen("http://en wikipedia org/w/index php?title=Albert_Einstein&amp;printable=yes") s = f read() f close() ```` However instead of the html page I get the following response: Error - Wikimedia Foundation: ````Request: GET http://en wikipedia org/w/index php?title=Albert_Einstein&amp;printable=yes from 192 35 17 11 via knsq1 knams wikimedia org (squid/2 6 STABLE21) to () Error: ERR_ACCESS_DENIED errno [No Error] at Tue 23 Sep 2008 09:09:08 GMT ```` Wikipedia seems to block request which are not from a standard browser Anybody know how to work around this?
Try changing the user agent header you are sending in your request to something like: User-Agent: Mozilla/5 0 (X11; YOU; Linux i686; en-US; rv:1 9 0 1) Gecko/2008072820 Ubuntu/8 04 (hardy) Firefox/3 0 1 (Linux Mint)
Short Integers in Python Python allocates integers automatically based on the underlying system architecture Unfortunately I have a huge dataset which needs to be fully loaded into memory So is there a way to force Python to use only 2 bytes for some integers (equivalent of C++ 'short')?
Nope But you can use short integers in arrays: ````from array import array a = array("h") # h = signed short H = unsigned short ```` As long as the value stays in that array it will be a short integer - documentation for the <a href="http://docs python org/dev/library/array">array module</a>
Directory listing in Python How do I get a list of all files (and directories) in a given directory in Python?
You can use ````os listdir(path) ```` For reference and more os functions look here: - Python 2 docs: <a href="https://docs python org/2/library/os html#os listdir">https://docs python org/2/library/os html#os listdir</a> - Python 3 docs: <a href="https://docs python org/3 4/library/os html#os listdir">https://docs python org/3 4/library/os html#os listdir</a>
Python subprocess issue with ampersands I am currently having a major issue with a python script The script runs arbitrary commands through a handler to convert incorrect error reporting into correct error reporting The issue I am having is getting the script to work correctly on windows with a command that contains ampersands in it is path I have attempted quoting the command escaping the ampersand with ^ and neither works I am now out of ideas Any suggestions? To clarify from current responses: - I am using the subprocess module - I am passing the command line arguments in as a list - The issue is with the path to the command itself not any of the arguments - I have tried quoting the command It causes a `[Error 123] The filename directory name or volume label syntax is incorrect` error - I am using no she will argument (so `she will=false`) - In case it matters I am grabbing a pipe to stderr for processing it but ignoring stdout and stdin - It is only for use on Windows currently and works as expected in all other cases that I have tested so far - The command that is failing is: <blockquote> p = subprocess Popen(prog stderr = subprocess PIPE bufsize=-1) </blockquote> when the first element of the list 'prog' contains any ampersands Quoting this first string does not work
A proper answer will need more information than that What are you actually doing? How does it fail? Are you using the subprocess module? Are you passing a list of arguments and she will=False (or no she will argument) or are you actually invoking the she will?
SVG rendering in a PyGame application In a <a href="http://www pygame org/">pyGame</a> application I would like to render resolution-free GUI widgets described in SVG What tool and/or library can I use to reach this goal ? (I like the <a href="http://ocemp sourceforge net/gui html">OCEMP GUI</a> toolkit but it seems to be bitmap dependent for its rendering)
You can use <a href="http://www cairographics org/" rel="nofollow">Cairo</a> (with PyCairo) which has support for rendering SVGs The PyGame webpage has a <a href="http://www pygame org/wiki/CairoPygame" rel="nofollow">HOWTO</a> for rendering into a buffer with a Cairo and using that buffer directly with PyGame
Why does Python pep-8 strongly recommend spaces over tabs for indentation? I see on Stack Overflow and <a href="http://www python org/dev/peps/pep-0008/">PEP 8</a> that the recommendation is to use spaces only for indentation in Python programs I can understand the need for consistent indentation and I have felt that pain Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with
The problem with tabs is that they are invisible and people can never agree on the width of tabs When you mix tabs and spaces and you set tabstops at something other than Python (which uses tabstops every 8 spaces) you will be seeing the code in a different layout than Python sees it And because the layout determines blocks you will be seeing different logic It leads to subtle bugs If you insist on defying PEP 8 and using tabs -- or worse mixing tabs and spaces -- at least always run python with the '-tt' argument which makes <them>inconsistent</them> indentation (sometimes a tab sometimes a space for the same indentation level) an error Also if possible set your editor to display tabs differently But really the best approach is not to use tabs period
How can I normalize a URL in python I would like to know do I normalize a URL in python For example If I have a url string like : "http://www example com/foo goo/bar html" I need a library in python that will transform the extra space (or any other non normalized character) to a proper URL
````import urlparse urllib def myquote(url): parts= urlparse urlparse(url) return urlparse urlunparse(parts[:2] urllib quote(parts[2]) parts[3:]) ```` This quotes only the path component Otherwise you could do: `urllib quote(url safe=":/")`
How do I develop and create a self-contained PyGTK application bundle for MacOS with native-looking widgets? I have read that it is possible to <a href="http://developer imendio com/projects/gtk-macosx/build-instructions" rel="nofollow">build GTK+ on MacOS X</a> I know that it is possible to create a <a href="http://developer imendio com/projects/gtk-macosx/creating-app-bundles" rel="nofollow">bundle of a GTK+ application on MacOS</a> I also know that it is possible to create widgets <a href="http://people imendio com/richard/archives/2008/02/native_mac_them_1 html" rel="nofollow">that look sort of native</a> However searching around I am not really clear on how to create a bundle that includes the native theme stuff and uses Python rather than its own C main-point There are also rumors <a href="http://developer imendio com/node/175" rel="nofollow">that it is possible to build PyGTK</a> but it sounds like there might still be some wrinkles in that process However there is no step-by-step guide that explains how one can set up an environment where an application might be run from Python source then built and deployed in an app bundle How can I go about doing that?
I am not sure if I am grokking all the details of your question but looking at your problem in general (how do I deploy a python app on mac) I am inclined to say that the answer is <a href="http://undefined org/python/py2app html" rel="nofollow">py2app</a> Basically this will bundle a python interpreter and all relevant python files for you and give you a scriptable system that you can use to add in whatever other resources/dependencies you need
Accessing object memory address When you call the `object __repr__()` method in python you get something like this back: `<__main__ Test object at 0x2aba1c0cf890&gt;` is there any way to get a hold of the memory address if you overload `__repr__()` other then calling `super(Class obj) __repr__()` and regexing it out?
Just use ````id(object) ````
How do I include a stacktrace in my Django 500 html page? I am running `Django 1 0` and I am close to deploying my app As such I will be changing the DEBUG setting to False With that being said I would still like to include the stacktrace on my 500 html page when errors occur By doing so users can copy-and-paste the errors and easily email them to the developers Any thoughts on how best to approach this issue?
Automatically log your 500s that way: - You know when they occur - You do not need to rely on users sending you stacktraces Joel recommends even going so far as automatically creating tickets in your bug tracker when your application experiences a failure Personally I create a (private) RSS feed with the stacktraces urls etc that the developers can subscribe to Showing stack traces to your users on the other hand could possibly leak information that malicious users could use to attack your site Overly detailed error messages are one of the classic stepping stones to SQL injection attacks <them>Edit</them> (added code sample to capture traceback): You can get the exception information from the sys exc_info call While formatting the traceback for display comes from the traceback module: ````import traceback import sys try: raise Exception("Message") except: type value tb = sys exc_info() print &gt;&gt; sys stderr type __name__ ":" value print &gt;&gt; sys stderr '\n' join(traceback format_tb(tb)) ```` Prints: ````Exception : Message File "exception py" line 5 in <module&gt; raise Exception("Message") ````
How do I write this in Ruby/Python? Or can you translate my LINQ to Ruby/Python? Yesterday I asked <a href="http://stackoverflow com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby">this</a> question and never really got an answer I was really happy with I really would like to know how to generate a list of N unique random numbers using a functional language such as Ruby without having to be extremely imperative in style Since I did not see anything I really liked I have written the solution I was looking for in LINQ: ```` static void Main(string[] args) { var temp = from q in GetRandomNumbers(100) Distinct() Take(5) select q; } private static IEnumerable GetRandomNumbers(int max) { Random are = new Random(); while (true) { yield return r Next(max); } } ```` Can you translate my LINQ to Ruby? Python? Any other functional programming language? <strong>Note:</strong> Please try not to use too many loops and conditionals - otherwise the solution is trivial Also I would rather see a solution where you do not have to generate an array much bigger than N so you can then just remove the duplicates and trim it down to N I know I am being picky but I would really like to see some elegant solutions to this problem Thanks! <strong>Edit:</strong><br /> Why all the downvotes? Originally my code sample had the Distinct() after the Take() which as many pointed out could leave me with an empty list I have changed the order in which those methods are called to reflect what I meant in the first place <strong>Apology:</strong><br /> I have been told this post came across as rather snobbish I was not trying to imply that LINQ is better than Ruby/Python; or that my solution is much better than everyone else's My intent is just to learn how to do this (with certain constraints) in Ruby I am sorry if I came across as a jerk
Python with Numeric Python: ````from numpy import * a = random random_integers(0 100 5) b = unique(a) ```` Voilà! Sure you could do something similar in a functional programming style but why?
How do you translate this regular-expression idiom from Perl into Python? I switched from Perl to Python about a year ago and have not looked back There is only *one* idiom that I have ever found I can do more easily in Perl than in Python: ````if ($var =~ /foo( +)/) { # do something with $1 } elsif ($var =~ /bar( +)/) { # do something with $1 } elsif ($var =~ /baz( +)/) { # do something with $1 } ```` The corresponding Python code is not so elegant since the if statements keep getting nested: ````m = re search(r'foo( +)' var) if m: # do something with m group(1) else: m = re search(r'bar( +)' var) if m: # do something with m group(1) else: m = re search(r'baz( +)' var) if m: # do something with m group(2) ```` Does anyone have an elegant way to reproduce this pattern in Python? I have seen anonymous function dispatch tables used but those seem kind of unwieldy to me for a small number of regular expressions
Using named groups and a dispatch table: ````are = re compile(r'(?P<cmd&gt;foo|bar|baz)(?P<data&gt; +)') def do_foo(data): def do_bar(data): def do_baz(data): dispatch = { 'foo': do_foo 'bar': do_bar 'baz': do_baz } m = r match(var) if m: dispatch[m group('cmd')](m group('data')) ```` With a little bit of introspection you can auto-generate the regexp and the dispatch table
How do I find the location of my Python site-packages directory? How do I find the location of my site-packages directory?
From <a href="http://docs djangoproject com/en/dev/topics/install/#remove-any-old-versions-of-django">"How to Install Django" documentation</a> (though this is useful to more than just Django installation) - execute the following from the she will: ````python -c "from distutils sysconfig import get_python_lib; print(get_python_lib())" ```` Formatted for readability (rather than use as a one-liner) that looks like the following: ````from distutils sysconfig import get_python_lib print(get_python_lib()) ````
Is there an Eclipse add-on to build a python executable for distribution? I want to build an executable to distribute to people without python installed on their machines Is there an add-on to Eclipse that allows this? I could not find one If not do you have a builder that you recommend that would make it easy to go to my python project directory created in Eclipse and bundle it all up? Thanks Mark
It is not eclipse but ActiveState's <a href="http://docs activestate com/activepython/2 5/faq/windows/index html#where-is-freeze-for-windows" rel="nofollow">ActivePython FAQ</a> mentions the freeze utility which sounds like it might be close to what you are asking for
Need to create a layered dict from a flat one I have a dict that looks like this: ````{ 'foo': { 'opt1': 1 'opt2': 2 } 'foo/bar': { 'opt3': 3 'opt4': 4 } 'foo/bar/baz': { 'opt5': 5 'opt6': 6 } } ```` And I need to get it to look like: ````{ 'foo': { 'opt1': 1 'opt2': 2 'bar': { 'opt3': 3 'opt4': 4 'baz': { 'opt5': 5 'opt6': 6 } } } } ```` I should point out that there can and will be multiple top-level keys ('foo' in this case) I could probably throw something together to get what i need but I was hoping that there is a solution that is more efficient
Like this: ````def nest(d): rv = {} for key value in d iteritems(): node = rv for part in key split('/'): node = node setdefault(part {}) node update(value) return rv ````
How do I copy a file in python? How do I copy a file in Python? I could not find anything under <a href="https://docs python org/2/library/os html">`os`</a>
<a href="http://docs python org/2/library/shutil html">`shutil`</a> has many methods you can use One of which is: ````from shutil import copyfile copyfile(src dst) ```` Copy the contents of the file named `src` to a file named `dst` The destination location must be writable; otherwise an `IOError` exception will be raised If `dst` already exists it will be replaced Special files such as character or block devices and pipes cannot be copied with this function `src` and `dst` are path names given as strings
Passing apache2 digest authentication information to a wsgi script run by mod_wsgi I have got the directive ````<VirtualHost *&gt; <Location /&gt; AuthType Digest AuthName "global" AuthDigestDomain / AuthUserFile /root/apache_users <Limit GET&gt; Require valid-user </Limit&gt; </Location&gt; WSGIScriptAlias / /some/script wsgi WSGIDaemonProcess mywsgi user=someuser group=somegroup processes=2 threads=25 WSGIProcessGroup mywsgi ServerName some example org </VirtualHost&gt; ```` I would like to know in the /some/script wsgi ````def application(environ start_response): start_response('200 OK' [ ('Content-Type' 'text/plain') ]) return ['Hello'] ```` What user is logged in How do I do that?
add `WSGIPassAuthorization On`: ````<VirtualHost *&gt; <Location /&gt; AuthType Digest AuthName "global" AuthDigestDomain / AuthUserFile /root/apache_users <Limit GET&gt; Require valid-user </Limit&gt; </Location&gt; WSGIPassAuthorization On WSGIScriptAlias / /some/script wsgi WSGIDaemonProcess mywsgi user=someuser group=somegroup processes=2 threads=25 WSGIProcessGroup mywsgi ServerName some example org </VirtualHost&gt; ```` Then just read `environ['REMOTE_USER']`: ````def application(environ start_response): start_response('200 OK' [ ('Content-Type' 'text/plain') ]) return ['Hello %s' % environ['REMOTE_USER']] ```` More information at <a href="http://code google com/p/modwsgi/wiki/ConfigurationGuidelines#User_Authentication">mod_wsgi documentation</a>
How to get/set logical directory path in python In python is it possible to get or set a logical directory (as opposed to an absolute one) For example if I have: ````/real/path/to/dir ```` and I have ````/linked/path/to/dir ```` linked to the same directory using os getcwd and os chdir will always use the absolute path ````&gt;&gt;&gt; import os &gt;&gt;&gt; os chdir('/linked/path/to/dir') &gt;&gt;&gt; print os getcwd() /real/path/to/dir ```` The only way I have found to get around this at all is to launch 'pwd' in another process and read the output However this only works until you call os chdir for the first time
The underlying operational system / she will reports real paths to python So there really is no way around it since `os getcwd()` is a wrapped call to C Library `getcwd()` function There are some workarounds in the spirit of the one that you already know which is launching `pwd` Another one would involve using `os environ['PWD']` If that environmnent variable is set you can make some `getcwd` function that respects it The solution below combines both: ````import os from subprocess import Popen PIPE class CwdKeeper(object): def __init__(self): self _cwd = os environ get("PWD") if self _cwd is None: # no environment fall back to calling pwd on she will self _cwd = Popen('pwd' stdout=PIPE) communicate()[0] strip() self _os_getcwd = os getcwd self _os_chdir = os chdir def chdir(self path): if not self _cwd: return self _os_chdir(path) p = os path normpath(os path join(self _cwd path)) result = self _os_chdir(p) self _cwd = p os environ["PWD"] = p return result def getcwd(self): if not self _cwd: return self _os_getcwd() return self _cwd cwd = CwdKeeper() print cwd getcwd() # use only cwd chdir and cwd getcwd from now on # monkeypatch os if you want: os chdir = cwd chdir os getcwd = cwd getcwd # now you can use os chdir and os getcwd as normal ````
Passing around urls between applications in the same project I am trying to mock-up an API and am using separate apps within Django to represent different web services I would like App A to take in a link that corresponds to App B and parse the `json` response Is there a way to dynamically construct the url to App B so that I can test the code in development and not change to much before going into production? The problem is that I cannot use localhost as part of a link I am currently using urllib but eventually I would like to do something less hacky and better fitting with the web services `REST` paradigm
You could do something like ````if settings DEBUG: other = "localhost" else: other = "somehost" ```` and use other to build the external URL Generally you code in DEBUG mode and deploy in non-DEBUG mode settings DEBUG is a 'standard' Django thing
Comparison of Python and Perl solutions to Wide Finder challenge I would be very grateful if you could compare the winning <a href="http://www cs ucsd edu/~sorourke/wf pl" rel="nofollow">O’Rourke's Perl solution</a> to <a href="http://effbot org/zone/wide-finder htm" rel="nofollow">Lundh's Python solution</a> as I do not know Perl good enough to understand what is going on there More specifically I would like to know what gave Perl version 3x advantage: algorithmic superiority quality of C extensions other factors? <a href="http://www tbray org/ongoing/When/200x/2007/10/30/WF-Results" rel="nofollow">Wide Finder: Results</a>
Perl is heavily optimized for text processing There are so many factors that it is hard to say what is the exact difference Text is represented completely differently internally (utf-8 versus utf-16/utf-32) and the regular expression engines are completely different too Python's regular expression engine is a custom one and not as much used as the perl one There are very few developers working on it (I think it is largely unmaintained) in contrast to the Perl one which is basically the "core of the language" After all Perl is <them>the</them> text processing language
What is the intended use of the DEFAULT section in config files used by ConfigParser? I have used ConfigParser for quite a while for simple configs One thing that is bugged me for a long time is the DEFAULT section I am not really sure what is an appropriate use I have read the documentation but I would really like to see some clever examples of its use and how it affects other sections in the file (something that really illustrates the kind of things that are possible)
I found an explanation <a href="http://www enfoldsystems com/software/proxy/docs/4 0/configuringmanually html#the-default-section">here</a> by googling for "windows ini" "default section" Summary: whatever you put in the [DEFAULT] section gets propagated to every other section Using the example from the linked website let us say I have a config file called test1 ini: ````[host 1] lh_server=192 168 0 1 vh_hosts = PloneSite1:8080 lh_root = PloneSite1 [host 2] lh_server=192 168 0 1 vh_hosts = PloneSite2:8080 lh_root = PloneSite2 ```` I can read this using ConfigParser: ````&gt;&gt;&gt; cp = ConfigParser ConfigParser() &gt;&gt;&gt; cp read('test1 ini') ['test1 ini'] &gt;&gt;&gt; cp get('host 1' 'lh_server') '192 168 0 1' ```` But I notice that lh_server is the same in both sections; and indeed I realise that it will be the same for most hosts I might add So I can do this as test2 ini: ````[DEFAULT] lh_server=192 168 0 1 [host 1] vh_root = PloneSite1 lh_root = PloneSite1 [host 2] vh_root = PloneSite2 lh_root = PloneSite2 ```` Despite the sections not having lh_server keys I can still access them: ````&gt;&gt;&gt; cp read('test2 ini') ['test2 ini'] &gt;&gt;&gt; cp get('host 1' 'lh_server') '192 168 0 1' ```` Read the linked page for a further example of using variable substitution in the DEFAULT section to simplify the INI file even more
What is the easiest most concise way to make selected attributes in an instance be readonly? In Python I want to make <strong>selected</strong> instance attributes of a class be readonly to code outside of the class I want there to be no way outside code can alter the attribute except indirectly by invoking methods on the instance I want the syntax to be concise What is the best way? (I give my current best answer below )
There is no real way to do this There are ways to make it more 'difficult' but there is no concept of completely hidden inaccessible class attributes If the person using your class cannot be trusted to follow the API docs then that is their own problem Protecting people from doing stupid stuff just means that they will do far more elaborate complicated and damaging stupid stuff to try to do whatever they should not have been doing in the first place
Adding New Element to Text Substring Say I have the following string: ````"I am the most foo h4ck3r ever!!" ```` I am trying to write a makeSpecial(foo) function where the foo substring would be wrapped in a new span element resulting in: ````"I am the most <span class="special"&gt;foo&gt;</span&gt; h4ck3r ever!!" ```` BeautifulSoup seemed like the way to go but I have not been able to make it work I could also pass this to the browser and do it with javascript but that does not seem like a great idea Some advice for this would be really useful especially in python
How about this: ````Python 2 5 1 (r251:54863 Apr 18 2007 08:51:08) [MSC v 1310 32 bit (Intel)] on win32 Type "help" "copyright" "credits" or "license" for more information &gt;&gt;&gt; def makeSpecial(mystring special_substr): return mystring replace(special_substr '<span class="special"&gt;%s</span&gt; ' % special_substr) &gt;&gt;&gt; makeSpecial("I am the most foo h4ck3r ever!!" "foo") 'I am the most <span class="special"&gt;foo</span&gt; h4ck3r ever!!' &gt;&gt;&gt; ````
extracting text from MS word files in python for working with MS word files in python there is python win32 extensions which can be used in windows How do I do the same in linux? Is there any library?
Take a look at <a href="http://stackoverflow com/questions/124869/how-does-the-doc-format-work" rel="nofollow" title="how the doc format works">how the doc format works</a> and <a href="http://stackoverflow com/questions/124959/create-word-document-using-php-in-lunux" rel="nofollow" title="create word document using php in linux">create word document using PHP in linux</a> The former is especially useful <a href="http://www abisource com/" rel="nofollow" title="abiword">Abiword</a> is my recommended tool There are <a href="http://www abisource com/wiki/Microsoft_Word_documents" rel="nofollow" title="Abiword limitations">limitations</a> though: <blockquote> However if the document has complicated tables text boxes embedded spreadsheets and so forth then it might not work as expected Developing good MS Word filters is a very difficult process so please bear with us as we work on getting Word documents to open correctly If you have a Word document which fails to load please open a Bug and include the document so we can improve the importer </blockquote>
How do I modify a text file in Python? I am using Python and would like to insert a string into a text file without deleting or copying the file How can I do that?
Depends on what you want to do To append you can open it with "a": ```` with open("foo txt" "a") as f: f write("new line\n") ```` If you want to preprend something you have to read from the file first: ````with open("foo txt" "r+") as f: old = f read() # read everything in the file f seek(0) # rewind f write("new line\n" old) # write the new line before ````
Python library for rendering HTML and javascript Is there any python module for rendering a HTML page with javascript and get back a DOM object? I want to parse a page which generates almost all of its content using javascript
Only way I know to accomplish this would be to drive real browser for example using <a href="http://selenium-rc openqa org" rel="nofollow">selenium-rc</a>
Example Facebook Application using TurboGears -- pyFacebook I have a TurboGears application I would like to run through Facebook and am looking for an example TurboGears project using pyFacebook or minifb py pyFacebook is Django-centric and I can probably figure it out but this is after all the lazy web
Why is pyFacebook django centric? Looks like it works perfectly fine with all kinds of WSGI apps or Python applications in general No need to use Django
"cannot find -lpq" when trying to install psycopg2 <strong>Intro</strong>: I am trying to migrate our Trac SQLite to a PostgreSQL backend to do that I need psycopg2 After clicking past the embarrassing rant on www initd org I downloaded the latest version and tried running `setup py install` This did not work telling me I needed mingw So I downloaded and installed mingw <strong>Problem</strong>: I now get the following error when running `setup py build_ext --compiler=mingw32 install`: ````running build_ext building 'psycopg2 _psycopg' extension writing build\temp win32-2 4\Release\psycopg\_psycopg def C:\mingw\bin\gcc exe -mno-cygwin -shared -s build\temp win32-2 4\Release\psycopg \psycopgmodule o build\temp win32-2 4\Release\psycopg\pqpath o build\temp win32- 2 4\Release\psycopg\typecast o build\temp win32-2 4\Release\psycopg\microprotoco ls o build\temp win32-2 4\Release\psycopg\microprotocols_proto o build\temp win3 2-2 4\Release\psycopg\connection_type o build\temp win32-2 4\Release\psycopg\con nection_int o build\temp win32-2 4\Release\psycopg\cursor_type o build\temp win3 2-2 4\Release\psycopg\cursor_int o build\temp win32-2 4\Release\psycopg\lobject_ type o build\temp win32-2 4\Release\psycopg\lobject_int o build\temp win32-2 4\R elease\psycopg\adapter_qstring o build\temp win32-2 4\Release\psycopg\adapter_pb oolean o build\temp win32-2 4\Release\psycopg\adapter_binary o build\temp win32- 2 4\Release\psycopg\adapter_asis o build\temp win32-2 4\Release\psycopg\adapter_ list o build\temp win32-2 4\Release\psycopg\adapter_datetime o build\temp win32- 2 4\Release\psycopg\_psycopg def -LC:\Python24\libs -LC:\Python24\PCBuild -Lc:/P ROGRA~1/POSTGR~1/8 3/lib -lpython24 -lmsvcr71 -lpq -lmsvcr71 -lws2_32 -ladvapi32 -o build\lib win32-2 4\psycopg2\_psycopg pyd C:\mingw\bin\ \lib\gcc\mingw32\3 4 5\ \ \ \ \mingw32\bin\ld exe: cannot fin d -lpq collect2: ld returned 1 exit status error: command 'gcc' failed with exit status 1 ```` <strong>What I have tried</strong> - I noticed the forward slashes in the -L option so I manually entered my PostgreSQL lib directory in the library_dirs option in the setup cfg to no avail (the call then had a -L option with backslashes but the error message stayed the same)
Have you tried the <a href="http://www stickpeople com/projects/python/win-psycopg/" rel="nofollow">binary build</a> of psycopg2 for windows? If that works with your python then it mitigates the need to build by hand I have seen random people ask this question on various lists and it seems one recommendation is to build postgresql by hand to work around this problem
Iterate a list with indexes in Python I could swear I have seen the function (or method) that takes a list like this `[3 7 19]` and makes it into iterable list of tuples like so: `[(0 3) (1 7) (2 19)]` to use it instead of: ````for i in range(len(name_of_list)): name_of_list[i] = something ```` but I cannot remember the name and googling "iterate list" gets nothing
````&gt;&gt;&gt; a = [3 4 5 6] &gt;&gt;&gt; for i val in enumerate(a): print i val 0 3 1 4 2 5 3 6 &gt;&gt;&gt; ````
How can i move an object drawn in device context python I have drawn an image in the device context using python and i want to move it somothly/animate either vertically or horizontally? What algorithm should i use? Where can i get info for this kind of tasks in python?
Once an object is drawn in a device context it stays there If you want to move it you need to redraw it You can keep a background that is fixed and only redraw the movable elements each time they move Basically that is how it is done To move an object smoothly over a line you have to do something like this (I do not have a program ready so can only give you an idea): - choose the start and end position: point A(x1 y1) and B(x2 y2) - choose in how much time the object should change position from A to B (say 10 seconds) - use a timer set to a certain interval (say 2 seconds) - calculate the delta X and Y that the object should change for each timer interval In this case dx = (x2-x1)*2/10 and dy = (y2-y1)*2/10 - in the timer callback increment the current object position with dx and dy and redraw the image That would be the algorithm I suggest that you also take a look to <a href="http://www pygame org/" rel="nofollow">PyGame</a> Maybe you can use that and it also has some tutorials
Checking for code changes in all imported python modules Almost every Python web framework has a simple server that runs a wsgi application and automatically reloads the imported modules every time the source gets changed I know I can look at the code and see how it is done but that may take some time and I am asking just out of curiosity Does anyone have any idea how this is implemented?
As the author of one of the reloader mechanisms (the one in werkzeug) I can tell you that it does not work What all the reloaders do is forking one time and restarting the child process if a monitor thread notices that one module changed on the file system Inline `reload()`ing does not work because references to the reloaded module are not updated
Find out number of capture groups in Python regular expressions Is there a way to determine how many capture groups there are in a given regular expression? I would like to be able to do the follwing: ````def groups(regexp s): """ Returns the first result of re findall or an empty default &gt;&gt;&gt; groups(r'(\d)(\d)(\d)' '123') ('1' '2' '3') &gt;&gt;&gt; groups(r'(\d)(\d)(\d)' 'abc') ('' '' '') """ import re m = re search(regexp s) if m: return m groups() return ('' ) * num_of_groups(regexp) ```` This allows me to do stuff like: ````first last phone = groups(r'(\w+) (\w+) ([\d\-]+)' 'John Doe 555-3456') ```` However I do not know how to implement `num_of_groups` (Currently I just work around it ) <strong>EDIT:</strong> Following the <a href="http://stackoverflow com/questions/127055/find-out-number-of-capture-groups-in-python-regular-expressions/127089#127089">advice from rslite</a> I replaced `re findall` with `re search` `sre_parse` seems like the most robust and comprehensive solution but requires tree traversal and appears to be a bit heavy MizardX's regular expression seems to cover all bases so I am going to go with that
First of all if you only need the first result of re findall it is better to just use re search that returns a match or None For the groups number you could count the number of open parenthesis '(' except those that are escaped by '\' You could use another regex for that: ````def num_of_groups(regexp): rg = re compile(r'(?<!\\)\(') return len(rg findall(regexp)) ```` Note that this does not work if the regex contains non-capturing groups and also if '(' is escaped by using it as '[(]' So this is not very reliable But depending on the regexes that you use it might help
Contributing to Python I am a pretty inexperienced programmer (can make tk apps text processing sort of understand oop) but Python is so awesome that I would like to help the community What is the best way for a beginner to contribute?
I guess one way would be to help with documentation (translation updating) until you are aware enough about the language Also following the devs and users mail groups would give you a pretty good idea of what is being done and needs to be done by the community
Editing XML as a dictionary in python? I am trying to generate customized xml files from a template xml file in python Conceptually I want to read in the template xml remove some elements change some text attributes and write the new xml out to a file I wanted it to work something like this: ````conf_base = ConvertXmlToDict('config-template xml') conf_base_dict = conf_base UnWrap() del conf_base_dict['root-name']['level1-name']['leaf1'] del conf_base_dict['root-name']['level1-name']['leaf2'] conf_new = ConvertDictToXml(conf_base_dict) ```` now I want to write to file but I do not see how to get to ElementTree ElementTree write() ````conf_new write('config-new xml') ```` Is there some way to do this or can someone suggest doing this a different way?
I am not sure if converting the info set to nested dicts first is easier Using ElementTree you can do this: ````import xml etree ElementTree as ET doc = ET parse("template xml") lvl1 = doc findall("level1-name")[0] lvl1 remove(lvl1 find("leaf1") lvl1 remove(lvl1 find("leaf2") # or use del lvl1[idx] doc write("config-new xml") ```` ElementTree was designed so that you do not have to convert your XML trees to lists and attributes first since it uses exactly that internally It also support as small subset of <a href="http://effbot org/zone/element-xpath htm" rel="nofollow">XPath</a>
How to parse an ISO 8601-formatted date in Python? I need to parse <a href="https://tools ietf org/html/rfc3339">RFC 3339</a> strings like `"2008-09-03T20:56:35 450686Z"` into Python's `datetime` type I have found <a href="https://docs python org/library/datetime html#datetime datetime strptime">`strptime`</a> in the Python standard library but it is not very convenient What is the best way to do this?
What is the exact error you get? Is it like the following: ````&gt;&gt;&gt; datetime datetime strptime("2008-08-12T12:20:30 656234Z" "%Y-%m-%dT%H:%M:%S Z") ValueError: time data did not match format: data=2008-08-12T12:20:30 656234Z fmt=%Y-%m-%dT%H:%M:%S Z ```` If yes you can split your input string on " " and then add the microseconds to the datetime you got Try this: ````&gt;&gt;&gt; def gt(dt_str): dt _ us= dt_str partition(" ") dt= datetime datetime strptime(dt "%Y-%m-%dT%H:%M:%S") us= int(us rstrip("Z") 10) return dt datetime timedelta(microseconds=us) &gt;&gt;&gt; gt("2008-08-12T12:20:30 656234Z") datetime datetime(2008 8 12 12 20 30 656234) &gt;&gt;&gt; ````
How to implement a Decorator with non-local equality? Greetings currently I am refactoring one of my programs and I found an interesting problem I have Transitions in an automata Transitions always have a start-state and an end-state Some Transitions have a label which encodes a certain Action that must be performed upon traversal No label means no action Some transitions have a condition which must be fulfilled in order to traverse this condition if there is no condition the transition is basically an epsilon-transition in an NFA and will be traversed without consuming an input symbol I need the following operations: - check if the transition has a label - get this label - add a label to a transition - check if the transition has a condition - get this condition - check for equality Judging from the first five points this sounds like a clear decorator with a base transition and two decorators: Labeled and Condition However this approach has a problem: two transitions are considered equal if their start-state and end-state are the same the labels at both transitions are equal (or not-existing) and both conditions are the same (or not existing) With a decorator I might have two transitions Labeled("foo" Conditional("bar" Transition("baz" "qux"))) and Conditional("bar" Labeled("foo" Transition("baz" "qux"))) which need a non-local equality that is the decorators would need to collect all the data and the Transition must compare this collected data on a set-base: ````class Transition(object): def __init__(self start end): self start = start self end = end def get_label(self): return None def has_label(self): return False def collect_decorations(self decorations): return decorations def internal_equality(self my_decorations other): try: return (self start == other start and self end == other end and my_decorations = other collect_decorations()) def __eq__(self other): return self internal_equality(self collect_decorations({}) other) class Labeled(object): def __init__(self label base): self base = base self label = label def has_label(self): return True def get_label(self): return self label def collect_decorations(self decorations): assert 'label' not in decorations decorations['label'] = self label return self base collect_decorations(decorations) def __getattr__(self attribute): return self base __getattr(attribute) ```` Is this a clean approach? Am I missing something? I am mostly confused because I can solve this - with longer class names - using cooperative multiple inheritance: ````class Transition(object): def __init__(self **kwargs): # init is pythons MI-madness ;-) super(Transition self) __init__(**kwargs) self start = kwargs['start'] self end = kwargs['end'] def get_label(self): return None def get_condition(self): return None def __eq__(self other): try: return self start == other start and self end == other end except AttributeError: return False class LabeledTransition(Transition): def __init__(self **kwargs): super(LabeledTransition) __init__(**kwargs) self label = kwargs['label'] def get_label(self): return self label def __eq__(self): super_result = super(LabeledTransition self) __eq__(other) try: return super_result and self label == other label except AttributeError: return False class ConditionalTransition(Transition): def __init__(self **kwargs): super(ConditionalTransition self) __init__(**kwargs) self condition = kwargs['condition'] def get_condition(self): return self condition def __eq__(self other): super_result = super(ConditionalTransition self) __eq__(other) try: return super_result and self condition = other condition except AttributeError: return False # ConditionalTransition about the same with get_condition class LabeledConditionalTransition(LabeledTransition ConditionalTransition): pass ```` the class LabledConditionalTransition behaves exactly as expected - and having no code in there is appealing and I do not thing MI is confusing at this size Of course the third option would be to just hammer everything into a single transition class with a bunch of in has_label/has_transition So I am confused Am I missing something? Which implementation looks better? How do you handle similar cases that is objects which look like a Decorator could handle them but then such a non-local method comes around? <them>EDIT</them>: Added the ConditionalTransition-class Basically this kind of behaves like the decorator minus the order created by the order of creating the decorators the transition checks for start and end being correct the LabeledTransition-class checks for label being correct and ConditionalTransition checks for condition being correct
From the code that was posted the only difference between Transition and Labeled Transition is the return of get_lable() and has_label() In which case you can compress these two a single class that sets a label attribute to None and ````return self label is not None ```` in the has_label() function Can you post the code for the `ConditionalTransition` class? I think this would make it clearer
What is the best way to store set data in Python? I have a list of data in the following form: `[(id\__1_ description id\_type) (id\__2_ description id\_type) (id\__n_ description id\_type))` The data are loaded from files that belong to the same group In each group there could be multiples of the same id each coming from different files I do not care about the duplicates so I thought that a nice way to store all of this would be to throw it into a Set type But there is a problem Sometimes for the same id the descriptions can vary slightly as follows: IPI00110753 - Tubulin alpha-1A chain - Tubulin alpha-1 chain - Alpha-tubulin 1 - Alpha-tubulin isotype M-alpha-1 (Note that this example is taken from the <a href="http://www uniprot org/uniprot/P68369" rel="nofollow">uniprot protein database</a> ) I do not care if the descriptions vary I cannot throw them away because there is a chance that the protein database I am using will not contain a listing for a certain identifier If this happens I will want to be able to display the human readable description to the biologists so they know roughly what protein they are looking at I am currently solving this problem by using a dictionary type However I do not really like this solution because it uses a lot of memory (I have a lot of these ID's) This is only an intermediary listing of them There is some additional processing the ID's go through before they are placed in the database so I would like to keep my data-structure smaller I have two questions really First will I get a smaller memory footprint using the Set type (over the dictionary type) for this or should I use a sorted list where I check every time I insert into the list to see if the ID exists or is there a third solution that I have not thought of? Second if the Set type is the better answer how do I key it to look at just the first element of the tuple instead of the whole thing? Thank you for reading my question Tim <strong>Update</strong> based on some of the comments I received let me clarify a little Most of what I do with data-structure is insert into it I only read it twice once to annotate it with additional information * and once to do be inserted into the database However down the line there may be additional annotation that is done before I insert into the database Unfortunately I do not know if that will happen at this time Right now I am looking into storing this data in a structure that is not based on a hash-table (ie a dictionary) I would like the new structure to be fairly quick on insertion but reading it can be linear since I only really do it twice I am trying to move away from the hash table to save space Is there a better structure or is a hash-table about as good as it gets? *The information is a list of Swiss-Prot protein identifiers that I get by querying uniprot
Sets do not have keys The element <strong>is</strong> the key If you think you want keys you have a mapping More-or-less by definition Sequential list lookup can be slow even using a binary search Mappings use hashes and are fast Are you talking about a dictionary like this? ````{ 'id1': [ ('description1a' 'type1') ('description1b' 'type1') ] 'id2': [ ('description2' 'type2') ] } ```` This sure seems minimal ID's are only represented once Perhaps you have something like this? ````{ 'id1': ( ('description1a' 'description1b' ) 'type1' ) 'id2': ( ('description2' ) 'type2' ) } ```` I am not sure you can find anything more compact unless you resort to using the `struct` module
What is the best way to upgrade from Django 0 96 to 1 0? Should I try to actually upgrade my existing app or just rewrite it mostly from scratch saving what pieces (templates etc) I can?
Upgrade For me it was very simple: change `__str__()` to `__unicode__()` write basic `admin py` and done Just start running your app on 1 0 test it and when you encounter an error use the documentation on <a href="http://code djangoproject com/wiki/BackwardsIncompatibleChanges" rel="nofollow">backwards-incompatible changes</a> to see how to fix the issue
Should Python import statements always be at the top of a module? <a href="http://www python org/dev/peps/pep-0008/">PEP 08</a> states: <blockquote> Imports are always put at the top of the file just after any module comments and docstrings and before module globals and constants </blockquote> However if the class/method/function that I am importing is only used in rare cases surely it is more efficient to do the import when it is needed? Is not this: ````class SomeClass(object): def not_often_called(self) from datetime import datetime self datetime = datetime now() ```` more efficient than this? ````from datetime import datetime class SomeClass(object): def not_often_called(self) self datetime = datetime now() ````
The first variant is indeed more efficient than the second when the function is called either zero or one times With the second and subsequent invocations however the "import every call" approach is actually less efficient See <a href="http://wiki python org/moin/PythonSpeed/PerformanceTips#head-c849d5d5d94bc3eacbff9d5746af4083443cf2ca">this link</a> for a lazy-loading technique that combines the best of both approaches by doing a "lazy import" But there are reasons other than efficiency why you might prefer one over the other One approach is makes it much more clear to someone reading the code as to the dependencies that this module has They also have very different failure characteristics -- the first will fail at load time if there is no "datetime" module while the second will not fail until the method is called <strong>Added Note:</strong> In IronPython imports can be quite a bit more expensive than in CPython because the code is basically being compiled as it is being imported
Using property() on classmethods I have a class with two class methods (using the classmethod() function) for getting and setting what is essentially a static variable I tried to use the property() function with these but it results in an error I was able to reproduce the error with the following in the interpreter: ````&gt;&gt;&gt; class foo(object): _var=5 def getvar(cls): return cls _var getvar=classmethod(getvar) def setvar(cls value): cls _var=value setvar=classmethod(setvar) var=property(getvar setvar) &gt;&gt;&gt; f getvar() 5 &gt;&gt;&gt; f setvar(4) &gt;&gt;&gt; f getvar() 4 &gt;&gt;&gt; f var Traceback (most recent call last): File "<stdin&gt;" line 1 in ? TypeError: 'classmethod' object is not callable &gt;&gt;&gt; f var=5 Traceback (most recent call last): File "<stdin&gt;" line 1 in ? TypeError: 'classmethod' object is not callable ```` Is it possible to use the property() function with classmethod decorated functions?
Here is my suggestion Do not use class methods Seriously What is the reason for using class methods in this case? Why not have an ordinary object of an ordinary class? <hr /> If you simply want to change the value a property is not really very helpful is it? Just set the attribute value and be done with it A property should only be used if there is something to conceal -- something that might change in a future implementation Maybe your example is way stripped down and there is some hellish calculation you have left off But it does not look like the property adds significant value The Java-influenced "privacy" techniques (in Python attribute names that begin with _) are not really very helpful Private from whom? The point of private is a little nebulous when you have the source (as you do in Python ) The Java-influenced EJB-style getters and setters (often done as properties in Python) are there to facilitate Java's primitive introspection as well as to pass muster with the static language compiler All those getters and setters are not as helpful in Python
Does Django support multi-value cookies? I would like to set a cookie via Django with that has several different values to it similar to NET's <a href="http://msdn microsoft com/en-us/library/system web httpcookie_members(VS 80) aspx" rel="nofollow">HttpCookie Values</a> property Looking at the <a href="http://docs djangoproject com/en/dev/ref/request-response/#django http HttpResponse set_cookie" rel="nofollow">documentation</a> I cannot tell if this is possible It looks like it just takes a string so is there another way? I have tried passing it an array (`[10 20 30]`) and dictionary (`{'name': 'Scott' 'id': 1}`) but they just get converted to their string format My current solution is to just use an arbitrary separator and then parse it when reading it in which feels icky If multi-values are not possible is there a better way? I would rather not use lots of cookies because that would get annoying
NETs multi-value cookies work exactly the same way as what you are doing in django using a separator They have just abstracted that away for you What you are doing is fine and proper and I do not think Django has anything specific to 'solve' this problem I will say that you are doing the right thing in not using multiple cookies Keep the over-the-wire overhead down by doing what you are doing
Perl or Python script to remove user from group I am putting together a Samba-based server as a Primary Domain Controller and ran into a cute little problem that should have been solved many times over But a number of searches did not yield a result I need to be able to remove an existing user from an existing group with a command line script It appears that the usermod easily allows me to add a user to a supplementary group with this command: ````usermod -a -G supgroup1 supgroup2 username ```` Without the "-a" option if the user is currently a member of a group which is not listed the user will be removed from the group Does anyone have a perl (or Python) script that allows the specification of a user and group for removal? Am I missing an obvious existing command or well-known solution forthis? Thanks in advance! Thanks to J J for the pointer to the Unix::Group module which is part of Unix-ConfigFile It looks like the command deluser would do what I want but was not in any of my existing repositories I went ahead and wrote the perl script using the Unix:Group Module Here is the script for your sysadmining pleasure ````#!/usr/bin/perl # # Usage: removegroup pl login group # Purpose: Removes a user from a group while retaining current primary and # supplementary groups # Notes: There is a Debian specific utility that can do this called deluser # but I did not want any cross-distribution dependencies # # Date: 25 September 2008 # Validate Arguments (correct number format etc ) if ( ($#ARGV < 1) || (2 < $#ARGV) ) { print "\nUsage: removegroup pl login group\n\n"; print "EXIT VALUES\n"; print " The removeuser pl script exits with the following values:\n\n"; print " 0 success\n\n"; print " 1 Invalid number of arguments\n\n"; print " 2 Login or Group name supplied greater than 16 characters\n\n"; print " 3 Login and/or Group name contains invalid characters\n\n"; exit 1; } # Check for well formed group and login names if ((16 < length($ARGV[0])) ||(16 < length($ARGV[1]))) { print "Usage: removegroup pl login group\n"; print "ERROR: Login and Group names must be less than 16 Characters\n"; exit 2; } if ( ( $ARGV[0] !~ m{^[a-z_]+[a-z0-9_-]*$}) || ( $ARGV[0] !~ m{^[a-z_]+[a-z0-9_-]*$} ) ) { print "Usage: removegroup pl login group\n"; print "ERROR: Login and/or Group name contains invalid characters\n"; exit 3; } # Set some variables for readability $login=$ARGV[0]; $group=$ARGV[1]; # Requires the GroupFile interface from perl-Unix-Configfile use Unix::GroupFile; $grp = new Unix::GroupFile "/etc/group"; $grp>remove_user("$group" "$login"); $grp>commit(); undef $grp; exit 0; ````
It looks like <them>deluser --group [groupname]</them> should do it If not the <them>groups</them> command lists the groups that a user belongs to It should be fairly straightforward to come up with some Perl to capture that list into an array (or <them>map</them> it into a hash) delete the unwanted group(s) and feed that back to <them>usermod</them>
Generic Exception Handling in Python the "Right Way" Sometimes I find myself in the situation where I want to execute several sequential commands like such: ````try: foo(a b) except Exception e: baz(e) try: bar(c d) except Exception e: baz(e) ```` This same pattern occurs when exceptions simply need to be ignored This feels redundant and the excessive syntax causes it to be surprisingly difficult to follow when reading code In C I would have solved this type of problem easily with a macro but unfortunately this cannot be done in straight python Question: How can I best reduce the code footprint and increase code readability when coming across this pattern?
If they are simple one-line commands you can wrap them in `lambda`s: ````for cmd in [ (lambda: foo (a b)) (lambda: bar (c d)) ]: try: cmd () except StandardError e: baz (e) ```` You could wrap that whole thing up in a function so it looked like this: ````ignore_errors (baz [ (lambda: foo (a b)) (lambda: bar (c d)) ]) ````
How do you test that a Python function throws an exception? How does one write a unittest that fails only if a function does not throw an expected exception?
Have a look at the <a href="https://docs python org/2/library/unittest html#unittest TestCase assertRaises" rel="nofollow">assertRaises</a> method of the `unittest` module
Is there an inverse function for time gmtime() that parses a UTC tuple to seconds since the epoch? python's time module seems a little haphazard For example here is a list of methods in there from the docstring: ````time() -- return current time in seconds since the Epoch as a float clock() -- return CPU time since process start as a float sleep() -- delay for a number of seconds given as a float gmtime() -- convert seconds since Epoch to UTC tuple localtime() -- convert seconds since Epoch to local time tuple asctime() -- convert time tuple to string ctime() -- convert time in seconds to string mktime() -- convert local time tuple to seconds since Epoch strftime() -- convert time tuple to string according to format specification strptime() -- parse string to time tuple according to format specification tzset() -- change the local timezone ```` Looking at localtime() and its inverse mktime() why is there no inverse for gmtime() ? Bonus questions: what would you name the method ? How would you implement it ?
I always thought the time and datetime modules were a little incoherent Anyways here is the inverse of mktime ````import time def mkgmtime(t): """Convert UTC tuple to seconds since Epoch""" return time mktime(t)-time timezone ````
Getting Python to use the ActiveTcl libraries Is there any way to get Python to use my ActiveTcl installation instead of having to copy the ActiveTcl libraries into the Python/tcl directory?
Not familiar with ActiveTcl but in general here is how to get a package/module to be loaded when that name already exists in the standard library: ````import sys dir_name="/usr/lib/mydir" sys path insert(0 dir_name) ```` Substitute the value for dir_name with the path to the directory containing your package/module and run the above code before anything is imported This is often done through a 'sitecustomize py' file so that it will take effect as soon as the interpreter starts up so you will not need to worry about import ordering
How do I efficiently filter computed values within a Python list comprehension? The Python list comprehension syntax makes it easy to filter values within a comprehension For example: ````result = [x**2 for x in mylist if type(x) is int] ```` Will return a list of the squares of integers in mylist However what if the test involves some (costly) computation and you want to filter on the result? One option is: ````result = [expensive(x) for x in mylist if expensive(x)] ```` This will result in a list of non-"false" expensive(x) values however expensive() is called twice for each x Is there a comprehension syntax that allows you to do this test while only calling expensive once per x?
Came up with my own answer after a minute of thought It can be done with nested comprehensions: ````result = [y for y in (expensive(x) for x in mylist) if y] ```` I guess that works though I find nested comprehensions are only marginally readable
Python Date Comparisons I would like to find out if a particular python datetime object is older than X hours or minutes I am trying to do something similar to: ````if (datetime now() - self timestamp) &gt; 100 # Where 100 is either seconds or minutes ```` This generates a type error What is the proper way to do date time comparison in python? I already looked at <a href="http://wiki python org/moin/WorkingWithTime">WorkingWithTime</a> which is close but not exactly what I want I assume I just want the datetime object represented in seconds so that I can do a normal int comparison Please post lists of datetime best practices
You can subtract two <a href="http://docs python org/lib/module-datetime html" rel="nofollow">datetime</a> objects to find the difference between them <br /> You can use `datetime fromtimestamp` to parse a POSIX time stamp
How to pass all Visual Studio 2008 "Macros" to Python script? <them>[NOTE: This questions is similar to but <strong>not the same</strong> as <a href="http://stackoverflow com/questions/128634/how-to-use-system-environment-variables-in-vs-2008-post-build-events">this one</a> ]</them> Visual Studio defines several dozen "Macros" which are sort of simulated environment variables (completely unrelated to C++ macros) which contain information about the build in progress Examples: ``` ConfigurationName Release TargetPath D:\work\foo\win\Release\foo exe VCInstallDir C:\ProgramFiles\Microsoft Visual Studio 9 0\VC\ ``` Here is the complete set of 43 built-in Macros that I see (yours may differ depending on which version of VS you use and which tools you have enabled): ``` ConfigurationName IntDir RootNamespace TargetFileName DevEnvDir OutDir SafeInputName TargetFramework FrameworkDir ParentName SafeParentName TargetName FrameworkSDKDir PlatformName SafeRootNamespace TargetPath FrameworkVersion ProjectDir SolutionDir VCInstallDir FxCopDir ProjectExt SolutionExt VSInstallDir InputDir ProjectFileName SolutionFileName WebDeployPath InputExt ProjectName SolutionName WebDeployRoot InputFileName ProjectPath SolutionPath WindowsSdkDir InputName References TargetDir WindowsSdkDirIA64 InputPath RemoteMachine TargetExt ``` Of these only four (`FrameworkDir` `FrameworkSDKDir` `VCInstallDir` and `VSInstallDir`) are set in the environment used for build-events As Brian mentions user-defined Macros can be defined such as to be set in the environment in which build tasks execute My problem is with the built-in Macros I use a Visual Studio Post-Build Event to run a python script as part of my build process I would like to pass the entire set of Macros (built-in and user-defined) to my script in the environment but I do not know how Within my script I can access regular environment variables (e g Path SystemRoot) but NOT these "Macros" All I can do now is pass them on-by-one as named options which I then process within my script For example this is what my Post-Build Event command line looks like: ``` postbuild py --t="$(TargetPath)" --c="$(ConfigurationName)" ``` Besides being a pain in the neck there is a limit on the size of Post-Build Event command line so I cannot pass dozens Macros using this method even if I wanted to because the command line is truncated Does anyone know if there is a way to pass the entire set of Macro names and values to a command that does NOT require switching to MSBuild (which I believe is not available for native VC++) or some other make-like build tool?
This is a bit hacky but it could work Why not call multiple py scripts in a row? Each scripts can pass in a small subset of the parameters and the values to a temp text file The final script will read and work off of the temp text file I agree that this method is filled with danger and WTF's but sometimes you have to just hack stuff together
Request UAC elevation from within a Python script? I want my Python script to copy files on Vista When I run it from a normal `cmd exe` window no errors are generated yet the files are NOT copied If I run `cmd exe` "as administator" and then run my script it works fine This makes sense since User Account Control (UAC) normally prevents many file system actions Is there a way I can from within a Python script invoke a UAC elevation request (those dialogs that say something like "such and such app needs admin access is this OK?") If that is not possible is there a way my script can at least detect that it is not elevated so it can fail gracefully?
It seems there is no way to elevate the application privileges for a while for you to perform a particular task Windows needs to know at the start of the program whether the application requires certain privileges and will ask the user to confirm when the application performs any tasks that <them>need</them> those privileges There are two ways to do this: - Write a manifest file that tells Windows the application might require some privileges - Run the application with elevated privileges from inside another program This <a href="http://www codeproject com/KB/vista-security/UAC__The_Definitive_Guide aspx">two</a> <a href="http://msdn microsoft com/en-gb/magazine/cc163486 aspx">articles</a> explain in much more detail how this works What I would do if you do not want to write a nasty ctypes wrapper for the CreateElevatedProcess API is use the ShellExecuteEx trick explained in the Code Project article (Pywin32 comes with a wrapper for ShellExecute) How? Something like this: When your program starts it checks if it has Administrator privileges if it does not it runs itself using the ShellExecute trick and exits immediately if it does it performs the task at hand As you describe your program as a "script" I suppose that is enough for your needs Cheers
Style - When to serialize a Django model Instance: signals vs model's save method I plan to serialize a Django model to XML when it is saved or updated (The XML's going to be imported into a flash movie) Is it better to listen for a post_save() or pre_save() signal and then perform the serialization or to just handle it in the model's save() methon
Post save That way the new data (the reason for performing the serialization) is already in the database It will make for a much cleaner bit of code that simply takes from the database and does not have to worry about adding an extra value The other way that comes to mind is to maintain the xml file in parallel to the database That is to say in your save() add the data to the database and to the xml file This would have a much less overhead if you are dealing with huge tables
Do I have to cause an ValueError in Python I have this code: ````chars = #some list try: indx = chars index(chars) except ValueError: #doSomething else: #doSomethingElse ```` I want to be able to do this because I do not like knowfully causing Exceptions: ````chars = #some list indx = chars index(chars) if indx == -1: #doSomething else: #doSomethingElse ```` Is there a way I can do this?
````if element in mylist: index = mylist index(element) # do something else: # do something else ````
Showing the stack trace from a running Python application I have this Python application that gets stuck from time to time and I cannot find out where Is there any way to signal Python interpreter to show you the exact code that is running? Some kind of on-the-fly stacktrace? <strong><them>Related questions:</them></strong> - <a href="http://stackoverflow com/questions/1156023/print-current-call-stack-from-a-method-in-python-code">Print current call stack from a method in Python code</a> - <a href="http://stackoverflow com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py">Check what a running process is doing: print stack trace of an uninstrumented Python program</a>
<them>python -dv yourscript py</them> That will make the interpreter to run in debug mode and to give you a trace of what the interpreter is doing If you want to interactively debug the code you should run it like this: <them>python -m pdb yourscript py</them> That tells the python interpreter to run your script with the module "pdb" which is the python debugger if you run it like that the interpreter will be executed in interactive mode much like GDB
Translate algorithmic C to Python I would like to translate some C code to Python code or bytecode The C code in question is what i would call purely algorithmic: platform independent no I/O just algorithms and in-memory data structures An example would be a regular expression library Translation tool would process library source code and produce a functionally equivalent Python module that can be run in a <strong>sandboxed</strong> environment What specific approaches tools and techniques can you recommend? <hr /> <them>Note: Python C extension or ctypes is <strong>not an option</strong> because the environment is sandboxed </them> <them>Another note</them>: looks like there is a <a href="http://www axiomsol com/" rel="nofollow">C-to-Java-bytecode compiler</a> they even compiled libjpeg to Java Is Java bytecode+VM too different from CPython bytecode+VM?
Why not keeping the C code and <a href="http://www python org/doc/ext/intro html" rel="nofollow">creating a Python C module</a> which can be imported into a running Python environment?
Regex to remove conditional comments I want a regex which can match conditional comments in a HTML source page so I can remove only those I want to preserve the regular comments I would also like to avoid using the *? notation if possible The text is ````foo <!--[if IE]&gt; <style type="text/css"&gt; ul menu ul li{ font-size: 10px; font-weight:normal; padding-top:0px; } </style&gt; <![endif]-> bar ```` and I want to remove everything in `<!--[if IE]&gt;` and `<![endif]->` <strong>EDIT:</strong> It is because of BeautifulSoup I want to remove these tags BeautifulSoup fails to parse and gives an incomplete source <strong>EDIT2:</strong> [if IE] is not the only condition There are lots more and I do not have any list of all possible combinations <strong>EDIT3:</strong> Vinko Vrsalovic's solution works but the actual problem why beautifulsoup failed was because of a rogue comment within the conditional comment Like ````<!--[if lt IE 7 ]&gt; <script defer type="text/javascript" src="pngfix_253168 js"&gt;</script&gt;<!--png fix for IE-> <![endif]-> ```` Notice the `<!--png fix for IE->` comment? Though my problem was solve I would love to get a regex solution for this
Do not use a regular expression for this You will get confused about comments containing opening tags and what not and do the wrong thing HTML is not regular and trying to modify it with a single regular expression will fail Use a HTML parser for this BeautifulSoup is a good easy flexible and sturdy one that is able to handle real-world (meaning hopelessly broken) HTML With it you can just look up all comment nodes examine their content (you can use a regular expression for <them>that</them> if you wish) and remove them if they need to be removed
Is there a difference between `==` and `is` in Python? My <a href="http://en wiktionary org/wiki/Google-fu">Google-fu</a> has failed me In Python are the following two tests for equality equivalent (ha!)? ````n = 5 # Test one if n == 5: print 'Yay!' # Test two if n is 5: print 'Yay!' ```` Does this hold true for objects where you would be comparing instances (a `list` say)? Okay so this kind of answers my question: ````L = [] L append(1) if L == [1]: print 'Yay!' # Holds true but if L is [1]: print 'Yay!' # Does not ```` So `==` tests value where `is` tests to see if they are the same object?
== determines if the values are equivalent while "is" determines if they are the exact same object
Running subversion under apache and mod_python My Apache server runs on some non-default (not-root) account When it tries to run a python script which in turn executes a subversion check-out command 'svn checkout' fails with the following error message: ````svn: Cannot open file '/root/ subversion/servers': Permission denied ```` At the same time running that python script with subversion checkout command inside from command line under the same user account goes on perfectly well Apache server 2 2 6 with mod_python 3 2 8 runs on Fedora Core 6 machine Can anybody help me out? Thanks a lot
Try granting the Apache user (the user that the apache service is running under) r+w permissions on that file
Concurrent Access to RRD (RRDTool) I am using RRDTool (<a href="http://oss oetiker ch/rrdtool/" rel="nofollow">http://oss oetiker ch/rrdtool/</a>) as a graphing back-end for storing performance metrics This is done via the RRDTool CLI from a Python script My problem is that the script is multithreaded and each thread updates the RRD at a pretty rapid pace Sometimes an update fails because one thread is accessing the RRD file while another one tries to access it also I was under the impression that this is OK to try since RRDTool uses its own locking mechanism but I guess that is not true Does anyone have a good approach for concurrent access to an RRD? I can think of a few ways to go: - have 1 thread create a queue and only feed the RRD from a single thread - create my own locking mechanism inside the Python script (how would I do this?) got anything better or have you run into this issue before?
An exclusive lock ought to be enough for this problem : - <a href="http://docs python org/lib/lock-objects html" rel="nofollow">Python doc page</a> - <a href="http://effbot org/zone/thread-synchronization htm" rel="nofollow">Use example</a> Define your lock object at the main level not at the thread level and you are done Edit in Response to comment : if you define your lock (`lock = new Lock()`) at the thread level you will have one lock object per running thread and you really want a single lock for the file rrdtool updates so this definition must be at the main level