fumingxia 发表于 2017-4-25 11:32:38

python常用点整理

  1,b.py调用a.py的函数有如下两种方式
  库代码如下

# a.py
#!/usr/bin/env python
def funcA(str):
return "Hello " + str

  引用方式如下

# b.py
#!/usr/bin/env python
# type 1
import a
print a.funcA("World")
# type 2
from a import *
print funcA("World")
  2,引用文件夹代码
目录结构如下

>ls
test/
test/__init__.py # import时会自动调用
t.py
  库代码如下

# test/__init__.py
#!/usr/bin/env python
def funcB():
print "Yes"

  引用方式如下

# t.py
#!/usr/bin/env python
from test import funcB
#from test import *
funcB()

  3,python类的使用(私有公有属性函数,继承)

#!/usr/bin/env python
class Person:
#constructor
def __init__(self, p_name, p_sex, p_age=0):
self.name = p_name #public
self._sex = p_sex#protected (just a comment, not official)
self.__age = p_age #private
def say(self):
print "I am " + self.name + " " + str(self.__age) + " years old"
self.__private_say()
def __private_say(self):
print "I am chinese"

p = Person("ciaos","male",26)
p.say()
#p.__private_say()#forbidden
print p.name
print p._sex      #allow
#print p.__age      #forbidden

class Student(Person):
def __init__(self, p_name, p_sex, p_age, p_school):
Person.__init__(self, p_name, p_sex, p_age)
self.school = p_school
def introduce(self):
print "I am from " + self.school + " my name is " + self.name
s = Student("stone","female",26,"campus")
s.introduce()

  4,python的http digest认证(首先获取网站的Realm值)

#!/usr/bin/env python
import urllib2
URL      = 'http://website/digest-auth'
Realm    = 'Test Passport' #get realm info from website first
Username = 'account'
Password = 'password'
authhandler = urllib2.HTTPDigestAuthHandler()
authhandler.add_password(Realm, URL, Username, Password)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
page_content = urllib2.urlopen(URL)
for line in page_content:
print line#response content

  5,python查看变量有无定义

try:
variable_not_exist
except NameError:
variable_not_exist = None
  6,函数中使用全局变量

#!/usr/bin/env python
a=3
def func1():
b = a
print b
def func2():
a = "local"
print a
def func3():
global a
a = "test"
print a
func1() # global variable can be read in function
func2() # local variable
print a # global variable not change
func3() # global variable can be reset only after global statement
func1() # already reset
  7,用popen保证只有单个实例在运行

def check_exist():
pipe = os.popen("ps -ef | grep file_name.py | grep -v grep | wc -l")
ex_flag = pipe.read().strip()
print "### " + ex_flag + " ###"
pipe.close()
if int(ex_flag) > 1:
sys.exit(0)
if _name__ == '__main__':
chech_exist()
# continue job
  8,引用指定文件夹代码

import sys;
sys.path.append("/home/a/")
import b
9,编码转换


linux shell下默认为utf8编码
>>> str=u"我的"#unicode编码(前面加u)
>>> str
u'\u6211\u7684'
>>> str="我的"#utf8编码
>>> str
'\xe6\x88\x91\xe7\x9a\x84'
>>> str.decode("utf8")#utf8转unicode转gb2312
u'\u6211\u7684'
>>> str.decode("utf8").encode("gb2312")
'\xce\xd2\xb5\xc4'
>>> print str.decode("utf8").encode("gb2312")#会乱码(4/3个字)
windows idle下默认编码为gb2312
>>> str=u"我的"#unicode编码(前面加u)
>>> str
u'\xce\xd2\xb5\xc4'
>>> str="我的"#gb2312编码
>>> str
'\xce\xd2\xb5\xc4'
>>> str.decode("gb2312")
u'\u6211\u7684'
>>> str.decode("gb2312")#gb2312转unicode转utf8
u'\u6211\u7684'
>>> str.decode("gb2312").encode("utf8")
'\xe6\x88\x91\xe7\x9a\x84'
>>> print str.decode("gb2312").encode("utf8")#会乱码(3个字)


# -*- coding: gbk -*-
import urllib
str1="玫瑰小镇"
str2="天堂岛"
str3="玫"
ustr1=str1.decode("gb2312").encode("utf8")
ustr2=str2.decode("gb2312").encode("utf8")
ustr3=str3.decode("gb2312").encode("utf8")
print urllib.quote(str1)
print urllib.quote(str2)
print urllib.quote(str3)
print urllib.quote(ustr1)
print urllib.quote(ustr2)
print urllib.quote(ustr3)

# %C3%B5%B9%E5%D0%A1%D5%F2
# %CC%EC%CC%C3%B5%BA
# %C3%B5
# %E7%8E%AB%E7%91%B0%E5%B0%8F%E9%95%87
# %E5%A4%A9%E5%A0%82%E5%B2%9B
# %E7%8E%AB

# -*- coding: utf8 -*-
import urllib
str1="玫瑰小镇"
str2="天堂岛"
str3="玫"
gstr1=str1.decode("utf8").encode("gbk")
gstr2=str2.decode("utf8").encode("gbk")
gstr3=str3.decode("utf8").encode("gbk")
print urllib.quote(str1)
print urllib.quote(str2)
print urllib.quote(str3)
print urllib.quote(gstr1)
print urllib.quote(gstr2)
print urllib.quote(gstr3)
 10,test


#!/usr/bin/python
import os
import os.path
import sys
import urllib2
import logging
def get_logger(log_name):
logger = logging.getLogger()
formatter = logging.Formatter('%(pathname)s - %(asctime)s - %(name)s - %(levelname)s - %(message)s',)
file_handler = logging.FileHandler(log_name)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.setLevel(logging.NOTSET)
return logger
logger = get_logger("/tmp/web_wget.log")
def down(from_file, to_file):
src_url = from_file.replace('/usr/local/flashgameweb/webgame_htdocs','http://test')
to_dir_pos = to_file.rindex("/")
to_dir = to_file
if os.path.isdir(to_dir):
pass
else:
os.makedirs(to_dir)
try:
f = urllib2.urlopen(src_url,timeout=10800)
with open(to_file, "wb") as code:
code.write(f.read())
except:
logger.critical(sys.exc_info())
logger.error("download error: from " + src_url + " to " + to_file)
return False
logger.info("download ok: " + src_url)
return True
if __name__ == '__main__':
if len(sys.argv) < 2:
logger.critical("No action specified!")
from_file = sys.argv
to_file = from_file.replace("flashgameweb", "rsyncweb")
down(from_file, to_file)
  11,JSON


#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
with open('data.json', 'r') as content_file:
content = content_file.read()
decoded = json.loads(content)
print decoded
decoded = json.JSONDecoder().decode(content)
print decoded
encoded = json.JSONEncoder().encode(decoded)
print encoded
encoded = json.dumps(decoded)
print encoded
页: [1]
查看完整版本: python常用点整理