手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

使用Python实现Linux系统wc命令

[日期:2017-06-04] 来源:Linux社区  作者:270142877 [字体:大 中 小]

使用Python实现Linux系统wc命令,效果一样。

代码如下:
#!/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)

本文永久更新链接地址:http://www.linuxidc.com/Linux/2017-06/144490.htm

linux
相关资讯       Python实现wc命令  wc命令 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款