5 Star 117 Fork 5

八神 / linux

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
python-tips.txt 9.72 KB
一键复制 编辑 原始数据 按行查看 历史
bashen 提交于 2013-09-19 15:50 . add python-explanation.txt
** django admin app 正常启动
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',}
** Table 'MyDjango.django_admin_log' doesn't exist
Have you recently enabled admin history, but forgot to run syncdb? From what
I see, Django had no problem locating your model tables, but when you tried
to modify them through the admin interface it couldn't find the right table
to store your actions.
** troubleshooting 'WSGIRequest' object has no attribute 'user'
You need to enable 'django.contrib.auth.middleware.AuthenticationMiddleware',
because it sets request.user. You should also enable the other default
middleware or you're going to have other problems.
** timedelta 's parameter should be integer, otherwise:
TypeError: unsupported type for timedelta days component: ???
** convert query string to dict
json.dumps(urlparse.parse_qs("a=1&b=2"))
This is actually better than your {"a":1, "b":2}, because URL query strings
can legally contain the same key multiple times, i.e. multiple values per key.
{x.split('=')[0]:x.split('=')[1] for x in strs.split("&")}
dict([x.split('=') for x in s.split('&')])
{'a': 1, 'b': 2}
** progress bar in python
def status(percent):
sys.stdout.write("%3d%%\r" % percent)
sys.stdout.flush()
Note that I used sys.stdout.write instead of print (this is Python) because
print automatically prints "\r\n" (carriage-return new-line) at the end of
each line. I just want the carriage-return which returns the cursor to the
start of the line. Also, the flush() is necessary because by default,
sys.stdout only flushes its output after a newline (or after its buffer gets full).
** gem/git-style command line arguments in Python
argparse with add_subparser().
** 安装 PIP
wget https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py -O - | sudo python
wget https://raw.github.com/pypa/pip/master/contrib/get-pip.py -O - | sudo python
** 获取当前运行python脚本的路径
a. os.path.realpath(__file__) will give you the path of the current
file, resolving any symlinks in the path.
path = os.path.dirname(os.path.realpath(__file__))
b. refpath = os.path.dirname(sys.argv[0])
rpath = os.path.abspath(refpath)
此方法可能不正常工作。
** logging记录程序异常
try:
1/0
except Exception, e:
logging.exception('msg') # logging.exception(e)
logging.info('blah', exc_info=True)
# The exception method simply calls error(message, exc_info=1). As soon as
you pass exc_info to any of the logging methods from an exception context,
you will get a traceback.
** way to get the first item from an iterable matching a condition?
next(x for x in the_iterable if x > 3)
if you want StopIteration to be raised if no matching element is found,
next( (x for x in the_iterable if x>3), default_value)
if you want default_value (e.g. None) to be returned instead.
** logging的使用方法:
级别; DEBUG, INFO, WARNING, ERROR, CRITICAL
a. 基本
logging.warn('test warning msg')
logging.info('will not show by default')
logging.error('error happen')
默认是WARNING级别,输出是console
B. 写入文件
import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
The call to basicConfig() should come before any calls to debug(), info() etc。
If you want each run to start afresh, not remembering the messages from earlier runs:
logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)
logging可在import的模块内使用而不用初始化。
logging.basicConfig(filename='example.log',level=logging.DEBUG)
one = logging.getLogger('one')
one.info('info from one')
two = logging.getLogger('two')
two.info('info from two')
[example.log] 默认第二项为logger name.
INFO:one:info from one
INFO:two:info from two
A good convention to use when naming loggers is to use a module-level
logger, in each module which uses logging, named as follows:
logger = logging.getLogger(__name__)
下面这种格式不错:
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
** Map two lists into a dictionary in Python
dictionary = dict(zip(keys, values))
adict = dict(itertools.izip(keys,values))
{k: v for k, v in zip(keys, values)} # dictionary comprehensions >=2.7
** Getting key with maximum value in dictionary?
import operator
stats = {'a':1000, 'b':3000, 'c': 100}
max(stats.iteritems(), key=operator.itemgetter(1))[0]
max(stats.iterkeys(), key = lambda key: stats[key])
** reverse a string : s[::-1]
** make list element uniqu
1. not preserve order: list(set(la))
2. from itertools import groupby
[ key for key,_ in groupby(sortedList)]
3. la = reduce(lambda x, y: x if y in x else x + [y], la, [])
** 获取命令行参数的方法:
import getopt
字符串 optstring 可以包含下列元素:单个字符,字符后面接一个冒号说明后面跟随一个选项参数,字符后面接两个冒号说明后面跟随一个可有可无的选项参数。
getopt.getopt(args, options[, long_options]) # a non-option argument, all further arguments are considered also non-options., non-GNU Unix systems work.
getopt.gnu_getopt(args, options[, long_options])
import getopt, sys
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
except getopt.GetoptError as err:
# print help information and exit:
print str(err) # will print something like "option -a not recognized"
usage()
sys.exit(2)
output = None
verbose = False
for o, a in opts:
if o == "-v":
verbose = True
elif o in ("-h", "--help"):
usage()
sys.exit()
elif o in ("-o", "--output"):
output = a
else:
assert False, "unhandled option"
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args([list])
class argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True)
Create a new ArgumentParser object. All parameters should be passed as keyword arguments. Each parameter has its own more detailed description below, but in short they are:
prog - The name of the program (default: sys.argv[0])
usage - The string describing the program usage (default: generated from arguments added to parser)
description - Text to display before the argument help (default: none)
epilog - Text to display after the argument help (default: none)
parents - A list of ArgumentParser objects whose arguments should also be included
formatter_class - A class for customizing the help output
prefix_chars - The set of characters that prefix optional arguments (default: ‘-‘)
fromfile_prefix_chars - The set of characters that prefix files from which additional arguments should be read (default: None)
argument_default - The global default value for arguments (default: None)
conflict_handler - The strategy for resolving conflicting optionals (usually unnecessary)
add_help - Add a -h/–help option to the parser (default: True)
ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
Define how a single command-line argument should be parsed. Each parameter has its own more detailed description below, but in short they are:
name or flags - Either a name or a list of option strings, e.g. foo or -f, --foo.
action - The basic type of action to be taken when this argument is encountered at the command line.
nargs - The number of command-line arguments that should be consumed.
const - A constant value required by some action and nargs selections.
default - The value produced if the argument is absent from the command line.
type - The type to which the command-line argument should be converted.
choices - A container of the allowable values for the argument.
required - Whether or not the command-line option may be omitted (optionals only).
help - A brief description of what the argument does.
metavar - A name for the argument in usage messages.
dest - The name of the attribute to be added to the object returned by parse_args().
The following sections describe how each of these are used.
ArgumentParser.parse_args(args=None, namespace=None)
Convert argument strings to objects and assign them as attributes of the namespace. Return the populated namespace.
Previous calls to add_argument() determine exactly what objects are created and how they are assigned. See the documentation for add_argument() for details.
By default, the argument strings are taken from sys.argv, and a new empty Namespace object is created for the attributes.
VimL
1
https://gitee.com/wucai0503/linux.git
git@gitee.com:wucai0503/linux.git
wucai0503
linux
linux
master

搜索帮助