python-2.x

python _2or3 module?

怎甘沉沦 提交于 2019-12-06 01:23:27
I am writing a module to let me write code in python 3, but still run it in 2. It looks surprisingly easy actually... anything else I should add? From my (limited) flailing on the interactive interpreter, the future imports do not affect python 3 and are viewed as redundant. # _2or3.py ''' Common usage: from __future__ import print_function, nested_scopes, division, absolute_import, unicode_literals from _2or3 import * ''' import sys if sys.version[0] == '2': range = xrange input = raw_input Obviously there are some things you cannot do that you would normally be able to do in 3 (like

Calling Method with and without Parentheses in Python

本小妞迷上赌 提交于 2019-12-05 22:09:48
I've realized that some methods should be called with () , while others can't. How can I check, using IPython e.g., whether to use parentheses or not? For example the following file scratch.py import numpy as np arr = np.random.randn(5) print arr.sort, "\n" print arr.sort(), "\n"; print arr.shape, "\n"; print arr.shape(), "\n"; produces this output: <built-in method sort of numpy.ndarray object at 0x7fb4b5312300> None (5,) Traceback (most recent call last): File "scratch.py", line 8, in <module> print arr.shape(), "\n"; TypeError: 'tuple' object is not callable Those are not methods, those are

how to decode an ascii string with backslash x \x codes

浪子不回头ぞ 提交于 2019-12-05 20:50:26
问题 I am trying to decode from a Brazilian Portogese text: 'Demais Subfun\xc3\xa7\xc3\xb5es 12' It should be 'Demais Subfunções 12' >> a.decode('unicode_escape') >> a.encode('unicode_escape') >> a.decode('ascii') >> a.encode('ascii') all give: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 13: ordinal not in range(128) on the other hand this gives: >> print a.encode('utf-8') Demais Subfun├â┬º├â┬Áes 12 >> print a Demais Subfunções 12 回答1: You have binary data that is not

listdir doesn't print non-english letters correctly

半世苍凉 提交于 2019-12-05 14:09:37
On Python 2.7, for dir in os.listdir("E:/Library/Documents/Old - Archives/Case"): print dir prints out: Danny.xlsx Dannyh.xlsx ~$??? ?? ?????? ??? ???? ???????.docx while this: # using a unicode literal for dir in os.listdir(u"E:/Library/Documents/Old - Archives/Case"): print dir prints out: Dan.xlsx Dann.xlsx Traceback (most recent call last): File "E:\...\FirstModule.py", line 31, in <module> print dir File "C:\Python27\lib\encodings\cp1252.py", line 12, in encode return codecs.charmap_encode(input,errors,encoding_table) UnicodeEncodeError: 'charmap' codec can't encode characters in position

unicode_literals and type()

前提是你 提交于 2019-12-05 13:54:56
问题 I'm having problems supporting python2 and python3 on a type() call. This demonstrates the problem: from __future__ import unicode_literals name='FooClass' type(name, (dict,), {}) No problem on python3, but on python2: Traceback (most recent call last): File "test.py", line 6, in <module> type(name, (dict,), {}) TypeError: type() argument 1 must be string, not unicode This is related to Any gotchas using unicode_literals in Python 2.6?. In that question, someone recommends typecasting to a

Why can't I use `import *` in a function?

末鹿安然 提交于 2019-12-05 12:11:07
问题 This works as expected def outer_func(): from time import * print time() outer_func() I can define nested functions in the context fine and call them from other nested functions: def outer_func(): def time(): return '123456' def inner_func(): print time() inner_func() outer_func() I can even import individual functions: def outer_func(): from time import time def inner_func(): print time() inner_func() outer_func() This, however, throws SyntaxError: import * is not allowed in function 'outer

Finding network (external) IP addresses using Python

南楼画角 提交于 2019-12-05 11:51:17
问题 I want to know my internet provider (external) IP address (broadband or something else) with Python. There are multiple machines are connected to that network. I tried in different way's but I got only the local and public IP my machine. How do I find my external IP address through Python? Thanks in advance. 回答1: Use this script : import urllib, json data = json.loads(urllib.urlopen("http://ip.jsontest.com/").read()) print data["ip"] Without json : import urllib, re data = re.search('"([0-9.]

How do I print a '%' sign using string formatting?

家住魔仙堡 提交于 2019-12-05 10:05:15
问题 I've made a little script to calculator percent; however, I wish to actually include the '%' within the message printed... Tried this at the start - didn't work... oFile.write("Percentage: %s%"\n" % percent) I then tried "Percentage: %s"%"\n" % percent" which didn't work. I'd like the output to be: Percentage: x% I keep getting "TypeError: not all arguments converted during string formatting" 回答1: To print the % sign you need to 'escape' it with another % sign: percent = 12 print "Percentage:

Python on Raspberry Pi user input inside infinite loop misses inputs when hit with many

五迷三道 提交于 2019-12-05 09:34:57
I have a very basic parrot script written in Python that simply prompts for a user input and prints it back inside an infinite loop. The Raspberry Pi has a USB barcode scanner attached for the input. while True: barcode = raw_input("Scan barcode: ") print "Barcode scanned: " + barcode When you scan at a "normal" speed it works reliably and the command output looks like this: Scan barcode: 9780465031467 Barcode scanned: 9780465031467 Scan barcode: 9780007505142 Barcode scanned: 9780007505142 But when you really hammer it with many scans in close succession it is possible to make it miss inputs

Python's hasattr sometimes returns incorrect results

荒凉一梦 提交于 2019-12-05 08:19:23
Why does hasattr say that the instance doesn't have a foo attribute? >>> class A(object): ... @property ... def foo(self): ... ErrorErrorError ... >>> a = A() >>> hasattr(a, 'foo') False I expected: >>> hasattr(a, 'foo') NameError: name 'ErrorErrorError' is not defined` The python2 implementation of hasattr is fairly naive, it just tries to access that attribute and see whether it raises an exception or not. Unfortunately, this means that any unhandled exceptions inside properties will get swallowed, and errors in that code can get lost. To add insult to injury, when hasattr eats the exception