您的位置:首页 > 编程语言 > Python开发

Python第十天 print >> f,和fd.write()的区别 stdout的buffer 标准输入 标准输出 从控制台重定向到文件 标准错误 重定向 输出流和输入流 捕获sys.exit()调用

2017-01-23 23:19 1046 查看

Python第十天 print >> f,和fd.write()的区别 stdout的buffer 标准输入 标准输出 从控制台重定向到文件 标准错误 重定向 输出流和输入流 捕获sys.exit()调用

目录

Pycharm使用技巧(转载)

Python第一天 安装 shell 文件

Python第二天 变量 运算符与表达式 input()与raw_input()区别 字符编码 python转义符 字符串格式化

Python第三天 序列 5种数据类型 数值 字符串 列表 元组 字典

Python第四天 流程控制 if else条件判断 for循环 while循环

Python第五天 文件访问 for循环访问文件 while循环访问文件 字符串的startswith函数和split函数

Python第六天 类型转换

Python第七天 函数 函数参数 函数变量 函数返回值 多类型传值 冗余参数 函数递归调用 匿名函数 内置函数 列表表达式/列表重写

Python第八天 模块 包 全局变量和内置变量__name__ Python path

Python第九天 面向对象 类定义 类的属性 类的方法 内部类 垃圾回收机制 类的继承 装饰器

Python第十天 print >> f,和fd.write()的区别 stdout的buffer 标准输入 标准输出 标准错误 重定向 输出流和输入流

Python第十一天 异常处理 glob模块和shlex模块 打开外部程序和subprocess模块 subprocess类 Pipe管道 operator模块 sorted函数 生成器 walk模块 hashlib模块

Python第十二天 收集主机信息 正则表达式 无名分组 有名分组

Python第十三天 django 1.6 导入模板 定义数据模型 访问数据库 GET和POST方法 SimpleCMDB项目 urllib模块 urllib2模块 httplib模块 django和web服务器整合 wsgi模块 gunicorn模块

Python第十四天 序列化 pickle模块 cPickle模块 JSON模块 API的两种格式

Python第十五天 datetime模块 time模块 thread模块 threading模块 Queue队列模块 multiprocessing模块 paramiko模块 fabric模块

输出流和输入流
cat 12.rpm |ssh 192.168.2.6 "cat - >/tmp/12.rpm"

函数名:如果由多个单词组成,第二个单词的首字母应该大写
类名:如果由多个单词组成,每个单词的首字母应该大写
变量名:全部小写或者单词之间用下划线

#!/usr/bin/python和#!/usr/bin/env python的区别
/usr/bin/env表示到$PATH环境变量去找python执行文件,如果当前系统有两套python,那么不需要更改脚本内容
如果使用/usr/bin/python 绝对路径,就需要更改脚本

bash也有这种用法:#!/bin/bash和#!/usr/bin/env bash

Python如何处理管道输入输出
Python处理命令行参数
OS.path对文件路径的处理
逐步实现python版的wc命令

示例 1
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#__author__="huazai"
"""
pycharm 使用指南
Date:2016.08.12
"""

import sys

#sys.stdin 就是一个文件类,Linux里一切皆文件
#input = sys.stdin  input保存为文件描述符对象,相当于一个类sys.stdin实例化为一个对象input
#读取input时候按ctrl+d终止输入

input = sys.stdin

def lineCount(f):
n = 0
for i in f:
n += 1
return n

print lineCount(input)


从标准输入读取

示例 2
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#__author__="huazai"
"""
pycharm 使用指南
Date:2016.08.12
"""

import sys

fd = sys.stdin
data = fd.read()
sys.stdout.write(data+"\n")
print "你好"


文件对象的方法:
f.read() 按ctrl+d终止输入 ,f.read(10) 读取文件的10个字符,再运行第二次读取后10个字符,再运行第三次读取后10个字符,以此类推
f.readline() //用while遍历每一行
f.readlines() 与[i for i in f] //对文件每一行进行遍历
f.write()
f.close()

输出

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __author__="huazai"
"""
pycharm 使用指南
Date:2016.08.12
"""

import os
import sys
import string
import gc

import sys

print "hello world"
sys.stdout.write("Hello world"+'\n')
sys.stderr.write("Hello Error")


标准输出和标准错误输出

