python代码片段

1、python获取父目录

import os,sys
print os.path.dirname(os.path.abspath(__file__))
print os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
print os.path.abspath(os.path.join(os.path.dirname(__file__),".."))

2、python链接mysql

sudo apt-get install python-setuptools
curl -O http://python-distribute.org/distribute_setup.py;
python distribute_setup.py;
 
wget  https://github.com/pypa/pip/raw/master/contrib/get-pip.py
python get-pip.py
sudo easy_install -U distribute;
sudo easy_install mysql_python;
# -*- coding: UTF-8 -*-
import MySQLdb as mdb
con = None
try:
    #连接mysql的方法:connect('ip','user','password','dbname')
    con = mdb.connect('192.168.1.88','root','123456', 'dj',charset="utf8");
    #所有的查询,都在连接con的一个模块cursor上面运行的
    cur = con.cursor()
 
    #执行一个查询
    cur.execute("SELECT * from dj_music limit 0,10")
 
    #取得上个查询的结果,是单个结果
    #data = cur.fetchone()
    #print "Database version : %s " % data
    rows = cur.fetchall()
    #依次遍历结果集,发现每个元素,就是表中的一条记录,用一个元组来显示
    for row in rows:
        print row[1]
finally:
    if con:
        #无论如何,连接记得关闭
        con.close()

3、python使用sqlalchemy

sudo easy_install sqlalchemy
 
#coding=utf-8
from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
connstr = 'mysql://root:123456@192.168.1.88:3306/dj?charset=utf8'
db = create_engine(connstr, echo=True)
#metadata = MetaData(db) 
#table = Table('dj_music', metadata, autoload=True)
#i = table.all()
 
#from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=db)
session = Session()
 
 
class User(Base):
    __tablename__ = 'dj_music'
 
    id = Column(Integer, primary_key=True)
    music_name = Column(String)
 
print(session.query(User).filter_by(id=746)[0].music_name)

4、python连接redis服务器

sudo easy_install redis;
import redis
 
r = redis.StrictRedis(host='localhost', port=6379, db=0)
r.set('foo', 'bar')
if(r.exists('foo')):
    print(r.get('foo'))

5、python导入类
class_test.py

# -*- coding: UTF-8 -*-
class People:
	name=None
 
	def __init__(self,name=''):
		self.name = name
 
	def getName(self):
		return self.name
 
 
class Fish:
	name = None
	def __init__(self,name=''):
		self.name=name
	def getName(self):
		return self.name
	def setName(self,name=''):
		self.name=name

main.py

# -*- coding: UTF-8 -*-
from class_test import *
import simplejson as json
 
# python导入类测试
 
p = People('构造函数')
print p.getName()
 
 
fish =Fish()
fish.setName("金鱼")
print fish.getName()
 
# python map测试
dict ={}
dict['hehe']='中文'
dict['a']='中文'
dict['b']='中文b'
dict['c']='中文c'
dict.update({'a':'a','x':'博士'})
 
print len(dict)
for key in dict.keys():
	print key + '==' +dict.get(key,0)
 
# python list测试
list =[]
list.append(p)
list.append(People("你好中文测试"))
list.append(People("Basic"))
 
print len(list)
 
for obj in list:
	 print obj.getName()
 
 
# 测试json转换
 
str_json = json.dumps(fish.__dict__,sort_keys=True,indent=4)
print str_json
dict_o = json.loads(str_json)
print dict_o
print dict_o['name']
sudo easy_install web.py

原创文章,转载请注明: 转载自海波无痕

本文链接地址: python代码片段

文章的脚注信息由WordPress的wp-posturl插件自动生成

此条目发表在server分类目录,贴了标签。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。 必填项已用*标注

评论链接可以 移除 nofollow.