Python
退出 IPython shell 的若干方法
方法1:quit() 方法2:exit() 方法3:%exit 方法4:%quit 方法5:%Exit 方法6:%Quit 总结:方法1和方法2调用的是python系统函数; 方法3, 4, 5, 6 则执行的是 IPython 特有的魔力函数(magic functions),这些魔力函数均以%开头。方法1, 2, 3, 4 会在系统退出前进行操作的确认; 方法 5, 6则强制立即退出,没有询问过程。 补充:IPython 0.10.2 全部魔力函数列表:
|
1 2 3 4 5 6 7 8 |
%Exit %bookmark %dirs %logoff %p %popd %quickref %runlog %unalias
%Pprint %cd %doctest_mode %logon %page %profile %quit %save %upgrade
%Quit %clear %ed %logstart %paste %prun %r %sc %who
%alias %color_info %edit %logstate %pdb %psearch %rehash %store %who_ls
%autocall %colors %env %logstop %pdef %psource %rehashx %sx %whos
%autoindent %cpaste %exit %lsmagic %pdoc %pushd %rep %system_verbose %xmode
%automagic %debug %hist %macro %pfile %pwd %reset %time
%bg %dhist %history %magic %pinfo %pycat %run %timeit |
查询魔力函数使用帮助的办法,在 IPython shell 中输入: %magic_function_name? 回车即可。例如,下面的指令是获取%clear这个魔力函数的使用帮助:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
In [1]: %clear?
Type: Magic function
Base Class: <type 'instancemethod'>
String Form: <bound method InteractiveShell.clear_f of <IPython.iplib.InteractiveShell object at 0xb7e93bac>>
Namespace: IPython internal
File: /usr/lib/python2.4/site-packages/IPython/Extensions/clearcmd.py
Definition: %clear(self, arg)
Docstring:
Clear various data (e.g. stored history data)
%clear in - clear input history
%clear out - clear output history
%clear shadow_compress - Compresses shadow history (to speed up ipython)
%clear shadow_nuke - permanently erase all entries in shadow history
%clear dhist - clear dir history
%clear array - clear only variables that are NumPy arrays
Examples:
In [1]: clear in
Flushing input history
In [2]: clear shadow_compress
Compressing shadow history
In [3]: clear shadow_nuke
Erased all keys from shadow history
In [4]: clear dhist
Clearing directory history |
IPython 默认配置文件
ipython 的默认配置文件位于 ~/.ipython/ipy_user_conf.py 下面是 ipython 0.10.2 的默认配置文件内容:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
""" User configuration file for IPython
This is a more flexible and safe way to configure ipython than *rc files
(ipythonrc, ipythonrc-pysh etc.)
This file is always imported on ipython startup. You can import the
ipython extensions you need here (see IPython/Extensions directory).
Feel free to edit this file to customize your ipython experience.
Note that as such this file does nothing, for backwards compatibility.
Consult e.g. file 'ipy_profile_sh.py' for an example of the things
you can do here.
See http://ipython.scipy.org/moin/IpythonExtensionApi for detailed
description on what you could do here.
"""
# Most of your config files and extensions will probably start with this import
import IPython.ipapi
ip = IPython.ipapi.get()
# You probably want to uncomment this if you did %upgrade -nolegacy
# import ipy_defaults
import os
def main():
# uncomment if you want to get ipython -p sh behaviour
# without having to use command line switches
# import ipy_profile_sh
# Configure your favourite editor?
# Good idea e.g. for %edit os.path.isfile
#import ipy_editors
# Choose one of these:
#ipy_editors.scite()
#ipy_editors.scite('c:/opt/scite/scite.exe')
#ipy_editors.komodo()
#ipy_editors.idle()
# ... or many others, try 'ipy_editors??' after import to see them
# Or roll your own:
#ipy_editors.install_editor("c:/opt/jed +$line $file")
o = ip.options
# An example on how to set options
#o.autocall = 1
o.system_verbose = 0
#import_all("os sys")
#execf('~/_ipython/ns.py')
# -- prompt
# A different, more compact set of prompts from the default ones, that
# always show your current location in the filesystem:
#o.prompt_in1 = r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Normal\n\C_Green|\#>'
#o.prompt_in2 = r'.\D: '
#o.prompt_out = r'[\#] '
# Try one of these color settings if you can't read the text easily
# autoexec is a list of IPython commands to execute on startup
#o.autoexec.append('%colors LightBG')
#o.autoexec.append('%colors NoColor')
#o.autoexec.append('%colors Linux')
# for sane integer division that converts to float (1/2 == 0.5)
#o.autoexec.append('from __future__ import division')
# For %tasks and %kill
#import jobctrl
# For autoreloading of modules (%autoreload, %aimport)
#import ipy_autoreload
# For winpdb support (%wdb)
#import ipy_winpdb
# For bzr completer, requires bzrlib (the python installation of bzr)
#ip.load('ipy_bzr')
# Tab completer that is not quite so picky (i.e.
# "foo".<TAB> and str(2).<TAB> will work). Complete
# at your own risk!
#import ipy_greedycompleter
# If you are on Linux, you may be annoyed by
# "Display all N possibilities? (y or n)" on tab completion,
# as well as the paging through "more". Uncomment the following
# lines to disable that behaviour
#import readline
#readline.parse_and_bind('set completion-query-items 1000')
#readline.parse_and_bind('set page-completions no')
# some config helper functions you can use
def import_all(modules):
""" Usage: import_all("os sys") """
for m in modules.split():
ip.ex("from %s import *" % m)
def execf(fname):
""" Execute a file in user namespace """
ip.ex('execfile("%s")' % os.path.expanduser(fname))
main() |
源码安装 IPyhton 0.10.2
1. 下载 ipython 0.10.2 源码
|
1 |
wget http://ipython.scipy.org/dist/0.10.2/ipython-0.10.2.tar.gz |
2. 解压 ipython 0.10.2
|
1 |
tar xzvf ipython-0.10.2.tar.gz |
3. 安装 ipython 0.10.2
|
1 2 |
cd ./ipython-0.10.2
python setup.py install |
4. 测试安装 在命令行下输入“ipython”,回车,屏幕回显: 5. 退出 ipython shell 在 ipython shell 交互界面,输入 “quit()” 回车,即可退出 ipython 交互环境。
RFC2045 邮箱字符编码规则函数 for Python
编码规则里一句话就是:76个字节一行。代码如下:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import math
import base64
subject = '我是一个很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长的邮件标题'
def RFC2045_Encode(string = ''):
if(string == ''):
return string
else:
length = int(math.ceil(len(string) / 76.0))
i = 1
pieces = []
while(i <= length):
start = (i - 1) * 76
stop = start + 76
pieces.append('=?utf-8?B?' + base64.encodestring(string[start:stop]).strip() + '?=')
i = i + 1
return '\n'.join(pieces)
print RFC2045_Encode(subject) |
Python 批量发送邮件脚本
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import email
import smtplib
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
# 邮件列表文件(每行一个邮件地址)
MAIL_FILE_PATH = './emails.txt'
# 邮件内容文件
MAIL_CONTENT_PATH = './page_kfc.html'
# 发件人名称
SENDER_NAME = 'Company Inc.'
# 发件人邮箱
SENDER_MAIL = 'noreply@yourmailhost.com'
# 发件人邮箱密码
SENDER_PSWD = 'yourpassword'
# SMTP 服务器
SMTP_SERVER = 'smtp.yourmailhost.com'
# SMTP 端口
SMTP_PORT = '25'
# 每次发送给几人
RECEIVER_LIMIT_PER_TIME = 10
# ##################################################################
# #
# 以下部分请勿修改 #
# #
# ##################################################################
# 获取收件人列表
def GetReceivers(limit = 10):
f = open(MAIL_FILE_PATH, 'r+')
try:
lines = f.readlines()
finally:
f.close()
receivers = lines[:RECEIVER_LIMIT_PER_TIME]
lines = lines[RECEIVER_LIMIT_PER_TIME:]
f = open(MAIL_FILE_PATH, 'w+')
f.writelines(lines)
f.close()
return receivers
# 批量发送邮件
def SendEmail(sender, senderName, receivers, subject, body):
smtp = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
smtp.login(SENDER_MAIL, SENDER_PSWD)
if(senderName != ''):
sender = senderName + '<' + sender + '>'
for receiver in receivers:
receiver = receiver.strip()
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receiver
msg.attach(MIMEText(body, 'html', 'utf-8'))
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
if __name__ == '__main__':
'''
发送邮件开始
'''
# 获取本次要发送的邮件地址
receivers = GetReceivers(RECEIVER_LIMIT_PER_TIME)
# 获取邮件标题和内容
f = open(MAIL_CONTENT_PATH, 'r');
lines = f.readlines()
f.close()
subject = lines[0].strip()
body = ''.join(lines[1:])
# 发送
SendEmail(SENDER_MAIL, SENDER_NAME, receivers, subject, body) |
批量去除UTF-8文件的BOM头
PHP版本函数:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
function checkBOM ($filename) {
global $auto;
$contents = file_get_contents($filename);
$charset[1] = substr($contents, 0, 1);
$charset[2] = substr($contents, 1, 1);
$charset[3] = substr($contents, 2, 1);
if (ord($charset[1]) == 239 && ord($charset[2]) == 187 && ord($charset[3]) == 191) {
if ($auto == 1) {
$rest = substr($contents, 3);
rewrite ($filename, $rest);
return ("<font color=red>BOM found, automatically removed.</font>");
} else {
return ("<font color=red>BOM found.</font>");
}
}
else return ("BOM Not Found.");
} |
补上一个 Python 版本的脚本:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import os
def delBOM():
file_count = 0
bom_files = []
for dirpath, dirnames, filenames in os.walk('.'):
if(len(filenames)):
for filename in filenames:
file_count += 1
file = open(dirpath + "/" + filename, 'r+')
file_contents = file.read()
if(len(file_contents) > 3):
if(ord(file_contents[0]) == 239 and ord(file_contents[1]) == 187 and ord(file_contents[2]) == 191):
bom_files.append(dirpath + "/" + filename)
file.seek(0)
file.write(file_contents[3:])
print bom_files[-1], "BOM found. Deleted."
file.close()
print file_count, "file(s) found.", len(bom_files), "file(s) have a bom. Deleted."
if __name__ == "__main__":
delBOM() |
一道有意思的Python小题目
最近刚学python,所以想加个群和大家一起讨论,也利于自己进步。结果进群时候,群主出了个题目: 用一行代码求两列表[5,7,9]和[2,8,3]下标对应项乘积之和。 刚开始我使用迭代计算的: >>> num = 0 >>> for a, b in zip([5, 7, 9], [2, 8, 3]): num += a * b >>> num 但是显然不是群主想要的答案,人家不给开门,郁闷~~ 于是继续钻研,终于写出来啦: >>> sum([a * [2, 8, 3][[5, 7, 9].index(a)] for a in [5, 7, 9]]) 结果: 93 群主指点: sum(x*y for x,y in zip([5,7,9],[2,8,3])) 好强悍的Python !~