sys.stdout.write(str) :参数是字符串
sys.stderr.write(str):参数是字符串

print和stdout的区别
print通常是调用一个stdout对象的write方法
print会先进行格式转换
print会在最后加上换行符,要加逗号才能屏蔽换行符,等价于sys.stdout.write('hello'+'\n')

从控制台重定向到文件
在当前文件下新生成一个文件out.log,文件内容为hello
import sys
f_handler=open('out.log','w')
sys.stdout=f_handler
print 'hello'

捕获sys.exit()调用
执行到程序末尾,解释器自动退出,但是如果退出程序前执行某些操作,可以调用
sys.exit函数,带有一个可选整数参数返回给调用他的程序,表示你可以在主程序中捕获对sys.exit的调用,0是正常退出,其他为异常

def exitfunc():
print 'hello'

if __name__ == '__main__':
sys.exitfunc = exitfunc() # 设置捕获时调用的函数
print 'aaaaaa'
sys.exit(1) # 退出前调用exitfunc()函数,然后退出
print 'there' # 这句不会执行

print >> f,和fd.write()的区别
fd.write()只能输入字符串,输入数字要先用str()函数转换为字符串或者或者格式化("%d\n" % i)
print >> fd,可以直接输入int
print >> fd,"Hello world, I'm writting to file",11,200,300,400,500
fd = open('tmp','w')
fd.write('123')

示例

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __author__="huazai"
"""
pycharm 使用指南
Date:2016.08.12
"""

import os
import sys

with open('F:\ a.txt', 'a') as f: #以写的方式打开
print >> f, "Hello world, I'm writting to file", 11  # 用print往文件描述符里写内容,可以输入数字
#等价于
f.write("Hello world, I'm writting to file: "+str(11))  # 用write不能输入数字要先str函数转换为字符串或者格式化("%d\n" % i)

print >> sys.stderr, "Hello world, I'm writting to file", 11  # 向标准错误输入内容


stderr和重定向

#!/usr/bin/env python

import sys
print >> sys.stderr, "I am going to stderr"
sys.stdout.write("I am standard output\n")
python print2stderr.py 2> /dev/null


#写入到标准错误

print >> sys.stderr ,"Hello world, I'm writting to file",11,200,300,400,500
python xx.py 2>/dev/null 可以重定向


------------------------------------------------------
stdout的buffer

python命令的-u 选项
文件对象的.flush() 方法

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __author__="huazai"
"""
pycharm 使用指南
Date:2016.08.12
"""

import os
import sys
import  time

for i in range(1,10):
sys.stdout.write("str:%d\n" % i)
time.sleep(1)
sys.stdout.flush()

#
# python buffer.py | cat -
# python -u buffer.py | cat -
# -u表示不需要buffer


--------------------------------------------------

简单的word count

day04:包名
wc:模块名
wordCount:函数名
from day04 import wc

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#__author__="huazai"
"""
pycharm 使用指南
Date:2016.08.12
"""

from sys import stdin

data = stdin.read()

chars = len(data)
words = len(data.split())
lines = data.count('\n')

print "%(lines)s %(words)s %(chars)s" % locals()
或者
print "%(lines)s %(words)s %(chars)s"  % {'lines':lines,'words':words,'chars':chars}

#可以用管道符进行调用cat /etc/hosts |python wc.py


locals()返回一个字典对象,代表当前的变量情况

#!/usr/bin/python

import sys

data = sys.stdin.read()
chars = len(data)
words = len(data.split())
lines = data.count('\n')

print "%(lines)s %(words)s %(chars)s" % locals()

locals()返回一个字典对象,代表当前的变量情况
下面两种方法都可以
print "%s %s %s " %(chars,words,lines)
print "%(lines)s %(words)s %(chars)s" % locals()

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#__author__="huazai"
"""
从标准输入或参数读取文件内容
Date:2016.08.12
"""

#!/usr/bin/python

import sys
import os

if len(sys.argv) < 2:
data = sys.stdin.read()
else :
try:
fn = sys.argv[1]
except IndexError:
print "please follow a argument at %s" % __file__  # __file__内置变量表示脚本名
sys.exit()

if not os.path.exists(fn):
print "%s is not exists" % fn
sys.exit()

with open(fn) as fd:
data = fd.read()

chars = len(data)
words = len(data.split())
lines = data.count('\n')

