Python Note
获取当前工作目录
workpath = os.path.dirname(os.path.realpath(__file__))
获取PATH
path = os.environ.get('PATH', '')
展开当前用户目录
COCOS2D_PREFIX = os.path.expanduser('~/.cocos2d')
check python版本
def _check_python_version():
major_ver = sys.version_info[0]
if major_ver > 2:
print ("The python version is %d.%d. But python 2.x is required. (Version 2.7 is well tested)\n"
"Download it here: https://www.python.org/" % (major_ver, sys.version_info[1]))
return False
return True
- 解析json
def loadJson(file_path):
with open(file_path) as data_file:
data = json.load(data_file)
return data****
- 下载文件
def download_file(filename, url):
print("==> Ready to download '%s' from '%s'" % (filename, url))
import urllib2
try:
u = urllib2.urlopen(url)
except urllib2.HTTPError as e:
if e.code == 404:
print("==> Error: Could not find the file from url: '%s'" % (url))
print("==> Http request failed, error code: " + str(e.code) + ", reason: " + e.read())
sys.exit(1)
f = open(filename, 'wb')
meta = u.info()
content_len = meta.getheaders("Content-Length")
file_size = 0
if content_len and len(content_len) > 0:
file_size = int(content_len[0])
else:
# github server may not reponse a header information which contains `Content-Length`,
# therefore, the size needs to be written hardcode here. While server doesn't return
# `Content-Length`, use it instead
# print("==> WARNING: Couldn't grab the file size from remote, use 'zip_file_size' section in '%s'" % self._config_path)
# file_size = self._zip_file_size
print "NO 'Content-Length'"
print("==> Start to download, please wait ...")
file_size_dl = 0
block_sz = 8192
block_size_per_second = 0
old_time=time()
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
block_size_per_second += len(buffer)
f.write(buffer)
new_time = time()
if (new_time - old_time) > 1:
speed = block_size_per_second / (new_time - old_time) / 1000.0
status = ""
if file_size != 0:
percent = file_size_dl * 100. / file_size
status = r"Downloaded: %6dK / Total: %dK, Percent: %3.2f%%, Speed: %6.2f KB/S " % (file_size_dl / 1000, file_size / 1000, percent, speed)
else:
status = r"Downloaded: %6dK, Speed: %6.2f KB/S " % (file_size_dl / 1000, speed)
status = status + chr(8)*(len(status) + 1)
print(status),
sys.stdout.flush()
block_size_per_second = 0
old_time = new_time
print("==> Downloading finished!")
f.close()