将bash/shell行转换为python2.6

2024-05-15 04:39:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我对编程比较陌生,尤其是BASH和python,以及这个站点。抱歉,多个帖子! 我正在试着把这句话译成python。我试过了欧斯波本. 你们还有别的办法吗。我仅限于pythonv2.6版本,无法升级到新版本,否则我将知道如何在3.6版本中完成。 谢谢!你知道吗

 sample1=($(/bin/cat /proc/meminfo | egrep 'MemTotal|MemFree|Cached|SwapTotal|SwapFree|AnonPages|Dirty|Writeback|PageTables|HugePages_' | awk ' { print $2} ' | pr -t -T --columns=15 --width=240))

这是我在python中所拥有的,但它不起作用。任何人都不知道如何重新排列它,使之与BASH中的行相同。 我知道这些不应该是elif。老实说,我被难住了,不知道该怎么办。你知道吗

lst = []  #
inFile = open('/proc/meminfo')  # open file
line = inFile.readline()
sample1 = {}  # 
while(line):  # 
    if line.find('MemTotal'):
        line = line.split()
        sample1['MemTotal'] = line[1]
    elif line.find('MemFree'):
            line = line.split()
            sample1['MemFree'] = line[1]
    elif line.find(line, 'Cached'):
            line = line.split()
            sample1['Cached'] = line[1]
    elif line.find(line, 'SwapTotal'):
            line = line.split()
            sample1['SwapTotal'] = line[1]
    elif line.find(line, 'SwapFree'):
            line = line.split()
            sample1['SwapFree'] = line[1]
    elif line.find(line, 'AnonPages'):
            line = line.split()
            sample1['AnonPages'] = line[1]
    elif line.find(line, 'Dirty'):
            line = line.split()
            sample1['Dirty'] = line[1]
    elif line.find(line, 'Writeback'):
            line = line.split()
            sample1['WriteBack'] = line[1]
    elif line.find(line, 'PageTables'):
            line = line.split()
            sample1['PageTables'] = line[1]
    elif line.find(line, 'HugePages_'):
            line = line.split()
            sample1['HugePages'] = line[1]

Tags: 版本linefindsplitcachedelifdirtysample1
3条回答

这应该通过管道将输出通过subprocess.Popen从python运行bash命令,并适用于python2.6:

from subprocess import Popen, PIPE
p1 = Popen(["cat","/proc/meminfo"], stdout=PIPE)
p2 = Popen(["egrep", 'MemTotal|MemFree|Cached|SwapTotal|SwapFree|AnonPages|Dirty|Writeback|PageTables|HugePages_' ], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()  
p3 = Popen(["awk","{ print $2}"],stdin=p2.stdout,stdout=PIPE)
p2.stdout.close()
p4 = Popen(["pr", "-t", "-T", " columns=15", " width=240"],stdin=p3.stdout,stdout=PIPE)
p3.stdout.close()

output = p4.communicate()
print(output[0])

我的系统的输出是:

16341932    4484840     5105220     0       8388604     8388604     108     0       5106832     78100       0       0       0       0       0

也可以使用python打开文件,并将文件对象传递给第一个进程:

from subprocess import Popen,PIPE,STDOUT
with open("/proc/meminfo") as f:
    p1 = Popen(["egrep", 'MemTotal|MemFree|Cached|SwapTotal|SwapFree|AnonPages|Dirty|Writeback|PageTables|HugePages_' ], stdin=f, stdout=PIPE)
    p2 = Popen(["awk","{ print $2}"],stdin=p1.stdout,stdout=PIPE)
    p1.stdout.close()
    p3 = Popen(["pr", "-t", "-T", " columns=15", " width=240"],stdin=p2.stdout,stdout=PIPE)
    p2.stdout.close()

output = p3.communicate()
print(output[0])

纯python解决方案,使用str.find模拟egrep查找包含文件中pre的任何子字符串的行,并使用str.rsplit获取第二列,即数字:

pre = ('MemTotal', 'MemFree', 'Cached', 'SwapTotal', 'SwapFree', 'AnonPages', 'Dirty', 'Writeback', 'PageTables', 'HugePages_')
with open("/proc/meminfo") as f:
    out = []
    for line in f: 
        # if line.find(p) is not -1 we have a match
        if any(line.find(p) != -1 for p in pre):
            # split twice from the end on whitespace and get the second column
            v = line.rsplit(None, 2)[1]
            out.append(v)
   print("  ".join(out))

输出:

16341932   4507652   5128624   0   8388604   8388604   48   0   5059044   78068   0   0   0   0   0

在上面的代码中使用any将对匹配项进行延迟求值和短路,如果没有匹配项,它将求值为False,因此不会添加任何内容。你知道吗

我们可以使用re.search编译模式/子字符串来检查:

import  re
r = re.compile(r"MemTotal|MemFree|Cached|SwapTotal|SwapFree|AnonPages|Dirty|Writeback|PageTables|HugePages_")
with open("/proc/meminfo") as f:
    out =[]
    for line in f:
        if r.search(line):
            v = line.rsplit(None, 2)[1]
            out.append(v)
print("  ".join(out))

输出:

16341932   4507596   5128952   0   8388604   8388604   0   16788   5058092   78464   0   0   0   0   0

python作为python,我们可以将所有逻辑放在一个列表comp中以获得数据:

pre = ('MemTotal', 'MemFree', 'Cached', 'SwapTotal', 'SwapFree', 'AnonPages', 'Dirty', 'Writeback', 'PageTables', 'HugePages_')
with open("/proc/meminfo") as f:
    out = [line.rsplit(None, 2)[1] for line in f if r.search(line)]
print("   ".join(out))

输出:

16341932   4443796   5133420   0   8388604   8388604   120   0   5118004   78572   0   0   0   0   0

大概是这样的:

desiredTags = [ 'MemTotal', 'MemFree', 'Cached', 'SwapCached', 'SwapTotal',
                'SwapFree', 'AnonPages', 'Dirty', 'Writeback', 'PageTables',
                'HugePages_Total', 'HugePages_Free', 'HugePages_Rsvd',
                'HugePages_Surp' ]
stats = []
with open('/proc/meminfo') as fd:
    for line in fd:
        fields = line.strip().split()
        # strip off the colon from the first field
        if fields[0][:-1] in desiredTags:
            stats.append(fields[1])

print ' '.join(stats)

我不确定我得到了理想的标签清单完全正确-请随时修改这些必要的。你知道吗

这将提供相同的输出,但使用内置的Python特性,而不是对所有内容进行炮轰:

columns = [
    'MemTotal', 'MemFree', 'Cached', 'SwapTotal', 'SwapFree', 'AnonPages',
    'Dirty', 'Writeback', 'WritebackTmp', 'PageTables', 'HugePages_Free',
    'HugePages_Rsvd', 'HugePages_Surp', 'HugePages_Total'
]
stats = {}
with open('/proc/meminfo') as infile:
    for line in infile:
        line = line.split()
        stats[line[0][:-1]] = line[1]

values = [stats[key] for key in columns]
print '\t'.join(values)

相关问题 更多 >

    热门问题