Python笔记
更多详细参见:https://github.com/kinegratii/PySnippet
使用a=b=c判断
# 在Python中可以使用a == b == c连等的判定条件 if not (c == len(raw_str) == len(set(raw_str) & set(allow_number_str))): print 'invalid input format,LOOK THE HINT!!!' continue
for-else的使用
s = ('pat','cheh','fa','yas') print 'Q1----------' for food in s: print food if food == 'yas': break else: #这个不会执行 print 'else in Q1' print 'Q2-----------' for food in s: if food == 'ccc': break else: #这个会被执行 print 'else in Q2'
简单请求IP查询API(PY2.x)
import urllib def request_ip_address(self, ip): res = None url = 'http://ip.taobao.com/service/getIpInfo.php?ip={ip}'.format(ip=ip) req = urllib2.Request(url) try: response_str = urllib2.urlopen(req) if response_str: res = json.load(response_str) print res except Exception as e: print str(e)
os.path模块
import os # 基本路径 self.base_path = os.path.dirname(__file__) # 书本目录 self.book_path = os.path.join(self.base_path, self.src_dir) # 如果某一目录不存在就创建 if not os.path.exists(self.dst_book_dir): os.makedirs(self.dst_book_dir)
复制文件
import shutil def _copy_media(self, parent_path, file_name): src_path = os.path.join(parent_path, file_name) dst_path = os.path.join(self.dst_book_dir, file_name) if not os.path.exists(dst_path): shutil.copyfile(src_path,dst_path)
使用with语句读写文件
def _add_to_dst_file(self, file_path): with open(file_path, 'r') as fp: content = fp.read() if content: self.dst_fp.write(os.linesep) self.dst_fp.write(content)
使用cx_freeze打包同目录下的tk_demo.py程序
import sys from cx_Freeze import setup, Executable base = None if sys.platform == "win32": base = "Win32GUI" includeFiles = [ ( r"D:\py\tcl\tcl8.5", "tcl"), ( r"D:\py\tcl\tk8.5", "tk") ] setup( name = "tk_demo", version = "1.0", description = "A demo for tkinter", options = {"build_exe": {"include_files": includeFiles,}}, executables = [Executable("tk_demo.py",base = base)])
更多详细参见:https://github.com/kinegratii/PySnippet