代码拉取完成,页面将自动刷新
同步操作将从 八神/linux 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
** 安装 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.
** 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.
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。