title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Sanitising user input using Python
16,861
46
2008-08-19T20:18:31Z
25,136
23
2008-08-24T16:08:37Z
[ "python", "xss" ]
What's the best way to sanitise user input for a Python-based web application? Is there a single function to remove HTML characters and any other necessary characters combinations to prevent an [XSS](http://en.wikipedia.org/wiki/Cross-site_scripting) or SQL injection attack?
Here is a snippet that will remove all tags not on the white list, and all tag attributes not on the attribues whitelist (so you can't use `onclick`). It is a modified version of <http://www.djangosnippets.org/snippets/205/>, with the regex on the attribute values to prevent people from using `href="javascript:..."`, and other cases described at <http://ha.ckers.org/xss.html>. (e.g. `<a href="ja&#x09;vascript:alert('hi')">` or `<a href="ja vascript:alert('hi')">`, etc.) As you can see, it uses the (awesome) [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) library. ``` import re from urlparse import urljoin from BeautifulSoup import BeautifulSoup, Comment def sanitizeHtml(value, base_url=None): rjs = r'[\s]*(&#x.{1,7})?'.join(list('javascript:')) rvb = r'[\s]*(&#x.{1,7})?'.join(list('vbscript:')) re_scripts = re.compile('(%s)|(%s)' % (rjs, rvb), re.IGNORECASE) validTags = 'p i strong b u a h1 h2 h3 pre br img'.split() validAttrs = 'href src width height'.split() urlAttrs = 'href src'.split() # Attributes which should have a URL soup = BeautifulSoup(value) for comment in soup.findAll(text=lambda text: isinstance(text, Comment)): # Get rid of comments comment.extract() for tag in soup.findAll(True): if tag.name not in validTags: tag.hidden = True attrs = tag.attrs tag.attrs = [] for attr, val in attrs: if attr in validAttrs: val = re_scripts.sub('', val) # Remove scripts (vbs & js) if attr in urlAttrs: val = urljoin(base_url, val) # Calculate the absolute url tag.attrs.append((attr, val)) return soup.renderContents().decode('utf8') ``` As the other posters have said, pretty much all Python db libraries take care of SQL injection, so this should pretty much cover you.
Sanitising user input using Python
16,861
46
2008-08-19T20:18:31Z
93,857
12
2008-09-18T15:56:09Z
[ "python", "xss" ]
What's the best way to sanitise user input for a Python-based web application? Is there a single function to remove HTML characters and any other necessary characters combinations to prevent an [XSS](http://en.wikipedia.org/wiki/Cross-site_scripting) or SQL injection attack?
The best way to prevent XSS is not to try and filter everything, but rather to simply do HTML Entity encoding. For example, automatically turn < into &lt;. This is the ideal solution assuming you don't need to accept any html input (outside of forum/comment areas where it is used as markup, it should be pretty rare to need to accept HTML); there are so many permutations via alternate encodings that anything but an ultra-restrictive whitelist (a-z,A-Z,0-9 for example) is going to let something through. SQL Injection, contrary to other opinion, is still possible, if you are just building out a query string. For example, if you are just concatenating an incoming parameter onto a query string, you will have SQL Injection. The best way to protect against this is also not filtering, but rather to religiously use parameterized queries and NEVER concatenate user input. This is not to say that filtering isn't still a best practice, but in terms of SQL Injection and XSS, you will be far more protected if you religiously use Parameterize Queries and HTML Entity Encoding.
Sanitising user input using Python
16,861
46
2008-08-19T20:18:31Z
248,933
18
2008-10-30T00:41:40Z
[ "python", "xss" ]
What's the best way to sanitise user input for a Python-based web application? Is there a single function to remove HTML characters and any other necessary characters combinations to prevent an [XSS](http://en.wikipedia.org/wiki/Cross-site_scripting) or SQL injection attack?
**Edit**: [bleach](https://github.com/jsocol/bleach) is a wrapper around html5lib which makes it even easier to use as a whitelist-based sanitiser. [`html5lib`](http://code.google.com/p/html5lib/) comes with a whitelist-based HTML sanitiser - it's easy to subclass it to restrict the tags and attributes users are allowed to use on your site, and it even attempts to sanitise CSS if you're allowing use of the `style` attribute. Here's now I'm using it in my Stack Overflow clone's `sanitize_html` utility function: <http://code.google.com/p/soclone/source/browse/trunk/soclone/utils/html.py> I've thrown all the attacks listed in [ha.ckers.org's XSS Cheatsheet](http://ha.ckers.org/xss.html) (which are handily [available in XML format](http://ha.ckers.org/xssAttacks.xml) at it after performing Markdown to HTML conversion using [python-markdown2](http://code.google.com/p/python-markdown2/) and it seems to have held up ok. The WMD editor component which Stackoverflow currently uses is a problem, though - I actually had to disable JavaScript in order to test the XSS Cheatsheet attacks, as pasting them all into WMD ended up giving me alert boxes and blanking out the page.
Create an encrypted ZIP file in Python
17,250
24
2008-08-20T00:16:40Z
16,050,005
13
2013-04-17T01:39:00Z
[ "python", "zip" ]
I'm creating an ZIP file with ZipFile in Python 2.5, it works ok so far: ``` import zipfile, os locfile = "test.txt" loczip = os.path.splitext (locfile)[0] + ".zip" zip = zipfile.ZipFile (loczip, "w") zip.write (locfile) zip.close() ``` but I couldn't find how to encrypt the files in the ZIP file. I could use system and call PKZIP -s, but I suppose there must be a more "Pythonic" way. I'm looking for an open source solution.
I created a simple library to create a password encrypted zip file in python. - [**here**](https://github.com/smihica/pyminizip) ``` import pyminizip compression_level = 5 # 1-9 pyminizip.compress("src.txt", "dst.zip", "password", compression_level) ``` **The library requires zlib.** I have checked that the file can be extracted in WINDOWS/MAC.
What's the best way to distribute python command-line tools?
17,893
36
2008-08-20T13:07:25Z
17,933
33
2008-08-20T13:25:23Z
[ "python", "command-line", "packaging" ]
My current setup.py script works okay, but it installs tvnamer.py (the tool) as "tvnamer.py" into site-packages or somewhere similar.. Can I make setup.py install tvnamer.py as tvnamer, and/or is there a better way of installing command-line applications?
Try the `entry_points.console_scripts` parameter in the setup() call. As described in the [setuptools docs](http://peak.telecommunity.com/DevCenter/setuptools#automatic-script-creation), this should do what I think you want. To reproduce here: ``` from setuptools import setup setup( # other arguments here... entry_points = { 'console_scripts': [ 'foo = package.module:func', 'bar = othermodule:somefunc', ], } ) ```
Build a Basic Python Iterator
19,151
321
2008-08-21T00:36:11Z
19,152
90
2008-08-21T00:36:33Z
[ "python", "object", "iterator" ]
How would one create an iterative function (or iterator object) in python?
First of all the [itertools module](https://docs.python.org/3/library/itertools.html) is incredibly useful for all sorts of cases in which an iterator would be useful, but here is all you need to create an iterator in python: > yield Isn't that cool? Yield can be used to replace a normal **return** in a function. It returns the object just the same, but instead of destroying state and exiting, it saves state for when you want to execute the next iteration. Here is an example of it in action pulled directly from the [itertools function list](http://docs.python.org/lib/itertools-functions.html): ``` def count(n=0): while True: yield n n += 1 ``` As stated in the functions description (it's the **count()** function from the itertools module...) , it produces an iterator that returns consecutive integers starting with n. [Generator expressions](https://docs.python.org/2/reference/expressions.html#generator-expressions) are a whole other can of worms (awesome worms!). They may be used in place of a [List Comprehension](http://www.secnetix.de/olli/Python/list_comprehensions.hawk) to save memory (list comprehensions create a list in memory that is destroyed after use if not assigned to a variable, but generator expressions can create a Generator Object... which is a fancy way of saying Iterator). Here is an example of a generator expression definition: ``` gen = (n for n in xrange(0,11)) ``` This is very similar to our iterator definition above except the full range is predetermined to be between 0 and 10. I just found **xrange()** (suprised I hadn't seen it before...) and added it to the above example. **xrange()** is an iterable version of **range()** which has the advantage of not prebuilding the list. It would be very useful if you had a giant corpus of data to iterate over and only had so much memory to do it in.
Build a Basic Python Iterator
19,151
321
2008-08-21T00:36:11Z
24,377
374
2008-08-23T16:57:28Z
[ "python", "object", "iterator" ]
How would one create an iterative function (or iterator object) in python?
Iterator objects in python conform to the iterator protocol, which basically means they provide two methods: `__iter__()` and `next()`. The `__iter__` returns the iterator object and is implicitly called at the start of loops. The `next()` method returns the next value and is implicitly called at each loop increment. `next()` raises a StopIteration exception when there are no more value to return, which is implicitly captured by looping constructs to stop iterating. Here's a simple example of a counter: ``` class Counter: def __init__(self, low, high): self.current = low self.high = high def __iter__(self): return self def next(self): # Python 3: def __next__(self) if self.current > self.high: raise StopIteration else: self.current += 1 return self.current - 1 for c in Counter(3, 8): print c ``` This will print: ``` 3 4 5 6 7 8 ``` This is easier to write using a generator, as covered in a previous answer: ``` def counter(low, high): current = low while current <= high: yield current current += 1 for c in counter(3, 8): print c ``` The printed output will be the same. Under the hood, the generator object supports the iterator protocol and does something roughly similar to the class Counter. David Mertz's article, [Iterators and Simple Generators](https://www.ibm.com/developerworks/library/l-pycon/), is a pretty good introduction.
Build a Basic Python Iterator
19,151
321
2008-08-21T00:36:11Z
7,542,261
202
2011-09-24T22:13:44Z
[ "python", "object", "iterator" ]
How would one create an iterative function (or iterator object) in python?
There are four ways to build an iterative function: * create a generator (uses the [yield keyword](http://docs.python.org/py3k/reference/expressions.html#yield-expressions)) * use a generator expression ([genexp](http://docs.python.org/py3k/reference/expressions.html#generator-expressions)) * create an iterator (defines [`__iter__` and `__next__`](http://docs.python.org/py3k/library/stdtypes.html?highlight=__iter__#iterator-types) (or `next` in Python 2.x)) * create a function that Python can iterate over on its own ([defines `__getitem__`](http://docs.python.org/py3k/reference/datamodel.html?highlight=__getitem__#object.__getitem__)) Examples: ``` # generator def uc_gen(text): for char in text: yield char.upper() # generator expression def uc_genexp(text): return (char.upper() for char in text) # iterator protocol class uc_iter(): def __init__(self, text): self.text = text self.index = 0 def __iter__(self): return self def __next__(self): try: result = self.text[self.index].upper() except IndexError: raise StopIteration self.index += 1 return result # getitem method class uc_getitem(): def __init__(self, text): self.text = text def __getitem__(self, index): result = self.text[index].upper() return result ``` To see all four methods in action: ``` for iterator in uc_gen, uc_genexp, uc_iter, uc_getitem: for ch in iterator('abcde'): print ch, print ``` Which results in: ``` A B C D E A B C D E A B C D E A B C D E ``` **Note**: The two generator types (`uc_gen` and `uc_genexp`) cannot be `reversed()`; the plain iterator (`uc_iter`) would need the `__reversed__` magic method (which must return a new iterator that goes backwards); and the getitem iteratable (`uc_getitem`) must have the `__len__` magic method: ``` # for uc_iter def __reversed__(self): return reversed(self.text) # for uc_getitem def __len__(self) return len(self.text) ``` --- To answer Colonel Panic's secondary question about an infinite lazily evaluated iterator, here are those examples, using each of the four methods above: ``` # generator def even_gen(): result = 0 while True: yield result result += 2 # generator expression def even_genexp(): return (num for num in even_gen()) # or even_iter or even_getitem # not much value under these circumstances # iterator protocol class even_iter(): def __init__(self): self.value = 0 def __iter__(self): return self def __next__(self): next_value = self.value self.value += 2 return next_value # getitem method class even_getitem(): def __getitem__(self, index): return index * 2 import random for iterator in even_gen, even_genexp, even_iter, even_getitem: limit = random.randint(15, 30) count = 0 for even in iterator(): print even, count += 1 if count >= limit: break print ``` Which results in (at least for my sample run): ``` 0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 ```
Build a Basic Python Iterator
19,151
321
2008-08-21T00:36:11Z
11,690,539
52
2012-07-27T15:05:12Z
[ "python", "object", "iterator" ]
How would one create an iterative function (or iterator object) in python?
I see some of you doing `return self` in `__iter__`. I just wanted to note that `__iter__` itself can be a generator (thus removing the need for `__next__` and raising `StopIteration` exceptions) ``` class range: def __init__(self,a,b): self.a = a self.b = b def __iter__(self): i = self.a while i < self.b: yield i i+=1 ``` Of course here one might as well directly make a generator, but for more complex classes it can be useful.
A Transpose/Unzip Function in Python (inverse of zip)
19,339
241
2008-08-21T04:29:07Z
19,343
397
2008-08-21T04:36:29Z
[ "python", "list", "matrix", "unzip", "transpose" ]
I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item. **For example:** ``` original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] # and I want to become... result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4]) ``` Is there a builtin function that does that?
[`zip`](http://docs.python.org/library/functions.html#zip) is its own inverse! Provided you use the special \* operator. ``` >>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)]) [('a', 'b', 'c', 'd'), (1, 2, 3, 4)] ``` The way this works is by calling `zip` with the arguments: ``` zip(('a', 1), ('b', 2), ('c', 3), ('d', 4)) ``` … except the arguments are passed to `zip` directly (after being converted to a tuple), so there's no need to worry about the number of arguments getting too big.
A Transpose/Unzip Function in Python (inverse of zip)
19,339
241
2008-08-21T04:29:07Z
25,193
17
2008-08-24T17:07:57Z
[ "python", "list", "matrix", "unzip", "transpose" ]
I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item. **For example:** ``` original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] # and I want to become... result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4]) ``` Is there a builtin function that does that?
You could also do ``` result = ([ a for a,b in original ], [ b for a,b in original ]) ``` It *should* scale better. Especially if Python makes good on not expanding the list comprehensions unless needed. (Incidentally, it makes a 2-tuple (pair) of lists, rather than a list of tuples, like `zip` does.) If generators instead of actual lists are ok, this would do that: ``` result = (( a for a,b in original ), ( b for a,b in original )) ``` The generators don't munch through the list until you ask for each element, but on the other hand, they do keep references to the original list.
A Transpose/Unzip Function in Python (inverse of zip)
19,339
241
2008-08-21T04:29:07Z
4,578,299
14
2011-01-02T12:14:17Z
[ "python", "list", "matrix", "unzip", "transpose" ]
I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item. **For example:** ``` original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] # and I want to become... result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4]) ``` Is there a builtin function that does that?
If you have lists that are not the same length, you may not want to use zip as per Patricks answer. This works: ``` >>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)]) [('a', 'b', 'c', 'd'), (1, 2, 3, 4)] ``` But with different length lists, zip truncates each item to the length of the shortest list: ``` >>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', )]) [('a', 'b', 'c', 'd', 'e')] ``` You can use map with no function to fill empty results with None: ``` >>> map(None, *[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', )]) [('a', 'b', 'c', 'd', 'e'), (1, 2, 3, 4, None)] ``` zip() is marginally faster though.
A Transpose/Unzip Function in Python (inverse of zip)
19,339
241
2008-08-21T04:29:07Z
22,115,957
7
2014-03-01T15:00:15Z
[ "python", "list", "matrix", "unzip", "transpose" ]
I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item. **For example:** ``` original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] # and I want to become... result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4]) ``` Is there a builtin function that does that?
I like to use `zip(*iterable)` (which is the piece of code you're looking for) in my programs as so: ``` def unzip(iterable): return zip(*iterable) ``` I find `unzip` more readable.
Introducing Python
19,654
5
2008-08-21T11:48:03Z
19,715
13
2008-08-21T12:25:21Z
[ "php", "python" ]
The company I used to work with has two developers working fulltime, and a handful of freelancers. They're in the process of hiring a new lead developer to try to bring order and management to the development. But, currently, one of the developers has seen the light of Django (the company has only developed in PHP to date) while the other developer is concerned that introducing a new language (Python) is a bad idea right now. How should they approach introducing this new technology? Obviously with only one of the developers actually knowing Python, there will be no redundancy when that dev is away or leaves the company. Should they bother to introduce Python, or should they look for PHP-only solutions until such a time when the team actually have more than one Pythonion? Without a team leader, the decisions are having to fall to them.
I recently introduced Python to my company, which does consulting work for the Post Office. I did this by waiting until there was a project for which I would be the only programmer, then getting permission to do this new project in Python. I then did another small project in Python with similarly impressive results. In addition, I used Python for all of my small throwaway assignments ("can you parse the stats in these files into a CSV file organized by date and site?", etc) and had a quick turnaround time on all of them. I also evangelized Python a bit; I went out of my way to NOT be obnoxious about it, but I'd occasionally describe why I liked it so much, talked about the personal projects I use it for in my free time and why it's awesome for me, etc. Eventually we started another project and I convinced everyone to use Python for it. I took care to point everyone to a lot of documentation, including the specific webpages relating to what they were working on, and every time they had a question, I'd explain how to do things properly by explaining the Pythonic approach to things, etc. This has worked really well. However, this might be somewhat different than what you're describing. In my case I started with moderately small projects and Python is only being used for new projects. Also, none of my co-workers were really Perl or PHP gurus; they all knew those languages and had been using them for awhile, but it didn't take much effort for them to become more productive in Python than they'd been before. So if you're talking about new projects with people who currently use PHP but aren't super-experts and don't love that language, then I think switching to Python is a no-brainer. However, if you're talking about working with a large existing PHP code base with a lot of very experienced PHP programmers who are happy with their current setup, then switching languages is probably not a good idea. You're probably somewhere in between, so you'll have to weigh the tradeoffs; hopefully my answer will help you do that.
What's the best way to grab/parse command line arguments passed to a Python script?
20,063
84
2008-08-21T14:24:41Z
20,065
13
2008-08-21T14:25:19Z
[ "python", "command-line", "command-line-arguments" ]
What's the **easiest, tersest, and most flexible** method or library for parsing Python command line arguments?
Use `optparse` which comes with the standard library. For example: ``` #!/usr/bin/env python import optparse def main(): p = optparse.OptionParser() p.add_option('--person', '-p', default="world") options, arguments = p.parse_args() print 'Hello %s' % options.person if __name__ == '__main__': main() ``` Source: [Using Python to create UNIX command line tools](http://www.ibm.com/developerworks/aix/library/au-pythocli/) However as of Python 2.7 optparse is deprecated, see: [Why use argparse rather than optparse?](http://stackoverflow.com/q/3217673/55075)
What's the best way to grab/parse command line arguments passed to a Python script?
20,063
84
2008-08-21T14:24:41Z
20,069
14
2008-08-21T14:26:57Z
[ "python", "command-line", "command-line-arguments" ]
What's the **easiest, tersest, and most flexible** method or library for parsing Python command line arguments?
Pretty much everybody is using [getopt](http://python.active-venture.com/lib/module-getopt.html) Here is the example code for the doc : ``` import getopt, sys def main(): try: opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="]) except getopt.GetoptError: # print help information and exit: usage() sys.exit(2) output = None verbose = False for o, a in opts: if o == "-v": verbose = True if o in ("-h", "--help"): usage() sys.exit() if o in ("-o", "--output"): output = a ``` So in a word, here is how it works. You've got two types of options. Those who are receiving arguments, and those who are just like switches. `sys.argv` is pretty much your `char** argv` in C. Like in C you skip the first element which is the name of your program and parse only the arguments : `sys.argv[1:]` `Getopt.getopt` will parse it according to the rule you give in argument. `"ho:v"` here describes the short arguments : `-ONELETTER`. The `:` means that `-o` accepts one argument. Finally `["help", "output="]` describes long arguments ( `--MORETHANONELETTER` ). The `=` after output once again means that output accepts one arguments. The result is a list of couple (option,argument) If an option doesn't accept any argument (like `--help` here) the `arg` part is an empty string. You then usually want to loop on this list and test the option name as in the example. I hope this helped you.
What's the best way to grab/parse command line arguments passed to a Python script?
20,063
84
2008-08-21T14:24:41Z
26,910
85
2008-08-25T21:11:03Z
[ "python", "command-line", "command-line-arguments" ]
What's the **easiest, tersest, and most flexible** method or library for parsing Python command line arguments?
**This answer suggests `optparse` which is appropriate for older Python versions. For Python 2.7 and above, `argparse` replaces `optparse`. See [this answer](http://stackoverflow.com/questions/3217673/why-use-argparse-rather-than-optparse) for more information.** As other people pointed out, you are better off going with optparse over getopt. getopt is pretty much a one-to-one mapping of the standard getopt(3) C library functions, and not very easy to use. optparse, while being a bit more verbose, is much better structured and simpler to extend later on. Here's a typical line to add an option to your parser: ``` parser.add_option('-q', '--query', action="store", dest="query", help="query string", default="spam") ``` It pretty much speaks for itself; at processing time, it will accept -q or --query as options, store the argument in an attribute called query and has a default value if you don't specify it. It is also self-documenting in that you declare the help argument (which will be used when run with -h/--help) right there with the option. Usually you parse your arguments with: ``` options, args = parser.parse_args() ``` This will, by default, parse the standard arguments passed to the script (sys.argv[1:]) options.query will then be set to the value you passed to the script. You create a parser simply by doing ``` parser = optparse.OptionParser() ``` These are all the basics you need. Here's a complete Python script that shows this: ``` import optparse parser = optparse.OptionParser() parser.add_option('-q', '--query', action="store", dest="query", help="query string", default="spam") options, args = parser.parse_args() print 'Query string:', options.query ``` 5 lines of python that show you the basics. Save it in sample.py, and run it once with ``` python sample.py ``` and once with ``` python sample.py --query myquery ``` Beyond that, you will find that optparse is very easy to extend. In one of my projects, I created a Command class which allows you to nest subcommands in a command tree easily. It uses optparse heavily to chain commands together. It's not something I can easily explain in a few lines, but feel free to [browse around in my repository](https://thomas.apestaart.org/moap/trac/browser/trunk/moap/extern/command/command.py) for the main class, as well as [a class that uses it and the option parser](https://thomas.apestaart.org/moap/trac/browser/trunk/moap/command/doap.py)
What's the best way to grab/parse command line arguments passed to a Python script?
20,063
84
2008-08-21T14:24:41Z
979,871
32
2009-06-11T07:54:53Z
[ "python", "command-line", "command-line-arguments" ]
What's the **easiest, tersest, and most flexible** method or library for parsing Python command line arguments?
The new hip way is `argparse` for [these](http://argparse.googlecode.com/svn/trunk/doc/argparse-vs-optparse.html) reasons. argparse > optparse > getopt **update:** As of py2.7 [argparse](http://docs.python.org/library/argparse.html) is part of the standard library and [optparse](http://docs.python.org/library/optparse.html) is deprecated.
What's the best way to grab/parse command line arguments passed to a Python script?
20,063
84
2008-08-21T14:24:41Z
16,377,263
37
2013-05-04T17:51:38Z
[ "python", "command-line", "command-line-arguments" ]
What's the **easiest, tersest, and most flexible** method or library for parsing Python command line arguments?
Since 2012 Python has a very easy, powerful and really *cool* module for argument parsing called [docopt](https://github.com/docopt/docopt). It works with Python 2.6 to 3.5 and needs no installation (just copy it). Here is an example taken from it's documentation: ``` """Naval Fate. Usage: naval_fate.py ship new <name>... naval_fate.py ship <name> move <x> <y> [--speed=<kn>] naval_fate.py ship shoot <x> <y> naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting] naval_fate.py (-h | --help) naval_fate.py --version Options: -h --help Show this screen. --version Show version. --speed=<kn> Speed in knots [default: 10]. --moored Moored (anchored) mine. --drifting Drifting mine. """ from docopt import docopt if __name__ == '__main__': arguments = docopt(__doc__, version='Naval Fate 2.0') print(arguments) ``` So this is it: one line of code plus your doc string which *is* essential. I told you it's cool, didn't I ;-)
What's the best way to grab/parse command line arguments passed to a Python script?
20,063
84
2008-08-21T14:24:41Z
30,493,366
27
2015-05-27T21:21:26Z
[ "python", "command-line", "command-line-arguments" ]
What's the **easiest, tersest, and most flexible** method or library for parsing Python command line arguments?
Other answers do mention that `argparse` is the way to go for new Python, but do not give usage examples. For completeness, here is a short summary of how to use argparse: **1) Initialize** ``` import argparse # Instantiate the parser parser = argparse.ArgumentParser(description='Optional app description') ``` **2) Add Arguments** ``` # Required positional argument parser.add_argument('pos_arg', type=int, help='A required integer positional argument') # Optional positional argument parser.add_argument('opt_pos_arg', type=int, nargs='?', help='An optional integer positional argument') # Optional argument parser.add_argument('--opt_arg', type=int, help='An optional integer argument') # Switch parser.add_argument('--switch', action='store_true', help='A boolean switch') ``` **3) Parse** ``` args = parser.parse_args() ``` **4) Access** ``` print("Argument values:") print(args.pos_arg) print(args.opt_pos_arg) print(args.opt_arg) print(args.switch) ``` **5) Check Values** ``` if args.pos_arg > 10: parser.error("pos_arg cannot be larger than 10") ``` ## Usage **Correct use:** ``` $ ./app 1 2 --opt_arg 3 --switch Argument values: 1 2 3 True ``` **Incorrect arguments:** ``` $ ./app foo 2 --opt_arg 3 --switch usage: convert [-h] [--opt_arg OPT_ARG] [--switch] pos_arg [opt_pos_arg] app: error: argument pos_arg: invalid int value: 'foo' $ ./app 11 2 --opt_arg 3 Argument values: 11 2 3 False usage: app [-h] [--opt_arg OPT_ARG] [--switch] pos_arg [opt_pos_arg] convert: error: pos_arg cannot be larger than 10 ``` **Full help:** ``` $ ./app -h usage: app [-h] [--opt_arg OPT_ARG] [--switch] pos_arg [opt_pos_arg] Optional app description positional arguments: pos_arg A required integer positional argument opt_pos_arg An optional integer positional argument optional arguments: -h, --help show this help message and exit --opt_arg OPT_ARG An optional integer argument --switch A boolean switch ```
Find broken symlinks with Python
20,794
13
2008-08-21T19:00:52Z
20,848
11
2008-08-21T19:15:33Z
[ "python", "linux", "symlink" ]
If I call `os.stat()` on a broken `symlink`, python throws an `OSError` exception. This makes it useful for finding them. However, there are a few other reasons that `os.stat()` might throw a similar exception. Is there a more precise way of detecting broken `symlinks` with Python under Linux?
[os.lstat()](https://docs.python.org/2/library/os.html#os.lstat) may be helpful. If lstat() succeeds and stat() fails, then it's probably a broken link.
Find broken symlinks with Python
20,794
13
2008-08-21T19:00:52Z
26,957
18
2008-08-25T21:32:20Z
[ "python", "linux", "symlink" ]
If I call `os.stat()` on a broken `symlink`, python throws an `OSError` exception. This makes it useful for finding them. However, there are a few other reasons that `os.stat()` might throw a similar exception. Is there a more precise way of detecting broken `symlinks` with Python under Linux?
A common Python saying is that it's easier to ask forgiveness than permission. While I'm not a fan of this statement in real life, it does apply in a lot of cases. Usually you want to avoid code that chains two system calls on the same file, because you never know what will happen to the file in between your two calls in your code. **A typical mistake is to write something like**: ``` if os.path.exists(path): os.unlink(path) ``` The second call (os.unlink) may fail if something else deleted it after your if test, raise an Exception, and stop the rest of your function from executing. (You might think this doesn't happen in real life, but we just fished another bug like that out of our codebase last week - and it was the kind of bug that left a few programmers scratching their head and claiming 'Heisenbug' for the last few months) So, in your particular case, I would probably do: ``` try: os.stat(path) except OSError, e: if e.errno == errno.ENOENT: print 'path %s does not exist or is a broken symlink' % path else: raise e ``` The annoyance here is that stat returns the same error code for a symlink that just isn't there and a broken symlink. So, I guess you have no choice than to break the atomicity, and do something like ``` if not os.path.exists(os.readlink(path)): print 'path %s is a broken symlink' % path ```
Specifying a mySQL ENUM in a Django model
21,454
65
2008-08-21T23:48:08Z
21,468
75
2008-08-21T23:54:52Z
[ "python", "mysql", "django", "django-models", "enums" ]
How do I go about specifying and using an ENUM in a Django model?
From the [Django documentation](https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.Field.choices): ``` MAYBECHOICE = ( ('y', 'Yes'), ('n', 'No'), ('u', 'Unknown'), ) ``` And you define a charfield in your model : ``` married = models.CharField(max_length=1, choices=MAYBECHOICE) ``` You can do the same with integer fields if you don't like to have letters in your db. In that case, rewrite your choices: ``` MAYBECHOICE = ( (0, 'Yes'), (1, 'No'), (2, 'Unknown'), ) ```
Specifying a mySQL ENUM in a Django model
21,454
65
2008-08-21T23:48:08Z
33,932
26
2008-08-29T03:57:14Z
[ "python", "mysql", "django", "django-models", "enums" ]
How do I go about specifying and using an ENUM in a Django model?
Using the `choices` parameter won't use the ENUM db type; it will just create a VARCHAR or INTEGER, depending on whether you use `choices` with a CharField or IntegerField. Generally, this is just fine. If it's important to you that the ENUM type is used at the database level, you have three options: 1. Use "./manage.py sql appname" to see the SQL Django generates, manually modify it to use the ENUM type, and run it yourself. If you create the table manually first, "./manage.py syncdb" won't mess with it. 2. If you don't want to do this manually every time you generate your DB, put some custom SQL in appname/sql/modelname.sql to perform the appropriate ALTER TABLE command. 3. Create a [custom field type](http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields) and define the db\_type method appropriately. With any of these options, it would be your responsibility to deal with the implications for cross-database portability. In option 2, you could use [database-backend-specific custom SQL](http://www.djangoproject.com/documentation/model-api/#database-backend-specific-sql-data) to ensure your ALTER TABLE is only run on MySQL. In option 3, your db\_type method would need to check the database engine and set the db column type to a type that actually exists in that database. **UPDATE**: Since the migrations framework was added in Django 1.7, options 1 and 2 above are entirely obsolete. Option 3 was always the best option anyway. The new version of options 1/2 would involve a complex custom migration using `SeparateDatabaseAndState` -- but really you want option 3.
Specifying a mySQL ENUM in a Django model
21,454
65
2008-08-21T23:48:08Z
1,530,858
31
2009-10-07T10:47:46Z
[ "python", "mysql", "django", "django-models", "enums" ]
How do I go about specifying and using an ENUM in a Django model?
``` from django.db import models class EnumField(models.Field): """ A field class that maps to MySQL's ENUM type. Usage: class Card(models.Model): suit = EnumField(values=('Clubs', 'Diamonds', 'Spades', 'Hearts')) c = Card() c.suit = 'Clubs' c.save() """ def __init__(self, *args, **kwargs): self.values = kwargs.pop('values') kwargs['choices'] = [(v, v) for v in self.values] kwargs['default'] = self.values[0] super(EnumField, self).__init__(*args, **kwargs) def db_type(self): return "enum({0})".format( ','.join("'%s'" % v for v in self.values) ) ```
Why Java and Python garbage collection methods are different?
21,934
35
2008-08-22T07:35:26Z
21,937
8
2008-08-22T07:40:12Z
[ "java", "python", "garbage-collection" ]
Python uses the reference count method to handle object life time. So an object that has no more use will be immediately destroyed. But, in Java, the GC(garbage collector) destroys objects which are no longer used at a specific time. Why does Java choose this strategy and what is the benefit from this? Is this better than the Python approach?
I think the article "[Java theory and practice: A brief history of garbage collection](http://www.ibm.com/developerworks/java/library/j-jtp10283/)" from IBM should help explain some of the questions you have.
Why Java and Python garbage collection methods are different?
21,934
35
2008-08-22T07:35:26Z
21,964
40
2008-08-22T09:10:06Z
[ "java", "python", "garbage-collection" ]
Python uses the reference count method to handle object life time. So an object that has no more use will be immediately destroyed. But, in Java, the GC(garbage collector) destroys objects which are no longer used at a specific time. Why does Java choose this strategy and what is the benefit from this? Is this better than the Python approach?
There are drawbacks of using reference counting. One of the most mentioned is circular references: Suppose A references B, B references C and C references B. If A were to drop its reference to B, both B and C will still have a reference count of 1 and won't be deleted with traditional reference counting. CPython (reference counting is not part of python itself, but part of the C implementation thereof) catches circular references with a separate garbage collection routine that it runs periodically... Another drawback: Reference counting can make execution slower. Each time an object is referenced and dereferenced, the interpreter/VM must check to see if the count has gone down to 0 (and then deallocate if it did). Garbage Collection does not need to do this. Also, Garbage Collection can be done in a separate thread (though it can be a bit tricky). On machines with lots of RAM and for processes that use memory only slowly, you might not want to be doing GC at all! Reference counting would be a bit of a drawback there in terms of performance...
Why Java and Python garbage collection methods are different?
21,934
35
2008-08-22T07:35:26Z
22,219
11
2008-08-22T12:40:03Z
[ "java", "python", "garbage-collection" ]
Python uses the reference count method to handle object life time. So an object that has no more use will be immediately destroyed. But, in Java, the GC(garbage collector) destroys objects which are no longer used at a specific time. Why does Java choose this strategy and what is the benefit from this? Is this better than the Python approach?
Darren Thomas gives a good answer. However, one big difference between the Java and Python approaches is that with reference counting in the common case (no circular references) objects are cleaned up immediately rather than at some indeterminate later date. For example, I can write sloppy, non-portable code in CPython such as ``` def parse_some_attrs(fname): return open(fname).read().split("~~~")[2:4] ``` and the file descriptor for that file I opened will be cleaned up immediately because as soon as the reference to the open file goes away, the file is garbage collected and the file descriptor is freed. Of course, if I run Jython or IronPython or possibly PyPy, then the garbage collector won't necessarily run until much later; possibly I'll run out of file descriptors first and my program will crash. So you SHOULD be writing code that looks like ``` def parse_some_attrs(fname): with open(fname) as f: return f.read().split("~~~")[2:4] ``` but sometimes people like to rely on reference counting to always free up their resources because it can sometimes make your code a little shorter. I'd say that the best garbage collector is the one with the best performance, which currently seems to be the Java-style generational garbage collectors that can run in a separate thread and has all these crazy optimizations, etc. The differences to how you write your code should be negligible and ideally non-existent.
Why Java and Python garbage collection methods are different?
21,934
35
2008-08-22T07:35:26Z
196,487
22
2008-10-13T01:42:10Z
[ "java", "python", "garbage-collection" ]
Python uses the reference count method to handle object life time. So an object that has no more use will be immediately destroyed. But, in Java, the GC(garbage collector) destroys objects which are no longer used at a specific time. Why does Java choose this strategy and what is the benefit from this? Is this better than the Python approach?
Actually reference counting and the strategies used by the Sun JVM are all different types of garbage collection algorithms. There are two broad approaches for tracking down dead objects: tracing and reference counting. In tracing the GC starts from the "roots" - things like stack references, and traces all reachable (live) objects. Anything that can't be reached is considered dead. In reference counting each time a reference is modified the object's involved have their count updated. Any object whose reference count gets set to zero is considered dead. With basically all GC implementations there are trade offs but tracing is usually good for high through put (i.e. fast) operation but has longer pause times (larger gaps where the UI or program may freeze up). Reference counting can operate in smaller chunks but will be slower overall. It may mean less freezes but poorer performance overall. Additionally a reference counting GC requires a cycle detector to clean up any objects in a cycle that won't be caught by their reference count alone. Perl 5 didn't have a cycle detector in its GC implementation and could leak memory that was cyclic. Research has also been done to get the best of both worlds (low pause times, high throughput): <http://cs.anu.edu.au/~Steve.Blackburn/pubs/papers/urc-oopsla-2003.pdf>
Why does this python date/time conversion seem wrong?
21,961
3
2008-08-22T09:06:43Z
21,975
7
2008-08-22T09:24:25Z
[ "python", "datetime" ]
``` >>> import time >>> time.strptime("01-31-2009", "%m-%d-%Y") (2009, 1, 31, 0, 0, 0, 5, 31, -1) >>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1)) 1233378000.0 >>> 60*60*24 # seconds in a day 86400 >>> 1233378000.0 / 86400 14275.208333333334 ``` time.mktime should return the number of seconds since the epoch. Since I'm giving it a time at midnight and the epoch is at midnight, shouldn't the result be evenly divisible by the number of seconds in a day?
Short answer: Because of timezones. The Epoch is in UTC. For example, I'm on IST (Irish Stsandard Time) or GMT+1. time.mktime() is relative to my timezone, so on my system this refers to ``` >>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1)) 1233360000.0 ``` Because you got the result 1233378000, that would suggest that you're 5 hours behind me ``` >>> (1233378000 - 1233360000) / (60*60) 5 ``` Have a look at the time.gmtime() function which works off UTC.
How do content discovery engines, like Zemanta and Open Calais work?
22,059
4
2008-08-22T10:51:19Z
35,667
7
2008-08-30T03:56:57Z
[ "python", "ruby", "semantics", "zemanta" ]
I was wondering how as semantic service like Open Calais figures out the names of companies, or people, tech concepts, keywords, etc. from a piece of text. Is it because they have a large database that they match the text against? How would a service like Zemanta know what images to suggest to a piece of text for instance?
I'm not familiar with the specific services listed, but the field of natural language processing has developed a number of techniques that enable this sort of information extraction from general text. As Sean stated, once you have candidate terms, it's not to difficult to search for those terms with some of the other entities in context and then use the results of that search to determine how confident you are that the term extracted is an actual entity of interest. [OpenNLP](http://opennlp.sourceforge.net/) is a great project if you'd like to play around with natural language processing. The capabilities you've named would probably be best accomplished with Named Entity Recognizers (NER) (algorithms that locate proper nouns, generally, and sometimes dates as well) and/or Word Sense Disambiguation (WSD) (eg: the word 'bank' has different meanings depending on it's context, and that can be very important when extracting information from text. Given the sentences: "the plane banked left", "the snow bank was high", and "they robbed the bank" you can see how dissambiguation can play an important part in language understanding) Techniques generally build on each other, and NER is one of the more complex tasks, so to do NER successfully, you will generally need accurate tokenizers (natural language tokenizers, mind you -- statistical approaches tend to fare the best), string stemmers (algorithms that conflate similar words to common roots: so words like informant and informer are treated equally), sentence detection ('Mr. Jones was tall.' is only one sentence, so you can't just check for punctuation), part-of-speech taggers (POS taggers), and WSD. There is a python port of (parts of) OpenNLP called NLTK (<http://nltk.sourceforge.net>) but I don't have much experience with it yet. Most of my work has been with the Java and C# ports, which work well. All of these algorithms are language-specific, of course, and they can take significant time to run (although, it is generally faster than reading the material you are processing). Since the state-of-the-art is largely based on statistical techniques, there is also a considerable error rate to take into account. Furthermore, because the error rate impacts all the stages, and something like NER requires numerous stages of processing, (tokenize -> sentence detect -> POS tag -> WSD -> NER) the error rates compound.
How do content discovery engines, like Zemanta and Open Calais work?
22,059
4
2008-08-22T10:51:19Z
821,663
9
2009-05-04T19:45:20Z
[ "python", "ruby", "semantics", "zemanta" ]
I was wondering how as semantic service like Open Calais figures out the names of companies, or people, tech concepts, keywords, etc. from a piece of text. Is it because they have a large database that they match the text against? How would a service like Zemanta know what images to suggest to a piece of text for instance?
Michal Finkelstein from OpenCalais here. First, thanks for your interest. I'll reply here but I also encourage you to read more on OpenCalais forums; there's a lot of information there including - but not limited to: <http://opencalais.com/tagging-information> <http://opencalais.com/how-does-calais-learn> Also feel free to follow us on Twitter (@OpenCalais) or to email us at [email protected] Now to the answer: OpenCalais is based on a decade of research and development in the fields of Natural Language Processing and Text Analytics. We support the full "NLP Stack" (as we like to call it): From text tokenization, morphological analysis and POS tagging, to shallow parsing and identifying nominal and verbal phrases. Semantics come into play when we look for Entities (a.k.a. Entity Extraction, Named Entity Recognition). For that purpose we have a sophisticated rule-based system that combines discovery rules as well as lexicons/dictionaries. This combination allows us to identify names of companies/persons/films, etc., even if they don't exist in any available list. For the most prominent entities (such as people, companies) we also perform anaphora resolution, cross-reference and name canonization/normalization at the article level, so we'll know that 'John Smith' and 'Mr. Smith', for example, are likely referring to the same person. So the short answer to your question is - no, it's not just about matching against large databases. Events/Facts are really interesting because they take our discovery rules one level deeper; we find relations between entities and label them with the appropriate type, for example M&As (relations between two or more companies), Employment Changes (relations between companies and people), and so on. Needless to say, Event/Fact extraction is not possible for systems that are based solely on lexicons. For the most part, our system is tuned to be precision-oriented, but we always try to keep a reasonable balance between accuracy and entirety. By the way there are some cool new metadata capabilities coming out later this month so stay tuned. Regards, Michal
Unicode vs UTF-8 confusion in Python / Django?
22,149
25
2008-08-22T12:01:53Z
22,208
8
2008-08-22T12:32:59Z
[ "python", "django", "unicode" ]
I stumbled over this passage in the [Django tutorial](http://www.djangoproject.com/documentation/tutorial01/): > Django models have a default **str**() method that calls **unicode**() and converts the result to a UTF-8 bytestring. This means that unicode(p) will return a Unicode string, and str(p) will return a normal string, with characters encoded as UTF-8. Now, I'm confused because afaik Unicode is not any particular representation, so what is a "Unicode string" in Python? Does that mean UCS-2? Googling turned up [this "Python Unicode Tutorial"](http://www.reportlab.com/i18n/python_unicode_tutorial.html) which boldly states > Unicode is a two-byte encoding which covers all of the world's common writing systems. which is plain wrong, or is it? I have been confused many times by character set and encoding issues, but here I'm quite sure that the documentation I'm reading is confused. Does anybody know what's going on in Python when it gives me a "Unicode string"?
Meanwhile, I did a refined research to verify what the internal representation in Python is, and also what its limits are. "[The Truth About Unicode In Python](http://www.cmlenz.net/archives/2008/07/the-truth-about-unicode-in-python)" is a very good article which cites directly from the Python developers. Apparently, internal representation is either UCS-2 or UCS-4 depending on a compile-time switch. So Jon, it's not UTF-16, but your answer put me on the right track anyway, thanks.
Unicode vs UTF-8 confusion in Python / Django?
22,149
25
2008-08-22T12:01:53Z
522,827
45
2009-02-07T00:54:09Z
[ "python", "django", "unicode" ]
I stumbled over this passage in the [Django tutorial](http://www.djangoproject.com/documentation/tutorial01/): > Django models have a default **str**() method that calls **unicode**() and converts the result to a UTF-8 bytestring. This means that unicode(p) will return a Unicode string, and str(p) will return a normal string, with characters encoded as UTF-8. Now, I'm confused because afaik Unicode is not any particular representation, so what is a "Unicode string" in Python? Does that mean UCS-2? Googling turned up [this "Python Unicode Tutorial"](http://www.reportlab.com/i18n/python_unicode_tutorial.html) which boldly states > Unicode is a two-byte encoding which covers all of the world's common writing systems. which is plain wrong, or is it? I have been confused many times by character set and encoding issues, but here I'm quite sure that the documentation I'm reading is confused. Does anybody know what's going on in Python when it gives me a "Unicode string"?
> what is a "Unicode string" in Python? Does that mean UCS-2? Unicode strings in Python are stored internally either as UCS-2 (fixed-length 16-bit representation, almost the same as UTF-16) or UCS-4/UTF-32 (fixed-length 32-bit representation). It's a compile-time option; on Windows it's always UTF-16 whilst many Linux distributions set UTF-32 (‘wide mode’) for their versions of Python. You are generally not supposed to care: you will see Unicode code-points as single elements in your strings and you won't know whether they're stored as two or four bytes. If you're in a UTF-16 build and you need to handle characters outside the Basic Multilingual Plane you'll be Doing It Wrong, but that's still very rare, and users who really need the extra characters should be compiling wide builds. > plain wrong, or is it? Yes, it's quite wrong. To be fair I think that tutorial is rather old; it probably pre-dates wide Unicode strings, if not Unicode 3.1 (the version that introduced characters outside the Basic Multilingual Plane). There is an additional source of confusion stemming from Windows's habit of using the term “Unicode” to mean, specifically, the UTF-16LE encoding that NT uses internally. People from Microsoftland may often copy this somewhat misleading habit.
Format numbers to strings in Python
22,617
68
2008-08-22T15:10:46Z
22,624
103
2008-08-22T15:12:41Z
[ "python", "string-formatting" ]
I need to find out how to format numbers as strings. My code is here: ``` return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm ``` Hours and minutes are integers, and seconds is a float. the str() function will convert all of these numbers to the tenths (0.1) place. So instead of my string outputting "5:30:59.07 pm", it would display something like "5.0:30.0:59.1 pm". Bottom line, what library / function do I need to do this for me?
Formatting in Python is done via the [string formatting (`%`) operator](http://docs.python.org/2/library/stdtypes.html#string-formatting): ``` "%02d:%02d:%02d" % (hours, minutes, seconds) ``` /Edit: There's also [strftime](https://docs.python.org/2/library/time.html#time.strftime).
Format numbers to strings in Python
22,617
68
2008-08-22T15:10:46Z
2,550,630
74
2010-03-31T05:13:20Z
[ "python", "string-formatting" ]
I need to find out how to format numbers as strings. My code is here: ``` return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm ``` Hours and minutes are integers, and seconds is a float. the str() function will convert all of these numbers to the tenths (0.1) place. So instead of my string outputting "5:30:59.07 pm", it would display something like "5.0:30.0:59.1 pm". Bottom line, what library / function do I need to do this for me?
Starting in Python 2.6, there is an alternative: the `str.format()` method. Here are some examples using the existing string format operator (`%`): ``` >>> "Name: %s, age: %d" % ('John', 35) 'Name: John, age: 35' >>> i = 45 >>> 'dec: %d/oct: %#o/hex: %#X' % (i, i, i) 'dec: 45/oct: 055/hex: 0X2D' >>> "MM/DD/YY = %02d/%02d/%02d" % (12, 7, 41) 'MM/DD/YY = 12/07/41' >>> 'Total with tax: $%.2f' % (13.00 * 1.0825) 'Total with tax: $14.07' >>> d = {'web': 'user', 'page': 42} >>> 'http://xxx.yyy.zzz/%(web)s/%(page)d.html' % d 'http://xxx.yyy.zzz/user/42.html' ``` Here are the equivalent snippets but using `str.format()`: ``` >>> "Name: {0}, age: {1}".format('John', 35) 'Name: John, age: 35' >>> i = 45 >>> 'dec: {0}/oct: {0:#o}/hex: {0:#X}'.format(i) 'dec: 45/oct: 0o55/hex: 0X2D' >>> "MM/DD/YY = {0:02d}/{1:02d}/{2:02d}".format(12, 7, 41) 'MM/DD/YY = 12/07/41' >>> 'Total with tax: ${0:.2f}'.format(13.00 * 1.0825) 'Total with tax: $14.07' >>> d = {'web': 'user', 'page': 42} >>> 'http://xxx.yyy.zzz/{web}/{page}.html'.format(**d) 'http://xxx.yyy.zzz/user/42.html' ``` Like Python 2.6+, all Python 3 releases (so far) understand how to do both. I shamelessly ripped this stuff straight out of [my hardcore Python intro book](http://amzn.com/0132269937) and the slides for the Intro+Intermediate [Python courses I offer](http://cyberwebconsulting.com) from time-to-time. `:-)`
How do I download a file over HTTP using Python?
22,676
492
2008-08-22T15:34:13Z
22,682
286
2008-08-22T15:38:22Z
[ "python" ]
I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes. The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows `.bat` file to download the actual MP3 however. I would prefer to have the entire utility written in Python though. I struggled though to find a way to actually down load the file in Python, thus why I resorted to `wget`. So, how do I download the file using Python?
In Python 2, use urllib2 which comes with the standard library. ``` import urllib2 response = urllib2.urlopen('http://www.example.com/') html = response.read() ``` This is the most basic way to use the library, minus any error handling. You can also do more complex stuff such as changing headers. The documentation can be found [here.](http://docs.python.org/2/library/urllib2.html)
How do I download a file over HTTP using Python?
22,676
492
2008-08-22T15:34:13Z
22,721
118
2008-08-22T15:58:17Z
[ "python" ]
I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes. The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows `.bat` file to download the actual MP3 however. I would prefer to have the entire utility written in Python though. I struggled though to find a way to actually down load the file in Python, thus why I resorted to `wget`. So, how do I download the file using Python?
``` import urllib2 mp3file = urllib2.urlopen("http://www.example.com/songs/mp3.mp3") with open('test.mp3','wb') as output: output.write(mp3file.read()) ``` The `wb` in `open('test.mp3','wb')` opens a file (and erases any existing file) in binary mode so you can save data with it instead of just text.
How do I download a file over HTTP using Python?
22,676
492
2008-08-22T15:34:13Z
22,723
9
2008-08-22T15:58:52Z
[ "python" ]
I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes. The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows `.bat` file to download the actual MP3 however. I would prefer to have the entire utility written in Python though. I struggled though to find a way to actually down load the file in Python, thus why I resorted to `wget`. So, how do I download the file using Python?
I agree with Corey, urllib2 is more complete than [urllib](http://docs.python.org/lib/module-urllib.html) and should likely be the module used if you want to do more complex things, but to make the answers more complete, urllib is a simpler module if you want just the basics: ``` import urllib response = urllib.urlopen('http://www.example.com/sound.mp3') mp3 = response.read() ``` Will work fine. Or, if you don't want to deal with the "response" object you can call **read()** directly: ``` import urllib mp3 = urllib.urlopen('http://www.example.com/sound.mp3').read() ```
How do I download a file over HTTP using Python?
22,676
492
2008-08-22T15:34:13Z
22,776
759
2008-08-22T16:19:09Z
[ "python" ]
I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes. The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows `.bat` file to download the actual MP3 however. I would prefer to have the entire utility written in Python though. I struggled though to find a way to actually down load the file in Python, thus why I resorted to `wget`. So, how do I download the file using Python?
One more, using [`urlretrieve`](http://docs.python.org/2/library/urllib.html#urllib.urlretrieve): ``` import urllib urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3") ``` (for Python 3+ use 'import urllib.request' and urllib.request.urlretrieve) Yet another one, with a "progressbar" ``` import urllib2 url = "http://download.thinkbroadband.com/10MB.zip" file_name = url.split('/')[-1] u = urllib2.urlopen(url) f = open(file_name, 'wb') meta = u.info() file_size = int(meta.getheaders("Content-Length")[0]) print "Downloading: %s Bytes: %s" % (file_name, file_size) file_size_dl = 0 block_sz = 8192 while True: buffer = u.read(block_sz) if not buffer: break file_size_dl += len(buffer) f.write(buffer) status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size) status = status + chr(8)*(len(status)+1) print status, f.close() ```
How do I download a file over HTTP using Python?
22,676
492
2008-08-22T15:34:13Z
10,744,565
224
2012-05-24T20:08:29Z
[ "python" ]
I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes. The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows `.bat` file to download the actual MP3 however. I would prefer to have the entire utility written in Python though. I struggled though to find a way to actually down load the file in Python, thus why I resorted to `wget`. So, how do I download the file using Python?
In 2012, use the [python requests library](http://docs.python-requests.org/en/latest/index.html) ``` >>> import requests >>> >>> url = "http://download.thinkbroadband.com/10MB.zip" >>> r = requests.get(url) >>> print len(r.content) 10485760 ``` You can run `pip install requests` to get it. Requests has many advantages over the alternatives because the API is much simpler. This is especially true if you have to do authentication. urllib and urllib2 are pretty unintuitive and painful in this case. --- 2015-12-30 People have expressed admiration for the progress bar. It's cool, sure. There are several off-the-shelf solutions now, including `tqdm`: ``` from tqdm import tqdm import requests url = "http://download.thinkbroadband.com/10MB.zip" response = requests.get(url, stream=True) with open("10MB", "wb") as handle: for data in tqdm(response.iter_content()): handle.write(data) ``` This is essentially the implementation @kvance described 30 months ago.
How do I download a file over HTTP using Python?
22,676
492
2008-08-22T15:34:13Z
16,518,224
14
2013-05-13T08:59:44Z
[ "python" ]
I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes. The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows `.bat` file to download the actual MP3 however. I would prefer to have the entire utility written in Python though. I struggled though to find a way to actually down load the file in Python, thus why I resorted to `wget`. So, how do I download the file using Python?
An improved version of the PabloG code for Python 2/3: ``` from __future__ import ( division, absolute_import, print_function, unicode_literals ) import sys, os, tempfile, logging if sys.version_info >= (3,): import urllib.request as urllib2 import urllib.parse as urlparse else: import urllib2 import urlparse def download_file(url, desc=None): u = urllib2.urlopen(url) scheme, netloc, path, query, fragment = urlparse.urlsplit(url) filename = os.path.basename(path) if not filename: filename = 'downloaded.file' if desc: filename = os.path.join(desc, filename) with open(filename, 'wb') as f: meta = u.info() meta_func = meta.getheaders if hasattr(meta, 'getheaders') else meta.get_all meta_length = meta_func("Content-Length") file_size = None if meta_length: file_size = int(meta_length[0]) print("Downloading: {0} Bytes: {1}".format(url, file_size)) file_size_dl = 0 block_sz = 8192 while True: buffer = u.read(block_sz) if not buffer: break file_size_dl += len(buffer) f.write(buffer) status = "{0:16}".format(file_size_dl) if file_size: status += " [{0:6.2f}%]".format(file_size_dl * 100 / file_size) status += chr(13) print(status, end="") print() return filename url = "http://download.thinkbroadband.com/10MB.zip" filename = download_file(url) print(filename) ```
How do I download a file over HTTP using Python?
22,676
492
2008-08-22T15:34:13Z
19,011,916
12
2013-09-25T17:55:16Z
[ "python" ]
I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes. The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows `.bat` file to download the actual MP3 however. I would prefer to have the entire utility written in Python though. I struggled though to find a way to actually down load the file in Python, thus why I resorted to `wget`. So, how do I download the file using Python?
Wrote [wget](https://pypi.python.org/pypi/wget) library in pure Python just for this purpose. It is pumped up `urlretrieve` with [these features](https://bitbucket.org/techtonik/python-wget/src/6859e7b4aba37cef57616111be890fb59631bc4c/wget.py?at=default#cl-330) as of version 2.0.
How do I download a file over HTTP using Python?
22,676
492
2008-08-22T15:34:13Z
31,857,152
14
2015-08-06T13:30:31Z
[ "python" ]
I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes. The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows `.bat` file to download the actual MP3 however. I would prefer to have the entire utility written in Python though. I struggled though to find a way to actually down load the file in Python, thus why I resorted to `wget`. So, how do I download the file using Python?
Here's how to do it in Python 3 using the standard library: * [`urllib.request.urlopen`](https://docs.python.org/3.0/library/urllib.request.html#urllib.request.urlopen) ``` import urllib.request response = urllib.request.urlopen('http://www.example.com/') html = response.read() ``` * [`urllib.request.urlretrieve`](https://docs.python.org/3.0/library/urllib.request.html#urllib.request.urlretrieve) ``` import urllib.request urllib.request.urlretrieve('http://www.example.com/songs/mp3.mp3', 'mp3.mp3') ```
What's the best way to duplicate fork() in windows?
23,397
20
2008-08-22T20:27:46Z
170,387
10
2008-10-04T14:10:36Z
[ "python", "windows", "process", "subprocess", "fork" ]
How do I implement some logic that will allow me to reproduce on Windows the functionality that I have on Linux with the `fork()` system call, using Python? I'm specifically trying to execute a method on the SAPI Com component, while continuing the other logic in the main thread without blocking or waiting.
`fork()` *has* in fact been duplicated in Windows, under [Cygwin](https://en.wikipedia.org/wiki/Cygwin), but it's pretty hairy. > The fork call in Cygwin is particularly interesting because it does not map well on top of the Win32 API. This makes it very difficult to implement correctly. See the [The Cygwin User's Guide](http://cygwin.com/cygwin-ug-net/highlights.html#ov-hi-process) for a description of this hack.
What's the best way to duplicate fork() in windows?
23,397
20
2008-08-22T20:27:46Z
6,020,663
15
2011-05-16T16:51:18Z
[ "python", "windows", "process", "subprocess", "fork" ]
How do I implement some logic that will allow me to reproduce on Windows the functionality that I have on Linux with the `fork()` system call, using Python? I'm specifically trying to execute a method on the SAPI Com component, while continuing the other logic in the main thread without blocking or waiting.
Use the python [multiprocessing module](http://docs.python.org/library/multiprocessing.html) which will work everywhere. Here is a [IBM developerWords article](http://www.ibm.com/developerworks/aix/library/au-multiprocessing/) that shows how to convert from os.fork() to the multiprocessing module.
How can I graph the Lines of Code history for git repo?
23,907
34
2008-08-23T03:00:46Z
35,664
22
2008-08-30T03:55:23Z
[ "python", "ruby", "git", "lines-of-code", "sloc" ]
Basically I want to get the number of lines-of-code in the repository after each commit. The only (really crappy) ways I have found is to use git filter-branch to run "wc -l \*", and a script that run git reset --hard on each commit, then ran wc -l To make it a bit clearer, when the tool is run, it would output the lines of code of the very first commit, then the second and so on.. This is what I want the tool to output (as an example): ``` me@something:~/$ gitsloc --branch master 10 48 153 450 1734 1542 ``` I've played around with the ruby 'git' library, but the closest I found was using the .lines() method on a diff, which seems like it should give the added lines (but does not.. it returns 0 when you delete lines for example) ``` require 'rubygems' require 'git' total = 0 g = Git.open(working_dir = '/Users/dbr/Desktop/code_projects/tvdb_api') last = nil g.log.each do |cur| diff = g.diff(last, cur) total = total + diff.lines puts total last = cur end ```
You may get both added and removed lines with git log, like: ``` git log --shortstat --reverse --pretty=oneline ``` From this, you can write a similar script to the one you did using this info. In python: ``` #!/usr/bin/python """ Display the per-commit size of the current git branch. """ import subprocess import re import sys def main(argv): git = subprocess.Popen(["git", "log", "--shortstat", "--reverse", "--pretty=oneline"], stdout=subprocess.PIPE) out, err = git.communicate() total_files, total_insertions, total_deletions = 0, 0, 0 for line in out.split('\n'): if not line: continue if line[0] != ' ': # This is a description line hash, desc = line.split(" ", 1) else: # This is a stat line data = re.findall( ' (\d+) files changed, (\d+) insertions\(\+\), (\d+) deletions\(-\)', line) files, insertions, deletions = ( int(x) for x in data[0] ) total_files += files total_insertions += insertions total_deletions += deletions print "%s: %d files, %d lines" % (hash, total_files, total_insertions - total_deletions) if __name__ == '__main__': sys.exit(main(sys.argv)) ```
How can I graph the Lines of Code history for git repo?
23,907
34
2008-08-23T03:00:46Z
2,854,506
22
2010-05-18T04:09:01Z
[ "python", "ruby", "git", "lines-of-code", "sloc" ]
Basically I want to get the number of lines-of-code in the repository after each commit. The only (really crappy) ways I have found is to use git filter-branch to run "wc -l \*", and a script that run git reset --hard on each commit, then ran wc -l To make it a bit clearer, when the tool is run, it would output the lines of code of the very first commit, then the second and so on.. This is what I want the tool to output (as an example): ``` me@something:~/$ gitsloc --branch master 10 48 153 450 1734 1542 ``` I've played around with the ruby 'git' library, but the closest I found was using the .lines() method on a diff, which seems like it should give the added lines (but does not.. it returns 0 when you delete lines for example) ``` require 'rubygems' require 'git' total = 0 g = Git.open(working_dir = '/Users/dbr/Desktop/code_projects/tvdb_api') last = nil g.log.each do |cur| diff = g.diff(last, cur) total = total + diff.lines puts total last = cur end ```
You might also consider [gitstats](http://gitstats.sourceforge.net/), which generates this graph as an html file.
How can I graph the Lines of Code history for git repo?
23,907
34
2008-08-23T03:00:46Z
3,180,919
9
2010-07-05T16:18:32Z
[ "python", "ruby", "git", "lines-of-code", "sloc" ]
Basically I want to get the number of lines-of-code in the repository after each commit. The only (really crappy) ways I have found is to use git filter-branch to run "wc -l \*", and a script that run git reset --hard on each commit, then ran wc -l To make it a bit clearer, when the tool is run, it would output the lines of code of the very first commit, then the second and so on.. This is what I want the tool to output (as an example): ``` me@something:~/$ gitsloc --branch master 10 48 153 450 1734 1542 ``` I've played around with the ruby 'git' library, but the closest I found was using the .lines() method on a diff, which seems like it should give the added lines (but does not.. it returns 0 when you delete lines for example) ``` require 'rubygems' require 'git' total = 0 g = Git.open(working_dir = '/Users/dbr/Desktop/code_projects/tvdb_api') last = nil g.log.each do |cur| diff = g.diff(last, cur) total = total + diff.lines puts total last = cur end ```
<http://github.com/ITikhonov/git-loc> worked right out of the box for me.
How to capture Python interpreter's and/or CMD.EXE's output from a Python script?
24,931
7
2008-08-24T08:46:57Z
24,949
9
2008-08-24T09:39:08Z
[ "python", "windows", "cmd" ]
1. Is it possible to capture Python interpreter's output from a Python script? 2. Is it possible to capture Windows CMD's output from a Python script? If so, which librar(y|ies) should I look into?
If you are talking about the python interpreter or CMD.exe that is the 'parent' of your script then no, it isn't possible. In every POSIX-like system (now you're running Windows, it seems, and that might have some quirk I don't know about, YMMV) each process has three streams, standard input, standard output and standard error. Bu default (when running in a console) these are directed to the console, but redirection is possible using the pipe notation: ``` python script_a.py | python script_b.py ``` This ties the standard output stream of script a to the standard input stream of script B. Standard error still goes to the console in this example. See the article on [standard streams](http://en.wikipedia.org/wiki/Standard_streams) on Wikipedia. If you're talking about a child process, you can launch it from python like so (stdin is also an option if you want two way communication): ``` import subprocess # Of course you can open things other than python here :) process = subprocess.Popen(["python", "main.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) x = process.stderr.readline() y = process.stdout.readline() process.wait() ``` See the Python [subprocess](http://docs.python.org/lib/module-subprocess.html) module for information on managing the process. For communication, the process.stdin and process.stdout pipes are considered standard [file objects](http://docs.python.org/lib/bltin-file-objects.html). For use with pipes, reading from standard input as [lassevk](http://stackoverflow.com/questions/24931/how-to-capture-python-interpreters-andor-cmdexes-output-from-a-python-script#24939) suggested you'd do something like this: ``` import sys x = sys.stderr.readline() y = sys.stdin.readline() ``` sys.stdin and sys.stdout are standard file objects as noted above, defined in the [sys](http://docs.python.org/lib/module-sys.html) module. You might also want to take a look at the [pipes](http://docs.python.org/lib/module-pipes.html) module. Reading data with readline() as in my example is a pretty naïve way of getting data though. If the output is not line-oriented or indeterministic you probably want to look into [polling](http://docs.python.org/lib/poll-objects.html) which unfortunately does not work in windows, but I'm sure there's some alternative out there.
Binary buffer in Python
25,116
41
2008-08-24T15:37:50Z
25,180
24
2008-08-24T16:52:29Z
[ "python", "binary", "io", "buffer" ]
In Python you can use [StringIO](https://docs.python.org/library/struct.html) for a file-like buffer for character data. [Memory-mapped file](https://docs.python.org/library/mmap.html) basically does similar thing for binary data, but it requires a file that is used as the basis. Does Python have a file object that is intended for binary data and is memory only, equivalent to Java's [ByteArrayOutputStream](http://java.sun.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html)? The use-case I have is I want to create a ZIP file in memory, and [ZipFile](https://docs.python.org/library/zipfile.html) requires a file-like object.
As long as you don't try to put any unicode data into your `StringIO` and you are careful NOT to use `cStringIO` you should be fine. According to the [StringIO](https://docs.python.org/library/stringio.html) documentation, as long as you keep to either unicode or 8-bits everything works as expected. Presumably, `StringIO` does something special when someone does a `f.write(u"asdf")` (which ZipFile does not do, to my knowledge). Anyway; ``` import zipfile import StringIO s = StringIO.StringIO() z = zipfile.ZipFile(s, "w") z.write("test.txt") z.close() f = file("x.zip", "w") f.write(s.getvalue()) s.close() f.close() ``` works just as expected, and there's no difference between the file in the resulting archive and the original file. If you know of a particular case where this approach does not work, I'd be most interested to hear about it :)
Binary buffer in Python
25,116
41
2008-08-24T15:37:50Z
7,357,938
55
2011-09-09T06:34:34Z
[ "python", "binary", "io", "buffer" ]
In Python you can use [StringIO](https://docs.python.org/library/struct.html) for a file-like buffer for character data. [Memory-mapped file](https://docs.python.org/library/mmap.html) basically does similar thing for binary data, but it requires a file that is used as the basis. Does Python have a file object that is intended for binary data and is memory only, equivalent to Java's [ByteArrayOutputStream](http://java.sun.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html)? The use-case I have is I want to create a ZIP file in memory, and [ZipFile](https://docs.python.org/library/zipfile.html) requires a file-like object.
You are probably looking for [io.BytesIO](http://docs.python.org/release/3.1.3/library/io.html#binary-i-o) class. It works exactly like StringIO except that it supports binary data: ``` from io import BytesIO bio = BytesIO(b"some initial binary data: \x00\x01") ``` StringIO will throw TypeError: ``` from io import StringIO sio = StringIO(b"some initial binary data: \x00\x01") ```
pyGame within a pyGTK application
25,661
7
2008-08-25T04:36:48Z
28,935
7
2008-08-26T19:36:24Z
[ "python", "gtk", "pygtk", "sdl", "pygame" ]
What is the best way to use PyGame (SDL) within a PyGTK application? I'm searching for a method that allows me to have a drawing area in the GTK window and at the same time being able to manage both GTK and SDL events.
I've never attempted it myself, but hearing plenty about other people who've tried, it's not a road you want to go down. There is the alternative of putting the gui in pygame itself. There are plenty of gui toolkits built specifically for pygame that you could use. Most of them are rather unfinished, but there are 2 big, actively maintained ones: [PGU](http://www.pygame.org/project/108/) and [OcempGUI](http://www.pygame.org/project/125/). The full list on the pygame site is [here](http://www.pygame.org/tags/gui).
Python super class reflection
25,807
30
2008-08-25T09:06:16Z
25,815
36
2008-08-25T09:22:22Z
[ "python", "reflection" ]
If I have Python code ``` class A(): pass class B(): pass class C(A, B): pass ``` and I have class `C`, is there a way to iterate through it's super classed (`A` and `B`)? Something like pseudocode: ``` >>> magicGetSuperClasses(C) (<type 'A'>, <type 'B'>) ``` One solution seems to be [inspect module](http://docs.python.org/lib/module-inspect.html) and `getclasstree` function. ``` def magicGetSuperClasses(cls): return [o[0] for o in inspect.getclasstree([cls]) if type(o[0]) == type] ``` but is this a "Pythonian" way to achieve the goal?
`C.__bases__` is an array of the super classes, so you could implement your hypothetical function like so: ``` def magicGetSuperClasses(cls): return cls.__bases__ ``` But I imagine it would be easier to just reference `cls.__bases__` directly in most cases.
Python super class reflection
25,807
30
2008-08-25T09:06:16Z
35,111
11
2008-08-29T19:30:31Z
[ "python", "reflection" ]
If I have Python code ``` class A(): pass class B(): pass class C(A, B): pass ``` and I have class `C`, is there a way to iterate through it's super classed (`A` and `B`)? Something like pseudocode: ``` >>> magicGetSuperClasses(C) (<type 'A'>, <type 'B'>) ``` One solution seems to be [inspect module](http://docs.python.org/lib/module-inspect.html) and `getclasstree` function. ``` def magicGetSuperClasses(cls): return [o[0] for o in inspect.getclasstree([cls]) if type(o[0]) == type] ``` but is this a "Pythonian" way to achieve the goal?
@John: Your snippet doesn't work -- you are returning the *class* of the base classes (which are also known as metaclasses). You really just want `cls.__bases__`: ``` class A: pass class B: pass class C(A, B): pass c = C() # Instance assert C.__bases__ == (A, B) # Works assert c.__class__.__bases__ == (A, B) # Works def magicGetSuperClasses(clz): return tuple([base.__class__ for base in clz.__bases__]) assert magicGetSuperClasses(C) == (A, B) # Fails ``` Also, if you're using Python 2.4+ you can use [generator expressions](http://www.python.org/dev/peps/pep-0289/) instead of creating a list (via []), then turning it into a tuple (via `tuple`). For example: ``` def get_base_metaclasses(cls): """Returns the metaclass of all the base classes of cls.""" return tuple(base.__class__ for base in clz.__bases__) ``` That's a somewhat confusing example, but genexps are generally easy and cool. :)
Is there any difference between "foo is None" and "foo == None"?
26,595
193
2008-08-25T18:27:16Z
26,611
223
2008-08-25T18:38:10Z
[ "python" ]
Is there any difference between: ``` if foo is None: pass ``` and ``` if foo == None: pass ``` The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?
`is` always returns `True` if it compares the same object instance Whereas `==` is ultimately determined by the `__eq__()` method i.e. ``` >>> class foo(object): def __eq__(self, other): return True >>> f = foo() >>> f == None True >>> f is None False ```
Is there any difference between "foo is None" and "foo == None"?
26,595
193
2008-08-25T18:27:16Z
26,626
46
2008-08-25T18:48:20Z
[ "python" ]
Is there any difference between: ``` if foo is None: pass ``` and ``` if foo == None: pass ``` The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?
You may want to read this [object identity and equivalence](http://mail.python.org/pipermail/python-list/2001-November/094920.html). The statement 'is' is used for object identity, it checks if objects refer to the same instance (same address in memory). And the '==' statement refers to equality (same value).
Is there any difference between "foo is None" and "foo == None"?
26,595
193
2008-08-25T18:27:16Z
28,067
21
2008-08-26T13:44:11Z
[ "python" ]
Is there any difference between: ``` if foo is None: pass ``` and ``` if foo == None: pass ``` The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?
A word of caution: ``` if foo: # do something ``` Is **not** exactly the same as: ``` if x is not None: # do something ``` The former is a boolean value test and can evaluate to false in different contexts. There are a number of things that represent false in a boolean value tests for example empty containers, boolean values. None also evaluates to false in this situation but other things do too.
Is there any difference between "foo is None" and "foo == None"?
26,595
193
2008-08-25T18:27:16Z
585,491
12
2009-02-25T10:34:49Z
[ "python" ]
Is there any difference between: ``` if foo is None: pass ``` and ``` if foo == None: pass ``` The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?
`(ob1 is ob2)` equal to `(id(ob1) == id(ob2))`
Is there any difference between "foo is None" and "foo == None"?
26,595
193
2008-08-25T18:27:16Z
2,932,590
10
2010-05-28T21:15:53Z
[ "python" ]
Is there any difference between: ``` if foo is None: pass ``` and ``` if foo == None: pass ``` The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?
The reason `foo is None` is the preferred way is that you might be handling an object that defines its own `__eq__`, and that defines the object to be equal to None. So, always use `foo is None` if you need to see if it is infact `None`.
Is there any difference between "foo is None" and "foo == None"?
26,595
193
2008-08-25T18:27:16Z
16,636,358
8
2013-05-19T15:35:38Z
[ "python" ]
Is there any difference between: ``` if foo is None: pass ``` and ``` if foo == None: pass ``` The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?
There is no difference because objects which are identical will of course be equal. However, [PEP 8](http://www.python.org/dev/peps/pep-0008/ "PEP 8") clearly states you should use `is`: > Comparisons to singletons like None should always be done with is or is not, never the equality operators.
Most Pythonic way equivalent for: while ((x = next()) != END)
28,559
9
2008-08-26T16:37:52Z
426,415
14
2009-01-08T23:06:34Z
[ "c", "python" ]
What's the best Python idiom for this C construct? ``` while ((x = next()) != END) { .... } ``` I don't have the ability to recode next(). update: and the answer from seems to be: ``` for x in iter(next, END): .... ```
@Mark Harrison's answer: ``` for x in iter(next_, END): .... ``` Here's an excerpt from [Python's documentation](http://docs.python.org/library/functions.html): ``` iter(o[, sentinel]) ``` > Return an iterator object. > *...(snip)...* If the second argument, `sentinel`, is given, then `o` must be > a callable object. The iterator > created in this case will call `o` > with no arguments for each call to its > `next()` method; if the value returned > is equal to `sentinel`, > `StopIteration` will be raised, > otherwise the value will be returned.
What refactoring tools do you use for Python?
28,796
52
2008-08-26T18:26:51Z
29,770
43
2008-08-27T09:15:42Z
[ "python", "refactoring" ]
I have a bunch of classes I want to rename. Some of them have names that are small and that name is reused in other class names, where I don't want that name changed. Most of this lives in Python code, but we also have some XML code that references class names. Simple search and replace only gets me so far. In my case, I want to rename AdminAction to AdminActionPlug and AdminActionLogger to AdminActionLoggerPlug, so the first one's search-and-replace would also hit the second, wrongly. Does anyone have experience with Python refactoring tools ? Bonus points if they can fix class names in the XML documents too.
In the meantime, I've tried it two tools that have some sort of integration with vim. The first is [Rope](http://rope.sourceforge.net/), a python refactoring library that comes with a Vim (and emacs) plug-in. I tried it for a few renames, and that definitely worked as expected. It allowed me to preview the refactoring as a diff, which is nice. It is a bit text-driven, but that's alright for me, just takes longer to learn. The second is [Bicycle Repair Man](http://bicyclerepair.sourceforge.net/) which I guess wins points on name. Also plugs into vim and emacs. Haven't played much with it yet, but I remember trying it a long time ago. Haven't played with both enough yet, or tried more types of refactoring, but I will do some more hacking with them.
What refactoring tools do you use for Python?
28,796
52
2008-08-26T18:26:51Z
26,381,548
12
2014-10-15T11:34:58Z
[ "python", "refactoring" ]
I have a bunch of classes I want to rename. Some of them have names that are small and that name is reused in other class names, where I don't want that name changed. Most of this lives in Python code, but we also have some XML code that references class names. Simple search and replace only gets me so far. In my case, I want to rename AdminAction to AdminActionPlug and AdminActionLogger to AdminActionLoggerPlug, so the first one's search-and-replace would also hit the second, wrongly. Does anyone have experience with Python refactoring tools ? Bonus points if they can fix class names in the XML documents too.
I would strongly recommend [PyCharm](https://www.jetbrains.com/pycharm/) - not just for refactorings. Since the first PyCharm answer was posted here a few years ago the refactoring support in PyCharm has improved significantly. [Python Refactorings available in PyCharm](https://www.jetbrains.com/pycharm/webhelp/refactoring-source-code.html) (last checked 2016/07/27 in PyCharm 2016.2) * Change Signature * Convert to Python Package/Module * Copy * Extract Refactorings * Inline * Invert Boolean * Make Top-Level Function * Move Refactorings * Push Members down * Pull Members up * Rename Refactorings * Safe Delete XML refactorings (I checked in context menu in an XML file): * Rename * Move * Copy * Extract Subquery as CTE * Inline Javascript refactorings: * Extract Parameter in JavaScript * Change Signature in JavaScript * Extract Variable in JavaScript
How do I create an xml document in python
29,243
14
2008-08-27T00:21:35Z
29,255
8
2008-08-27T00:35:29Z
[ "python", "xml" ]
Here is my sample code: ``` from xml.dom.minidom import * def make_xml(): doc = Document() node = doc.createElement('foo') node.innerText = 'bar' doc.appendChild(node) return doc if __name__ == '__main__': make_xml().writexml(sys.stdout) ``` when I run the above code I get this: ``` <?xml version="1.0" ?> <foo/> ``` I would like to get: ``` <?xml version="1.0" ?> <foo>bar</foo> ``` I just guessed that there was an innerText property, it gives no compiler error, but does not seem to work... how do I go about creating a text node?
Setting an attribute on an object won't give a compile-time or a run-time error, it will just do nothing useful if the object doesn't access it (i.e. "`node.noSuchAttr = 'bar'`" would also not give an error). Unless you need a specific feature of `minidom`, I would look at `ElementTree`: ``` import sys from xml.etree.cElementTree import Element, ElementTree def make_xml(): node = Element('foo') node.text = 'bar' doc = ElementTree(node) return doc if __name__ == '__main__': make_xml().write(sys.stdout) ```
How do I create an xml document in python
29,243
14
2008-08-27T00:21:35Z
29,262
8
2008-08-27T00:42:32Z
[ "python", "xml" ]
Here is my sample code: ``` from xml.dom.minidom import * def make_xml(): doc = Document() node = doc.createElement('foo') node.innerText = 'bar' doc.appendChild(node) return doc if __name__ == '__main__': make_xml().writexml(sys.stdout) ``` when I run the above code I get this: ``` <?xml version="1.0" ?> <foo/> ``` I would like to get: ``` <?xml version="1.0" ?> <foo>bar</foo> ``` I just guessed that there was an innerText property, it gives no compiler error, but does not seem to work... how do I go about creating a text node?
@Daniel Thanks for the reply, I also figured out how to do it with the minidom (I'm not sure of the difference between the ElementTree vs the minidom) ``` from xml.dom.minidom import * def make_xml(): doc = Document(); node = doc.createElement('foo') node.appendChild(doc.createTextNode('bar')) doc.appendChild(node) return doc if __name__ == '__main__': make_xml().writexml(sys.stdout) ``` I swear I tried this before posting my question...
Python distutils - does anyone know how to use it?
29,562
23
2008-08-27T05:03:07Z
29,575
13
2008-08-27T05:12:47Z
[ "python", "linux", "installer", "debian", "distutils" ]
I wrote a quick program in python to add a gtk GUI to a cli program. I was wondering how I can create an installer using distutils. Since it's just a GUI frontend for a command line app it only works in \*nix anyway so I'm not worried about it being cross platform. my main goal is to create a .deb package for debian/ubuntu users, but I don't understand make/configure files. I've primarily been a web developer up until now. Thanks for your help! **edit**: Does anyone know of a project that uses distutils so I could see it in action and, you know, actually try building it? ## Here are a few useful links * [Ubuntu Python Packaging Guide](https://wiki.ubuntu.com/PackagingGuide/Python) This Guide is ***very*** helpful. I don't know how I missed it during my initial wave of gooling. It even walks you through packaging up an existing python application * [The Ubuntu MOTU Project](https://wiki.ubuntu.com/MOTU/GettingStarted) This is the official package maintaining project at ubuntu. Anyone can join, and there are lots of tutorials and info about creating packages, of all types, which include the above 'python packaging guide'. * ["Python distutils to deb?" - Ars Technica Forum discussion](http://episteme.arstechnica.com/eve/forums/a/tpc/f/96509133/m/808004952931) According to this conversation, you can't just use distutils. It doesn't follow the debian packaging format (or something like that). I guess that's why you need dh\_make as seen in the Ubuntu Packaging guide * ["A bdist\_deb command for distutils](http://osdir.com/ml/linux.debian.devel.python/2004-10/msg00013.html) This one has some interesting discussion (it's also how I found the ubuntu guide) about concatenating a zip-file and a shell script to create some kind of universal executable (anything with python and bash that is). weird. Let me know if anyone finds more info on this practice because I've never heard of it. * [Description of the deb format and how distutils fit in - python mailing list](http://mail.python.org/pipermail/distutils-sig/2000-May/001000.html)
See the [distutils simple example](http://docs.python.org/dist/simple-example.html). That's basically what it is like, except real install scripts usually contain a bit more information. I have not seen any that are fundamentally more complicated, though. In essence, you just give it a list of what needs to be installed. Sometimes you need to give it some mapping dicts since the source and installed trees might not be the same. Here is a real-life (anonymized) example: ``` #!/usr/bin/python from distutils.core import setup setup (name = 'Initech Package 3', description = "Services and libraries ABC, DEF", author = "That Guy, Initech Ltd", author_email = "[email protected]", version = '1.0.5', package_dir = {'Package3' : 'site-packages/Package3'}, packages = ['Package3', 'Package3.Queries'], data_files = [ ('/etc/Package3', ['etc/Package3/ExternalResources.conf']) ]) ```
How do threads work in Python, and what are common Python-threading specific pitfalls?
31,340
71
2008-08-27T23:44:47Z
31,358
18
2008-08-27T23:52:59Z
[ "python", "multithreading" ]
I've been trying to wrap my head around how threads work in Python, and it's hard to find good information on how they operate. I may just be missing a link or something, but it seems like the official documentation isn't very thorough on the subject, and I haven't been able to find a good write-up. From what I can tell, only one thread can be running at once, and the active thread switches every 10 instructions or so? Where is there a good explanation, or can you provide one? It would also be very nice to be aware of common problems that you run into while using threads with Python.
Below is a basic threading sample. It will spawn 20 threads; each thread will output its thread number. Run it and observe the order in which they print. ``` import threading class Foo (threading.Thread): def __init__(self,x): self.__x = x threading.Thread.__init__(self) def run (self): print str(self.__x) for x in xrange(20): Foo(x).start() ``` As you have hinted at Python threads are implemented through time-slicing. This is how they get the "parallel" effect. In my example my Foo class extends thread, I then implement the `run` method, which is where the code that you would like to run in a thread goes. To start the thread you call `start()` on the thread object, which will automatically invoke the `run` method... Of course, this is just the very basics. You will eventually want to learn about semaphores, mutexes, and locks for thread synchronization and message passing.
How do threads work in Python, and what are common Python-threading specific pitfalls?
31,340
71
2008-08-27T23:44:47Z
31,372
32
2008-08-28T00:00:18Z
[ "python", "multithreading" ]
I've been trying to wrap my head around how threads work in Python, and it's hard to find good information on how they operate. I may just be missing a link or something, but it seems like the official documentation isn't very thorough on the subject, and I haven't been able to find a good write-up. From what I can tell, only one thread can be running at once, and the active thread switches every 10 instructions or so? Where is there a good explanation, or can you provide one? It would also be very nice to be aware of common problems that you run into while using threads with Python.
Python's a fairly easy language to thread in, but there are caveats. The biggest thing you need to know about is the Global Interpreter Lock. This allows only one thread to access the interpreter. This means two things: 1) you rarely ever find yourself using a lock statement in python and 2) if you want to take advantage of multi-processor systems, you have to use separate processes. EDIT: I should also point out that you can put some of the code in C/C++ if you want to get around the GIL as well. Thus, you need to re-consider why you want to use threads. If you want to parallelize your app to take advantage of dual-core architecture, you need to consider breaking your app up into multiple processes. If you want to improve responsiveness, you should CONSIDER using threads. There are other alternatives though, namely [microthreading](http://en.wikipedia.org/wiki/Microthread). There are also some frameworks that you should look into: * [stackless python](http://www.stackless.com/) * [greenlets](http://greenlet.readthedocs.org/en/latest/) * [gevent](http://www.gevent.org/) * [monocle](https://github.com/saucelabs/monocle)
How do threads work in Python, and what are common Python-threading specific pitfalls?
31,340
71
2008-08-27T23:44:47Z
31,398
41
2008-08-28T00:19:50Z
[ "python", "multithreading" ]
I've been trying to wrap my head around how threads work in Python, and it's hard to find good information on how they operate. I may just be missing a link or something, but it seems like the official documentation isn't very thorough on the subject, and I haven't been able to find a good write-up. From what I can tell, only one thread can be running at once, and the active thread switches every 10 instructions or so? Where is there a good explanation, or can you provide one? It would also be very nice to be aware of common problems that you run into while using threads with Python.
Yes, because of the Global Interpreter Lock (GIL) there can only run one thread at a time. Here are some links with some insights about this: * <http://www.artima.com/weblogs/viewpost.jsp?thread=214235> * <http://smoothspan.wordpress.com/2007/09/14/guido-is-right-to-leave-the-gil-in-python-not-for-multicore-but-for-utility-computing/> From the last link an interesting quote: > Let me explain what all that means. > Threads run inside the same virtual > machine, and hence run on the same > physical machine. Processes can run > on the same physical machine or in > another physical machine. If you > architect your application around > threads, you’ve done nothing to access > multiple machines. So, you can scale > to as many cores are on the single > machine (which will be quite a few > over time), but to really reach web > scales, you’ll need to solve the > multiple machine problem anyway. If you want to use multi core, [pyprocessing](http://www.python.org/dev/peps/pep-0371/) defines an process based API to do real parallelization. The [PEP](http://en.wikipedia.org/wiki/Python_Enhancement_Proposal#Development) also includes some interesting benchmarks.
How do threads work in Python, and what are common Python-threading specific pitfalls?
31,340
71
2008-08-27T23:44:47Z
31,552
9
2008-08-28T02:34:18Z
[ "python", "multithreading" ]
I've been trying to wrap my head around how threads work in Python, and it's hard to find good information on how they operate. I may just be missing a link or something, but it seems like the official documentation isn't very thorough on the subject, and I haven't been able to find a good write-up. From what I can tell, only one thread can be running at once, and the active thread switches every 10 instructions or so? Where is there a good explanation, or can you provide one? It would also be very nice to be aware of common problems that you run into while using threads with Python.
Use threads in python if the individual workers are doing I/O bound operations. If you are trying to scale across multiple cores on a machine either find a good [IPC](http://www.python.org/dev/peps/pep-0371/) framework for python or pick a different language.
How can I render a tree structure (recursive) using a django template?
32,044
44
2008-08-28T11:43:10Z
32,125
23
2008-08-28T12:47:29Z
[ "python", "django" ]
I have a tree structure in memory that I would like to render in HTML using a Django template. ``` class Node(): name = "node name" children = [] ``` There will be some object `root` that is a `Node`, and `children` is a list of `Node`s. `root` will be passed in the content of the template. I have found [this](http://blog.elsdoerfer.name/2008/01/22/recursion-in-django-templates/) one discussion of how this might be achieved, but the poster suggests this might not be good in a production environment. Does anybody know of a better way?
I think the canonical answer is: "Don't". What you should probably do instead is unravel the thing in your *view* code, so it's just a matter of iterating over (in|de)dents in the template. I think I'd do it by appending indents and dedents to a list while recursing through the tree and then sending that "travelogue" list to the template. (the template would then insert `<li>` and `</li>` from that list, creating the recursive structure with "understanding" it.) I'm also pretty sure recursively including template files is really a *wrong* way to do it...
How can I render a tree structure (recursive) using a django template?
32,044
44
2008-08-28T11:43:10Z
32,857
18
2008-08-28T17:23:22Z
[ "python", "django" ]
I have a tree structure in memory that I would like to render in HTML using a Django template. ``` class Node(): name = "node name" children = [] ``` There will be some object `root` that is a `Node`, and `children` is a list of `Node`s. `root` will be passed in the content of the template. I have found [this](http://blog.elsdoerfer.name/2008/01/22/recursion-in-django-templates/) one discussion of how this might be achieved, but the poster suggests this might not be good in a production environment. Does anybody know of a better way?
this might be way more than you need, but there is a django module called 'mptt' - this stores a hierarchical tree structure in an sql database, and includes templates for display in the view code. you might be able to find something useful there. here's the link : [django-mptt](https://github.com/django-mptt/django-mptt/)
How can I render a tree structure (recursive) using a django template?
32,044
44
2008-08-28T11:43:10Z
48,262
9
2008-09-07T08:49:51Z
[ "python", "django" ]
I have a tree structure in memory that I would like to render in HTML using a Django template. ``` class Node(): name = "node name" children = [] ``` There will be some object `root` that is a `Node`, and `children` is a list of `Node`s. `root` will be passed in the content of the template. I have found [this](http://blog.elsdoerfer.name/2008/01/22/recursion-in-django-templates/) one discussion of how this might be achieved, but the poster suggests this might not be good in a production environment. Does anybody know of a better way?
Django has a built in template helper for this exact scenario: <https://docs.djangoproject.com/en/dev/ref/templates/builtins/#unordered-list>
How can I render a tree structure (recursive) using a django template?
32,044
44
2008-08-28T11:43:10Z
957,761
7
2009-06-05T19:40:13Z
[ "python", "django" ]
I have a tree structure in memory that I would like to render in HTML using a Django template. ``` class Node(): name = "node name" children = [] ``` There will be some object `root` that is a `Node`, and `children` is a list of `Node`s. `root` will be passed in the content of the template. I have found [this](http://blog.elsdoerfer.name/2008/01/22/recursion-in-django-templates/) one discussion of how this might be achieved, but the poster suggests this might not be good in a production environment. Does anybody know of a better way?
I had the same problem and I wrote a template tag. I know there are other tags like this out there but I needed to learn to make custom tags anyway :) I think it turned out pretty well. Read the docstring for usage instructions. [github.com/skid/django-recurse](http://github.com/skid/django-recurse)
How can I render a tree structure (recursive) using a django template?
32,044
44
2008-08-28T11:43:10Z
11,644,588
51
2012-07-25T07:21:27Z
[ "python", "django" ]
I have a tree structure in memory that I would like to render in HTML using a Django template. ``` class Node(): name = "node name" children = [] ``` There will be some object `root` that is a `Node`, and `children` is a list of `Node`s. `root` will be passed in the content of the template. I have found [this](http://blog.elsdoerfer.name/2008/01/22/recursion-in-django-templates/) one discussion of how this might be achieved, but the poster suggests this might not be good in a production environment. Does anybody know of a better way?
Using `with` template tag, I could do tree/recursive list. Sample code: main template: assuming 'all\_root\_elems' is list of one or more root of tree ``` <ul> {%for node in all_root_elems %} {%include "tree_view_template.html" %} {%endfor%} </ul> ``` tree\_view\_template.html renders the nested `ul`, `li` and uses `node` template variable as below: ``` <li> {{node.name}} {%if node.has_childs %} <ul> {%for ch in node.all_childs %} {%with node=ch template_name="tree_view_template.html" %} {%include template_name%} {%endwith%} {%endfor%} </ul> {%endif%} </li> ```
How can I render a tree structure (recursive) using a django template?
32,044
44
2008-08-28T11:43:10Z
12,558,610
9
2012-09-24T03:50:27Z
[ "python", "django" ]
I have a tree structure in memory that I would like to render in HTML using a Django template. ``` class Node(): name = "node name" children = [] ``` There will be some object `root` that is a `Node`, and `children` is a list of `Node`s. `root` will be passed in the content of the template. I have found [this](http://blog.elsdoerfer.name/2008/01/22/recursion-in-django-templates/) one discussion of how this might be achieved, but the poster suggests this might not be good in a production environment. Does anybody know of a better way?
Yes, you can do it. It's a little trick, passing the filename to {% include %} as a variable: ``` {% with template_name="file/to_include.html" %} {% include template_name %} {% endwith %} ```
Is it possible to run a Python script as a service in Windows? If possible, how?
32,404
165
2008-08-28T14:28:04Z
32,440
169
2008-08-28T14:39:04Z
[ "python", "windows", "cross-platform" ]
I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which provides a higher level interface for operations on these objects, and the other programs to access the objects through that service. I am currently aiming for Python and the Django framework as the technologies to implement that service with. I'm pretty sure I figure how to demonize the Python program in Linux. However, it is an optional spec item that the system should support Windows. I have little experience with Windows programming and no experience at all with Windows services. **Is it possible to run a Python programs as a Windows service (i. e. run it automatically without user login)?** I won't necessarily have to implement this part, but I need a rough idea how it would be done in order to decide whether to design along these lines. *Edit: Thanks for all the answers so far, they are quite comprehensive. I would like to know one more thing: **How is Windows aware of my service? Can I manage it with the native Windows utilities?** **Basically, what is the equivalent of putting a start/stop script in /etc/init.d?***
Yes you can. I do it using the pythoncom libraries that come included with [ActivePython](http://www.activestate.com/Products/activepython/index.mhtml) or can be installed with [pywin32](https://sourceforge.net/projects/pywin32/) (Python for Windows extensions). This is a basic skeleton for a simple service: ``` import win32serviceutil import win32service import win32event import servicemanager import socket class AppServerSvc (win32serviceutil.ServiceFramework): _svc_name_ = "TestService" _svc_display_name_ = "Test Service" def __init__(self,args): win32serviceutil.ServiceFramework.__init__(self,args) self.hWaitStop = win32event.CreateEvent(None,0,0,None) socket.setdefaulttimeout(60) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_,'')) self.main() def main(self): pass if __name__ == '__main__': win32serviceutil.HandleCommandLine(AppServerSvc) ``` Your code would go in the main() method, usually with some kind of infinite loop that might be interrumped by checking a flag, that you set in the SvcStop method
Is it possible to run a Python script as a service in Windows? If possible, how?
32,404
165
2008-08-28T14:28:04Z
597,750
19
2009-02-28T08:30:54Z
[ "python", "windows", "cross-platform" ]
I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which provides a higher level interface for operations on these objects, and the other programs to access the objects through that service. I am currently aiming for Python and the Django framework as the technologies to implement that service with. I'm pretty sure I figure how to demonize the Python program in Linux. However, it is an optional spec item that the system should support Windows. I have little experience with Windows programming and no experience at all with Windows services. **Is it possible to run a Python programs as a Windows service (i. e. run it automatically without user login)?** I won't necessarily have to implement this part, but I need a rough idea how it would be done in order to decide whether to design along these lines. *Edit: Thanks for all the answers so far, they are quite comprehensive. I would like to know one more thing: **How is Windows aware of my service? Can I manage it with the native Windows utilities?** **Basically, what is the equivalent of putting a start/stop script in /etc/init.d?***
There are a couple alternatives for installing as a service virtually any Windows executable. ## Method 1: Use instsrv and srvany from rktools.exe For Windows Home Server or Windows Server 2003 (works with WinXP too), the [Windows Server 2003 Resource Kit Tools](http://www.microsoft.com/downloads/details.aspx?FamilyID=9D467A69-57FF-4AE7-96EE-B18C4790CFFD&displaylang=en) comes with utilities that can be used in tandem for this, called **instsrv.exe** and **srvany.exe**. See this Microsoft KB article [KB137890](http://support.microsoft.com/kb/137890) for details on how to use these utils. For Windows Home Server, there is a great user friendly wrapper for these utilities named aptly "[Any Service Installer](http://forum.wegotserved.com/index.php?autocom=downloads&showfile=7)". ## Method 2: Use ServiceInstaller for Windows NT There is another alternative using [ServiceInstaller for Windows NT](http://www.kcmultimedia.com/smaster/) ([download-able here](http://www.kcmultimedia.com/smaster/download.html)) with [python instructions available](http://conort.googlepages.com/runanywindowsapplicationasntservice). Contrary to the name, it works with both Windows 2000 and Windows XP as well. Here are some instructions for how to install a python script as a service. > **Installing a Python script** > > Run ServiceInstaller to create a new > service. (In this example, it is > assumed that python is installed at > c:\python25) > > ``` > Service Name : PythonTest > Display Name : PythonTest > Startup : Manual (or whatever you like) > Dependencies : (Leave blank or fill to fit your needs) > Executable : c:\python25\python.exe > Arguments : c:\path_to_your_python_script\test.py > Working Directory : c:\path_to_your_python_script > ``` > > After installing, open the Control > Panel's Services applet, select and > start the PythonTest service. After my initial answer, I noticed there were closely related Q&A already posted on SO. See also: [Can I run a Python script as a service (in Windows)? How?](http://stackoverflow.com/questions/32404/can-i-run-a-python-script-as-a-service-in-windows-how) [How do I make Windows aware of a service I have written in Python?](http://stackoverflow.com/questions/34328/how-do-i-make-windows-aware-of-a-service-i-have-written-in-python)
Is it possible to run a Python script as a service in Windows? If possible, how?
32,404
165
2008-08-28T14:28:04Z
24,996,607
17
2014-07-28T13:41:31Z
[ "python", "windows", "cross-platform" ]
I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which provides a higher level interface for operations on these objects, and the other programs to access the objects through that service. I am currently aiming for Python and the Django framework as the technologies to implement that service with. I'm pretty sure I figure how to demonize the Python program in Linux. However, it is an optional spec item that the system should support Windows. I have little experience with Windows programming and no experience at all with Windows services. **Is it possible to run a Python programs as a Windows service (i. e. run it automatically without user login)?** I won't necessarily have to implement this part, but I need a rough idea how it would be done in order to decide whether to design along these lines. *Edit: Thanks for all the answers so far, they are quite comprehensive. I would like to know one more thing: **How is Windows aware of my service? Can I manage it with the native Windows utilities?** **Basically, what is the equivalent of putting a start/stop script in /etc/init.d?***
Although I upvoted the chosen answer a couple of weeks back, in the meantime I struggled a lot more with this topic. It feels like having a special Python installation and using special modules to run a script as a service is simply the wrong way. What about portability and such? I stumbled across the wonderful [Non-sucking Service Manager](http://nssm.cc/), which made it really simple and sane to deal with Windows Services. I figured since I could pass options to an installed service, I could just as well select my Python executable and pass my script as an option. I have not yet tried this solution, but I will do so right now and update this post along the process. I am also interested in using virtualenvs on Windows, so I might come up with a tutorial sooner or later and link to it here.
How to generate dynamic (parametrized) unit tests in python?
32,899
111
2008-08-28T17:49:02Z
32,939
75
2008-08-28T18:02:33Z
[ "python", "unit-testing", "parameterized-unit-test" ]
I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this: ``` import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() ``` The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?
i use something like this: ``` import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequense(unittest.TestCase): pass def test_generator(a, b): def test(self): self.assertEqual(a,b) return test if __name__ == '__main__': for t in l: test_name = 'test_%s' % t[0] test = test_generator(t[1], t[2]) setattr(TestSequense, test_name, test) unittest.main() ``` The [`nose-parameterized`](https://github.com/wolever/nose-parameterized) package can be used to automate this process: ``` from nose_parameterized import parameterized class TestSequence(unittest.TestCase): @parameterized.expand([ ["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"], ]) def test_sequence(self, name, a, b): self.assertEqual(a,b) ``` Which will generate the tests: ``` test_sequence_0_foo (__main__.TestSequence) ... ok test_sequence_1_bar (__main__.TestSequence) ... FAIL test_sequence_2_lee (__main__.TestSequence) ... ok ====================================================================== FAIL: test_sequence_1_bar (__main__.TestSequence) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/nose_parameterized/parameterized.py", line 233, in <lambda> standalone_func = lambda *a: func(*(a + p.args), **p.kwargs) File "x.py", line 12, in test_sequence self.assertEqual(a,b) AssertionError: 'a' != 'b' ```
How to generate dynamic (parametrized) unit tests in python?
32,899
111
2008-08-28T17:49:02Z
34,094
48
2008-08-29T07:10:31Z
[ "python", "unit-testing", "parameterized-unit-test" ]
I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this: ``` import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() ``` The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?
The [nose](https://nose.readthedocs.org/en/latest/) testing framework [supports this](https://nose.readthedocs.org/en/latest/writing_tests.html#test-generators). Example (the code below is the entire contents of the file containing the test): ``` param_list = [('a', 'a'), ('a', 'b'), ('b', 'b')] def test_generator(): for params in param_list: yield check_em, params[0], params[1] def check_em(a, b): assert a == b ``` The output of the nosetests command: ``` > nosetests -v testgen.test_generator('a', 'a') ... ok testgen.test_generator('a', 'b') ... FAIL testgen.test_generator('b', 'b') ... ok ====================================================================== FAIL: testgen.test_generator('a', 'b') ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/python2.5/site-packages/nose-0.10.1-py2.5.egg/nose/case.py", line 203, in runTest self.test(*self.arg) File "testgen.py", line 7, in check_em assert a == b AssertionError ---------------------------------------------------------------------- Ran 3 tests in 0.006s FAILED (failures=1) ```
How to generate dynamic (parametrized) unit tests in python?
32,899
111
2008-08-28T17:49:02Z
20,870,875
31
2014-01-01T16:52:24Z
[ "python", "unit-testing", "parameterized-unit-test" ]
I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this: ``` import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() ``` The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?
This can be solved elegantly using Metaclasses: ``` import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequenceMeta(type): def __new__(mcs, name, bases, dict): def gen_test(a, b): def test(self): self.assertEqual(a, b) return test for tname, a, b in l: test_name = "test_%s" % tname dict[test_name] = gen_test(a,b) return type.__new__(mcs, name, bases, dict) class TestSequence(unittest.TestCase): __metaclass__ = TestSequenceMeta if __name__ == '__main__': unittest.main() ```
How to generate dynamic (parametrized) unit tests in python?
32,899
111
2008-08-28T17:49:02Z
23,508,426
18
2014-05-07T03:55:21Z
[ "python", "unit-testing", "parameterized-unit-test" ]
I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this: ``` import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() ``` The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?
[load\_tests](https://docs.python.org/2/library/unittest.html#load-tests-protocol) is a little known mechanism introduced in 2.7 to dynamically create a TestSuite. With it, you can easily create parametrized tests. For example: ``` import unittest class GeneralTestCase(unittest.TestCase): def __init__(self, methodName, param1=None, param2=None): super(GeneralTestCase, self).__init__(methodName) self.param1 = param1 self.param2 = param2 def runTest(self): pass # Test that depends on param 1 and 2. def load_tests(loader, tests, pattern): test_cases = unittest.TestSuite() for p1, p2 in [(1, 2), (3, 4)]: test_cases.addTest(GeneralTestCase('runTest', p1, p2)) return test_cases ``` That code will run all the TestCases in the TestSuite returned by load\_tests. No other tests are automatically run by the discovery mechanism. Alternatively, you can also use inheritance as shown in this ticket: <http://bugs.python.org/msg151444>
How to generate dynamic (parametrized) unit tests in python?
32,899
111
2008-08-28T17:49:02Z
25,626,660
12
2014-09-02T15:08:01Z
[ "python", "unit-testing", "parameterized-unit-test" ]
I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this: ``` import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() ``` The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?
It can be done by using [pytest](http://pytest.org). Just write the file `test_me.py` with content: ``` import pytest @pytest.mark.parametrize('name, left, right', [['foo', 'a', 'a'], ['bar', 'a', 'b'], ['baz', 'b', 'b']]) def test_me(name, left, right): assert left == right, name ``` And run your test with command `py.test --tb=short test_me.py`. Then the output will be looks like: ``` =========================== test session starts ============================ platform darwin -- Python 2.7.6 -- py-1.4.23 -- pytest-2.6.1 collected 3 items test_me.py .F. ================================= FAILURES ================================= _____________________________ test_me[bar-a-b] _____________________________ test_me.py:8: in test_me assert left == right, name E AssertionError: bar ==================== 1 failed, 2 passed in 0.01 seconds ==================== ``` It simple!. Also [pytest](http://pytest.org) has more features like `fixtures`, `mark`, `assert`, etc ...
How to generate dynamic (parametrized) unit tests in python?
32,899
111
2008-08-28T17:49:02Z
29,384,495
13
2015-04-01T06:46:45Z
[ "python", "unit-testing", "parameterized-unit-test" ]
I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this: ``` import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() ``` The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?
As of Python 3.4 subtests have been introduced to unittest for this purpose. See [the documentation](https://docs.python.org/3/library/unittest.html#distinguishing-test-iterations-using-subtests) for details. TestCase.subTest is a context manager which allows to isolate asserts in a test so that a failure will be reported with parameter information but does not stop the test execution. Here's the example from the documentation: ``` class NumbersTest(unittest.TestCase): def test_even(self): """ Test that numbers between 0 and 5 are all even. """ for i in range(0, 6): with self.subTest(i=i): self.assertEqual(i % 2, 0) ``` The output of a test run would be: ``` ====================================================================== FAIL: test_even (__main__.NumbersTest) (i=1) ---------------------------------------------------------------------- Traceback (most recent call last): File "subtests.py", line 32, in test_even self.assertEqual(i % 2, 0) AssertionError: 1 != 0 ====================================================================== FAIL: test_even (__main__.NumbersTest) (i=3) ---------------------------------------------------------------------- Traceback (most recent call last): File "subtests.py", line 32, in test_even self.assertEqual(i % 2, 0) AssertionError: 1 != 0 ====================================================================== FAIL: test_even (__main__.NumbersTest) (i=5) ---------------------------------------------------------------------- Traceback (most recent call last): File "subtests.py", line 32, in test_even self.assertEqual(i % 2, 0) AssertionError: 1 != 0 ``` This is also part of [unittest2](https://pypi.python.org/pypi/unittest2), so it is available for earlier versions of Python.
Extending base classes in Python
33,534
10
2008-08-28T22:18:02Z
33,663
22
2008-08-28T23:41:55Z
[ "python" ]
I'm trying to extend some "base" classes in Python: ``` class xlist (list): def len(self): return len(self) def add(self, *args): self.extend(args) return None class xint (int): def add(self, value): self += value return self x = xlist([1,2,3]) print x.len() ## >>> 3 ok print x ## >>> [1,2,3] ok x.add (4, 5, 6) print x ## >>> [1,2,3,4,5,6] ok x = xint(10) print x ## >>> 10 ok x.add (2) print x ## >>> 10 # Not ok (#1) print type(x) ## >>> <class '__main__.xint'> ok x += 5 print type(x) ## >>> <type 'int'> # Not ok (#2) ``` It works fine in the *list* case because the *append* method modifies the object "in place", without returning it. But in the *int* case, the *add* method doesn't modify the value of the external *x* variable. I suppose that's fine in the sense that *self* is a local variable in the *add* method of the class, but this is preventing me from modifying the initial value assigned to the instance of the class. Is it possible to extend a class this way or should I define a class property with the base type and map all the needed methods to this property?
Your two `xint` examples don't work for two different reasons. The first doesn't work because `self += value` is equivalent to `self = self + value` which just reassigns the local variable `self` to a different object (an integer) but doesn't change the original object. You can't really get this ``` >>> x = xint(10) >>> x.add(2) ``` to work with a subclass of `int` since integers are [immutable](http://docs.python.org/ref/objects.html). To get the second one to work you can define an [`__add__` method](http://docs.python.org/ref/numeric-types.html), like so: ``` class xint(int): def __add__(self, value): return xint(int.__add__(self, value)) >>> x = xint(10) >>> type(x) <class '__main__.xint'> >>> x += 3 >>> x 13 >>> type(x) <class '__main__.xint'> ```
Find out how much memory is being used by an object in Python
33,978
117
2008-08-29T04:59:31Z
35,645
67
2008-08-30T03:25:43Z
[ "python", "performance", "memory-profiling" ]
How would you go about finding out how much memory is being used by an object? I know it is possible to find out how much is used by a block of code, but not by an instantiated object (anytime during its life), which is what I want.
**There's no easy way to find out the memory size of a python object**. One of the problems you may find is that Python objects - like lists and dicts - may have references to other python objects (in this case, what would your size be? The size containing the size of each object or not?). There are some pointers overhead and internal structures related to object types and garbage collection. Finally, some python objects have non-obvious behaviors. For instance, lists reserve space for more objects than they have, most of the time; dicts are even more complicated since they can operate in different ways (they have a different implementation for small number of keys and sometimes they over allocate entries). There is a [big chunk of code](http://code.activestate.com/recipes/544288/) (and an [updated big chunk of code](http://code.activestate.com/recipes/546530/)) out there to try to best approximate the size of a python object in memory. There's also some [simpler approximations](https://mail.python.org/pipermail/python-list/2008-January/483475.html). But they will always be approximations. You may also want to check some [old description about PyObject](http://mail.python.org/pipermail/python-list/2002-March/135223.html) (the internal C struct that represents virtually all python objects).
Find out how much memory is being used by an object in Python
33,978
117
2008-08-29T04:59:31Z
12,924,399
14
2012-10-16T22:25:06Z
[ "python", "performance", "memory-profiling" ]
How would you go about finding out how much memory is being used by an object? I know it is possible to find out how much is used by a block of code, but not by an instantiated object (anytime during its life), which is what I want.
Another approach is to use pickle. See [this answer](http://stackoverflow.com/a/565382/420867) to a duplicate of this question.
Find out how much memory is being used by an object in Python
33,978
117
2008-08-29T04:59:31Z
19,865,746
24
2013-11-08T18:11:11Z
[ "python", "performance", "memory-profiling" ]
How would you go about finding out how much memory is being used by an object? I know it is possible to find out how much is used by a block of code, but not by an instantiated object (anytime during its life), which is what I want.
Try this: ``` sys.getsizeof(object) ``` [getsizeof()](https://docs.python.org/3/library/sys.html#sys.getsizeof) calls the object’s `__sizeof__` method and adds an additional garbage collector overhead **if** the object is managed by the garbage collector.
Are Python threads buggy?
34,020
17
2008-08-29T05:43:16Z
34,060
43
2008-08-29T06:33:54Z
[ "python", "multithreading" ]
A reliable coder friend told me that Python's current multi-threading implementation is seriously buggy - enough to avoid using altogether. What can said about this rumor?
Python threads are good for **concurrent I/O programming**. Threads are swapped out of the CPU as soon as they block waiting for input from file, network, etc. This allows other Python threads to use the CPU while others wait. This would allow you to write a multi-threaded web server or web crawler, for example. However, Python threads are serialized by the [GIL](http://en.wikipedia.org/wiki/Global_Interpreter_Lock) when they enter interpreter core. This means that if two threads are crunching numbers, only one can run at any given moment. It also means that you can't take advantage of multi-core or multi-processor architectures. There are solutions like running multiple Python interpreters concurrently, using a C based threading library. This is not for the faint of heart and the benefits might not be worth the trouble. Let's hope for an all Python solution in a future release.
Are Python threads buggy?
34,020
17
2008-08-29T05:43:16Z
34,078
7
2008-08-29T06:55:14Z
[ "python", "multithreading" ]
A reliable coder friend told me that Python's current multi-threading implementation is seriously buggy - enough to avoid using altogether. What can said about this rumor?
The GIL (Global Interpreter Lock) might be a problem, but the API is quite OK. Try out the excellent `processing` module, which implements the Threading API for separate processes. I am using that right now (albeit on OS X, have yet to do some testing on Windows) and am really impressed. The Queue class is really saving my bacon in terms of managing complexity! **EDIT**: it seemes the processing module is being included in the standard library as of version 2.6 (`import multiprocessing`). Joy!
Are Python threads buggy?
34,020
17
2008-08-29T05:43:16Z
34,782
13
2008-08-29T17:17:18Z
[ "python", "multithreading" ]
A reliable coder friend told me that Python's current multi-threading implementation is seriously buggy - enough to avoid using altogether. What can said about this rumor?
The standard implementation of Python (generally known as CPython as it is written in C) uses OS threads, but since there is the [Global Interpreter Lock](http://en.wikipedia.org/wiki/Global_Interpreter_Lock), only one thread at a time is allowed to run Python code. But within those limitations, the threading libraries are robust and widely used. If you want to be able to use multiple CPU cores, there are a few options. One is to use multiple python interpreters concurrently, as mentioned by others. Another option is to use a different implementation of Python that does not use a GIL. The two main options are [Jython](http://en.wikipedia.org/wiki/Jython) and [IronPython](http://en.wikipedia.org/wiki/IronPython). Jython is written in Java, and is now fairly mature, though some incompatibilities remain. For example, the web framework [Django does not run perfectly yet](http://zyasoft.com/pythoneering/2008/01/django-on-jython-minding-gap.html), but is getting closer all the time. Jython is [great for thread safety](http://mail.python.org/pipermail/python-list/2001-December/116555.html), comes out [better in benchmarks](http://blogs.warwick.ac.uk/dwatkins/entry/benchmarking_parallel_python_1_2/) and has a [cheeky message for those wanting the GIL](http://cgwalters.livejournal.com/17956.html). IronPython uses the .NET framework and is written in C#. Compatibility is reaching the stage where [Django can run on IronPython](http://www.infoq.com/news/2008/03/django-and-ironpython) (at least as a demo) and there are [guides to using threads in IronPython](http://www.voidspace.org.uk/ironpython/threading.shtml).
How to specify an authenticated proxy for a python http connection?
34,079
44
2008-08-29T06:55:54Z
34,116
53
2008-08-29T07:30:35Z
[ "python", "http", "proxy" ]
What's the best way to specify a proxy with username and password for an http connection in python?
This works for me: ``` import urllib2 proxy = urllib2.ProxyHandler({'http': 'http:// username:password@proxyurl:proxyport'}) auth = urllib2.HTTPBasicAuthHandler() opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler) urllib2.install_opener(opener) conn = urllib2.urlopen('http://python.org') return_str = conn.read() ```
How to specify an authenticated proxy for a python http connection?
34,079
44
2008-08-29T06:55:54Z
35,443
8
2008-08-29T22:52:47Z
[ "python", "http", "proxy" ]
What's the best way to specify a proxy with username and password for an http connection in python?
The best way of going through a proxy that requires authentication is using [urllib2](http://docs.python.org/lib/module-urllib2.html) to build a custom url opener, then using that to make all the requests you want to go through the proxy. Note in particular, you probably don't want to embed the proxy password in the url or the python source code (unless it's just a quick hack). ``` import urllib2 def get_proxy_opener(proxyurl, proxyuser, proxypass, proxyscheme="http"): password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None, proxyurl, proxyuser, proxypass) proxy_handler = urllib2.ProxyHandler({proxyscheme: proxyurl}) proxy_auth_handler = urllib2.ProxyBasicAuthHandler(password_mgr) return urllib2.build_opener(proxy_handler, proxy_auth_handler) if __name__ == "__main__": import sys if len(sys.argv) > 4: url_opener = get_proxy_opener(*sys.argv[1:4]) for url in sys.argv[4:]: print url_opener.open(url).headers else: print "Usage:", sys.argv[0], "proxy user pass fetchurls..." ``` In a more complex program, you can seperate these components out as appropriate (for instance, only using one password manager for the lifetime of the application). The python documentation has [more examples on how to do complex things with urllib2](http://docs.python.org/lib/urllib2-examples.html) that you might also find useful.
How to specify an authenticated proxy for a python http connection?
34,079
44
2008-08-29T06:55:54Z
3,942,980
11
2010-10-15T14:06:56Z
[ "python", "http", "proxy" ]
What's the best way to specify a proxy with username and password for an http connection in python?
Setting an environment var named **http\_proxy** like this: **http://username:password@proxy\_url:port**
How do I make Windows aware of a service I have written in Python?
34,328
10
2008-08-29T10:18:21Z
34,330
8
2008-08-29T10:20:39Z
[ "python", "windows", "cross-platform" ]
In [another question](http://stackoverflow.com/questions/32404/can-i-run-a-python-script-as-a-service-in-windows-how "Python scripts as Windows service") I posted yesterday, I got very good advice on how a Python script could be run as a service in Windows. What I'm left wondering is: How is Windows aware of the services that can be managed in the native tools ("services" window in "administrative tools"). I. e. what is the Windows equivalent of putting a start/stop script in /etc/init.d under Linux?
Here is code to install a python-script as a service, written in python :) <http://code.activestate.com/recipes/551780/> This post could also help you out: <http://essiene.blogspot.com/2005/04/python-windows-services.html>
Finding what methods an object has
34,439
159
2008-08-29T15:05:17Z
34,452
188
2008-08-29T15:09:05Z
[ "python", "introspection" ]
Given a Python object of any kind, is there an easy way to get a list of all methods that this object has? Or, if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called?
It appears you can use this code, replacing 'object' with the object you're interested in:- ``` [method for method in dir(object) if callable(getattr(object, method))] ``` I discovered it at [this site](http://www.diveintopython.net/power_of_introspection/index.html), hopefully that should provide some further detail!
Finding what methods an object has
34,439
159
2008-08-29T15:05:17Z
34,467
78
2008-08-29T15:36:55Z
[ "python", "introspection" ]
Given a Python object of any kind, is there an easy way to get a list of all methods that this object has? Or, if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called?
You can use the built in `dir()` function to get a list of all the attributes a module has. Try this at the command line to see how it works. ``` >>> import moduleName >>> dir(moduleName) ``` Also, you can use the `hasattr(module_name, "attr_name")` function to find out if a module has a specific attribute. See the [Guide to Python introspection](http://www.ibm.com/developerworks/library/l-pyint.html) for more information.
Finding what methods an object has
34,439
159
2008-08-29T15:05:17Z
34,472
20
2008-08-29T15:40:05Z
[ "python", "introspection" ]
Given a Python object of any kind, is there an easy way to get a list of all methods that this object has? Or, if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called?
To check if it has a particular method: ``` hasattr(object,"method") ```