python-2.x

Difference between IOError and OSError?

旧巷老猫 提交于 2019-12-03 11:33:34
问题 I am always getting confused on whether a function would raise an IOError or OSError (or both?). What is the principle rule behind these exception types, what is the difference between them and when is which raised? I've initially thought OSError is for things like permission denial, but opening a file without permissions will raise an IOError. 回答1: There is very little difference between the two types. In fact, even the core Python developers agreed that there is no real difference and

Chunking bytes (not strings) in Python 2 and 3

こ雲淡風輕ζ 提交于 2019-12-03 11:26:39
This is turning out to be trickier than I expected. I have a byte string: data = b'abcdefghijklmnopqrstuvwxyz' I want to read this data in chunks of n bytes. Under Python 2, this is trivial using a minor modification to the grouper recipe from the itertools documentation: def grouper(iterable, n, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx args = [iter(iterable)] * n return (''.join(x) for x in izip_longest(fillvalue=fillvalue, *args)) With this in place, I can call: >>> list(grouper(data, 2)) And get: ['ab', 'cd', 'ef', 'gh',

How to manipulate the exception in __exit__ of a context manager?

为君一笑 提交于 2019-12-03 08:23:09
I know it's bad style to re-raise an exception from within a context manager's __exit__() method. So, I'd like to tack an attribute on the instance which can carry contextual information that isn't available if I let the exception trickle through or if I catch it. This will avoid re-raising it. The alternative to tacking the attribute on the exception would be to swallow the exception, set some state on the instance that doubles as the context manager in question and later check that state. Problem is that this would lead to a catch 22, wouldn't it? Since the exception means that execution

How to organize Python modules for PyPI to support 2.x and 3.x

天大地大妈咪最大 提交于 2019-12-03 06:42:41
问题 I have a Python module that I would like to upload to PyPI. So far, it is working for Python 2.x. It shouldn't be too hard to write a version for 3.x now. But, after following guidelines for making modules in these places: Distributing Python Modules The Hitchhiker’s Guide to Packaging it's not clear to me how to support multiple source distributions for different versions of Python, and it's not clear if/how PyPI could support it. I envisage I would have separate code for: 2.x 2.6 (maybe, as

Set literal gives different result from set function call

心已入冬 提交于 2019-12-03 06:28:07
问题 Why does the set function call wipe out the dupes, but parsing a set literal does not? >>> x = Decimal('0') >>> y = complex(0,0) >>> set([0, x, y]) {0} >>> {0, x, y} {Decimal('0'), 0j} (Python 2.7.12. Possibly same root cause as for this similar question) 回答1: Sets test for equality, and until there are new Python releases, the order in which they do this can differ based on the form you hand the values to the set being constructed, as I'll show below. Since 0 == x is true and 0 == y is true,

Python ConfigParser interpolation from foreign section

折月煮酒 提交于 2019-12-03 06:01:12
With Python ConfigParser, is it possible to use interpolation across foreign sections? My mind seems to tell me I've seen that it's possible somewhere, but I can't find it when searching. This example doesn't work, but it's to give an idea of what I'm trying to do. [section1] root = /usr [section2] root = /usr/local [section3] dir1 = $(section1:root)/bin dir2 = $(section2:root)/bin Note that I'm using Python 2.4. chown In python 3.2 and up this is perfectly valid: [Common] home_dir: /Users library_dir: /Library system_dir: /System macports_dir: /opt/local [Frameworks] Python: 3.2 path: $

Parsing HTML to get text inside an element

你离开我真会死。 提交于 2019-12-03 05:41:45
问题 I need to get the text inside the two elements into a string: source_code = """<span class="UserName"><a href="#">Martin Elias</a></span>""" >>> text 'Martin Elias' How could I achieve this? 回答1: I searched "python parse html" and this was the first result: https://docs.python.org/2/library/htmlparser.html This code is taken from the python docs from HTMLParser import HTMLParser # create a subclass and override the handler methods class MyHTMLParser(HTMLParser): def handle_starttag(self, tag,

How to pass arguments to the metaclass from the class definition?

China☆狼群 提交于 2019-12-03 05:03:25
I'm trying to dynamically generate classes in python 2.7, and am wondering if you can easily pass arguments to the metaclass from the class object. I've read this post, which is awesome, but doesn't quite answer the question. at the moment I am doing: def class_factory(args, to, meta_class): Class MyMetaClass(type): def __new__(cls, class_name, parents, attrs): attrs['args'] = args attrs['to'] = to attrs['eggs'] = meta_class class MyClass(object): metaclass = MyMetaClass ... but this requires me to do the following MyClassClass = class_factory('spam', 'and', 'eggs') my_instance = MyClassClass(

How do I undo True = False in python interactive mode? [duplicate]

北慕城南 提交于 2019-12-03 04:50:32
问题 This question already has answers here : Naming conflict with built-in function (7 answers) Closed 4 years ago . So I tried the "evil" thing Ned Deily mentioned in his answer here. Now I have that the type True is now always False. How would I reverse this within the interactive window? Thing to not do: True = False Since True has now been completely overridden with False, there doesn't seem to be an obvious way to back-track. Is there a module that True comes from that I can do something

List minimum in Python with None?

巧了我就是萌 提交于 2019-12-03 04:45:00
Is there any clever in-built function or something that will return 1 for the min() example below? (I bet there is a solid reason for it not to return anything, but in my particular case I need it to disregard None values really bad!) >>> max([None, 1,2]) 2 >>> min([None, 1,2]) >>> None is being returned >>> print min([None, 1,2]) None >>> None < 1 True If you want to return 1 you have to filter the None away: >>> L = [None, 1, 2] >>> min(x for x in L if x is not None) 1 using a generator expression: >>> min(value for value in [None,1,2] if value is not None) 1 eventually, you may use filter: