使用 python 实现 wc 命令程序的基本功能
2016-12-10 17:25
716 查看
这里使用了 python 的基本代码实现了 Linux 系统下 wc 命令程序的基本功能。
#!/usr/bin/env python #encoding: utf-8 # Author: liwei # Function: wc program by python from optparse import OptionParser import sys,os def opt(): parser = OptionParser() 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') parser.add_option('-n', '--nototal', dest='nototal', action='store_true', default=False, help='don\'t print total information') options, args = parser.parse_args() return options, args #print options def get_count(data): chars = len(data) words = len(data.split()) lines = data.count('\n') return lines, words, chars #if not options.chars and not options.words and not options 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 directory\n' % fn) # 只有多个文件的时候会计算出total字段 if len(args) > 1 and not options.nototal: print_wc(options, total_lines, total_words, total_chars, 'total') else: fn = '' data = sys.stdin.read() lines, words, chars = get_count(data) print_wc(options, lines, words, chars, fn) if __name__ == '__main__': main()
相关文章推荐
- 使用Python实现Linux系统wc命令,效果一样
- python使用optparse模块实现wc命令(二)
- 使用read和write函数,编写一个程序,实现cp函数的基本功能
- python使用fcntl模块实现程序加锁功能示例
- python使用paramiko模块实现ssh远程命令执行,与sftp文件下载功能
- 使用Python实现touch命令功能
- Eclipse+python的安装与使用(详细阐述了eclipse编写Python程序的基本功能及技巧)
- 【Python】用Python来实现凑24的程序,续--实现统计功能,列举出所有情况
- 使用Java程序实现随机验证码功能的实例
- linux下使用系统调用编程实现dir命令功能
- 装饰者模式---使用装饰者模式实现带日志记录功能的数据库命令执行类
- 直接使用SMTP协议命令而在程序中实现电子邮件传送
- 在linux上使用rlwrap实现像dos功能使用上下键查看命令
- python cgi ajax - 使用CGIHTTPServer实现一个ajax程序
- 使用蜘蛛程序来实现电影资料库中的自动填写功能
- linux: 基本命令之:查看磁盘空间, netstat, wc简单使用
- 字符串处理是许多程序中非常重要的一部分,它们可以用于文本显示,数据表示,查找键和很多目的.在Unix下,用户可以使用正则表达式的强健功能实现这些 目的,从Java1.4起,Java核心API就引入了java.util.regex程序包,它是一种有价值的基础
- 使用管道编程----利用别人的程序,实现自己的功能
- C#实现SMTP服务器,使用TCP命令实现,功能比较完善
- 系统管理指南:基本管理 第22 章• 使用patchadd 命令管理Solaris 修补程序(任务)~附录A • SMF 服务