使用Python实现Linux系统wc命令,效果一样
2017-05-26 09:38
696 查看
代码如下:
执行结果如下:
#!/usr/bin/python #*-*coding:utf8*-* import sys import os from optparse import OptionParser """定义参数""" parser = OptionParser() parser.add_option("-l", "--line", dest="lines", action="store_true", default=False, help="only count lines") parser.add_option("-w", "--word", dest="words", action="store_true", default=False, help="only count words") parser.add_option("-c", "--char", dest="chars", action="store_true", default=False, help="only count chars") parser.add_option("-n", "--nototal", dest="nototal", action="store_true", default=False, help="no count total") options, args = parser.parse_args() """根据指定不同选项显示不同的值""" def display(l, w, c): global total_l total_l += l global total_w total_w += w global total_c total_c += c if not (options.words or options.chars or options.lines): print(l), print(w), print(c), if options.lines: print(l), if options.words: print(w), if options.chars: print(c), """针对文件特殊处理,如果是1个文件以上那么需要输入一个Total总和""" def dir(data): if not os.path.exists(data): sys.stderr.write("%s No such file or directory\n" %data) return False if os.path.isdir(data): sys.stderr.write("%s Is a directory\n" %data) return False return True def readFile(data): for f in data: b = dir(f) if b: with open(f) as files: fd = files.read() l = fd.count("\n") w = len(fd.split()) c = len(fd) display(l, w, c) print(f) else: continue if (len(args) > 1) and (not options.nototal): l = total_l w = total_w c = total_c display(l, w, c) print("Total") total_l = 0 total_w = 0 total_c = 0 if len(args) == 0: data = sys.stdin.read() l = data.count("\n") w = len(data.split()) c = len(data) display(l, w, c) else: data = args readFile(data)
执行结果如下:
相关文章推荐
- Linux系统使用crontab命令实现计划任务
- 使用 python 实现 wc 命令程序的基本功能
- java开发系统内核:像Linux一样使用中断实现内核API
- 使用python获取CPU和内存信息的思路与实现(linux系统)
- 使用Python实现简单Linux之find命令
- Linux系统编程:pipe匿名管道的使用,实现linux命令下管道命令
- 使用python获取CPU和内存信息的思路与实现(linux系统)
- Python 使用paramiko实现远程登录Linux主机并执行命令和操作
- Linux下使用crontab命令以及Python脚本实现自动签到
- 使用Python命令在Linux系统之间传输文件
- Python调用linux系统命令--使用subprocess模块
- linux下使用系统调用编程实现dir命令功能
- 使用 python 获取 Linux 系统信息(通过dmidecode命令)
- 在linux下将自己的shell代码当做系统命令一样使用
- Linux系统下使用MySQL命令实现远程连接MySQL数据库
- python使用optparse模块实现wc命令(二)
- linux下使用系统调用编程实现copy命令功能
- Linux中使用shell+python实现监控系统负载+邮件报警
- 使用python获取CPU和内存信息的思路与实现(linux系统)