python-2.x

Mock Python's built in print function

此生再无相见时 提交于 2019-11-28 00:37:46
I've tried from mock import Mock import __builtin__ __builtin__.print = Mock() But that raises a syntax error. I've also tried patching it like so @patch('__builtin__.print') def test_something_that_performs_lots_of_prints(self, mock_print): # assert stuff Is there any way to do this? print is a keyword in python 2.x, using it as attribute raises a SyntaxError. You can avoid that by using from __future__ import print_function in the beginning of the file. Note: you can't simply use setattr , because the print function you modified doesn't get invoked unless the print statement is disabled.

Backport Python 3.4's regular expression “fullmatch()” to Python 2

不打扰是莪最后的温柔 提交于 2019-11-27 23:48:39
问题 Python 3.4 introduced the new regex method re.fullmatch(pattern, string, flags=0). Has anyone back-ported this new method to older Python versions? 回答1: To make sure that the entire string matches, you need to use the \Z end-of-string anchor: def fullmatch(regex, string, flags=0): """Emulate python-3.4 re.fullmatch().""" return re.match("(?:" + regex + r")\Z", string, flags=flags) The \A anchor is not necessary since re.match() already anchors the match to the start of the string. 回答2: Here

`pip install pandas` gives UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 41: ordinal not in range(128)

萝らか妹 提交于 2019-11-27 22:48:39
When performing pip install pandas on a Digital Ocean 512MB droplet, I get the error UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 41: ordinal not in range(128) . Any ideas what may have caused it? I'm running Ubuntu 12.04 64bit. [Full Error] jfs It looks like gcc being killed due to insufficient memory (see @Blender's comment) exposed a bug in pip. It mixes bytestrings and Unicode while logging that leads to: >>> '\n'.join(['bytestring with non-ascii character ☺', u'unicode']) Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeDecodeError:

How does the min/max function on a nested list work?

元气小坏坏 提交于 2019-11-27 20:29:46
Lets say, there is a nested list, like: my_list = [[1, 2, 21], [1, 3], [1, 2]] When the function min() is called on this: min(my_list) The output received is [1, 2] Why and How does it work? What are some use cases of it? Bhargav Rao How are lists and other sequences compared in Python? Lists (and other sequences) in Python are compared lexicographically and not based on any other parameter. Sequence objects may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the

How can I denote unused function arguments?

廉价感情. 提交于 2019-11-27 20:23:32
问题 When "deconstructing" a tuple, I can use _ to denote tuple elements I'm not interested in, e.g. >>> a,_,_ = (1,2,3) >>> a 1 Using Python 2.x, how can I express the same with function arguments? I tried to use underscores: >>> def f(a,_,_): return a ... File "<stdin>", line 1 SyntaxError: duplicate argument '_' in function definition I also tried to just omit the argument altogether: >>> def f(a,,): return a File "<stdin>", line 1 def f(a,,): return a ^ SyntaxError: invalid syntax Is there

A good way to make long strings wrap to newline?

喜欢而已 提交于 2019-11-27 20:03:42
In my project, I have a bunch of strings that are read in from a file. Most of them, when printed in the command console, exceed 80 characters in length and wrap around, looking ugly. I want to be able to have Python read the string, then test if it is over 75 characters in length. If it is, then split the string up into multiple strings, then print one after the other on a new line. I also want it to be smart, not cutting off full words. i.e. "The quick brown <newline> fox..." instead of "the quick bro<newline>wn fox..." . I've tried modifying similar code that truncates the string after a

Learn Python the Hard Way Exercise 17 Extra Question(S)

杀马特。学长 韩版系。学妹 提交于 2019-11-27 19:46:53
I'm doing Zed Shaw's fantastic Learn Python The Hard Way , but an extra question has me stumped: Line 9--10 could be written in one line, how? I've tried some different thoughts, but to no avail. I could move on, but what would the fun in that be? from sys import argv from os.path import exists script, from_file, to_file = argv print "Copying from %s to %s" % (from_file, to_file) # we could do these two on one line too, how? input = open(from_file) indata = input.read() print "The input file is %d bytes long" % len(indata) print "Does the output file exist? %r" % exists(to_file) print "Ready,

Why is math.factorial much slower in Python 2.x than 3.x?

佐手、 提交于 2019-11-27 19:19:36
I get the following results on my machine: Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> import timeit >>> timeit.timeit('factorial(10000)', 'from math import factorial', number=100) 1.9785256226699202 >>> Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> import timeit >>> timeit.timeit('factorial(10000)', 'from math import factorial', number=100) 9.403801111593792 >>> I

How do you use subprocess.check_output() in Python?

百般思念 提交于 2019-11-27 18:05:49
I have found documentation about subprocess.check_output() but I cannot find one with arguments and the documentation is not very in depth. I am using Python 3 (but am trying to run a Python 2 file through Python 3) I am trying to run this command: python py2.py -i test.txt -i is a positional argument for argparse, test.txt is what the -i is, py2.py is the file to run I have tried a lot of (non working) variations including: py2output = subprocess.check_output([str('python py2.py '),'-i', 'test.txt']) py2output = subprocess.check_output([str('python'),'py2.py','-i', test.txt']) abarnert The

How to add an element to the beginning of an OrderedDict?

天涯浪子 提交于 2019-11-27 17:47:32
I have this: d1 = OrderedDict([('a', '1'), ('b', '2')]) If I do this: d1.update({'c':'3'}) Then I get this: OrderedDict([('a', '1'), ('b', '2'), ('c', '3')]) but I want this: [('c', '3'), ('a', '1'), ('b', '2')] without creating new dictionary. There's no built-in method for doing this in Python 2. If you need this, you need to write a prepend() method/function that operates on the OrderedDict internals with O(1) complexity. For Python 3.2 and later, you should use the move_to_end method. The method accepts a last argument which indicates whether the element will be moved to the bottom ( last