设为首页 收藏本站
查看: 3237|回复: 0

[经验分享] python常用点整理

[复制链接]

尚未签到

发表于 2017-4-25 11:32:38 | 显示全部楼层 |阅读模式
  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[0:to_dir_pos+1]
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[1]
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、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-369065-1-1.html 上篇帖子: python克隆数据 copy 下篇帖子: python 参数格式化getopt
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表