python常用点整理

9015 ワード

1,b.pyがa.pyを呼び出す関数には、次の2つの方法があります.
ライブラリコードは次のとおりです.
# 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