print "%(lines)s %(words)s %(chars)s" % locals()

# print sys.argv 返回一个列表  ,argv本身是一个属性


--------------------------------------------------------
optparse
真正的命令行参数,代替sys.argv[],比如 ls /etc/passwd -l,sys.argv[]只能获取到参数的索引位置,但是准确位置无法获取,

比如获取-l参数,-l可以写在前面又可以写在后面

ls /etc/passwd -l ,ls -l /etc/passwd

OptionParser是一个类

-c、--chars:命令行选项
dest:为选项定义变量名,值characters就是’-c’选项的名字,同理,words就是‘-w’选项的名字,lines就是‘-l’选项的名字,每个选项就是一个变量,选项的值就是变量的值
default=False:characters的默认值False,意思是默认情况下命令不带-c选项
help:选项的解释说明部分

改写wc程序
支持 -l -w -l选项
支持文件参数和管道输入
多文件计算总行数
程序中使用函数

示例1
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#__author__="huazai"
"""
从标准输入或参数读取文件内容
Date:2016.08.12
"""

from optparse import OptionParser
import sys, os

# parser = OptionParser()
parser = OptionParser("Usage: %prog [file1] [file2]...")
parser.add_option("-c",
"--chars",
dest="characters",
action="store_true",
default=False,
help="only count characters", )
parser.add_option("-w",
"--words",
dest="words",
action="store_true",
default=False,
help="only count words", )
parser.add_option("-l",
"--lines",
dest="lines",
action="store_true",
default=False,
help="only count lines", )
options, args = parser.parse_args()  # 返回选项字典 options是一个类 可以直接调用选项(options.words)和参数列表
print options, args,
if not (options.characters or options.words or options.lines):
options.characters, options.words, options.lines = True, True, True

data = sys.stdin.read()
chars = len(data)
words = len(data.split())
lines = data.count('\n')

if options.lines:
print lines,
if options.words:
print words,
if options.characters:
print chars,

调用方式:cat /etc/passwd |python wc.py

示例2
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __author__="huazai"
"""
pycharm 使用指南
Date:2016.08.12
"""

import sys
import os
from optparse import OptionParser

def opt():
parser = OptionParser("Usage: %prog [option] [file1] [file2]")
parser.add_option("-c", "--char",
dest="chars",
action="store_true",
default=False,
help="only count chars")
parser.add_option("-w", "--word",
dest="words",
action="store_true",
default=False,
help="only count words")
parser.add_option("-l", "--line",
dest="lines",
action="store_true",
default=False,
help="only count lines")
options, args = parser.parse_args()
return options, args

def get_count(data):
chars = len(data)
words = len(data.split())
lines = data.count('\n')
return lines, words, chars

def print_wc(options, lines, words, chars, fn):
if options.lines:
print lines,
if options.words:
print words,
if options.chars:
print chars,
print fn

def main():
options, args = opt()
if not (options.lines or options.words or options.chars):
options.lines, options.words, options.chars = True, True, True
if args:
total_lines, total_words, total_chars = 0, 0, 0
for fn in args:
if os.path.isfile(fn):
with open(fn) as fd:
data = fd.read()
lines, words, chars = get_count(data)
print_wc(options, lines, words, chars, fn)
total_lines += lines
total_words += words
total_chars += chars
elif os.path.isdir(fn):
print >> sys.stderr, "%s: is a directory" % fn
else:
sys.stderr.write("%s: No such file or direcotry\n" % fn)
if len(args) > 1:
print_wc(options, total_lines, total_words, total_chars, 'total')
else:
data = sys.stdin.read()
fn = ''
lines, words, chars = get_count(data)
print_wc(options, lines, words, chars, fn)

if __name__ == '__main__':
main()     #main()函数不想让其他模块调用,不加if __name__ == '__main__':,那么import wc这个模块的时候就会自动执行main()这个函数


注意:OptionParser不能使用-h选项,因为他内置了一个帮助选项,就是-h

parser.add_option("-h", "--host", # 改为-H ,‘--Host’
dest="host",
action="store",
default='127.0.0.1',
help="host address")

print "%s -h" % __file__
sys.exit(1)

不然会报错:optparse.OptionConflictError: option -h/--host: conflicting option string(s): -h

系统中的wc命令用C语言写
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: