linux怎么用python运维命令_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)

执行结果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值