Python处理文本文件以打印其输出 [英] Python to handle text file to print its output

查看:157
本文介绍了Python处理文本文件以打印其输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很py on on on and and:::::::::::。。。。。。。。。。。。。。。。。。。。。。。

  NIC:
名称:eth0
ID:0 1
动态MAC地址:00 :00:00:00:00:01
首选项:NONE

以太网接口:
名称:prod
默认网络:是
VLAN ID: 2
操作VLAN:SWA
配置Qual:N / A

名称:dev
默认网络:否
VLAN ID:3
操作VLAN:SWA
配置Qual:N / A

名称:eth1
Fabric ID:1 0
动态MAC地址:00:00:00:00: 00:11
首选项:NONE
以太网接口:
名称:prod
默认网络:是
VLAN ID:2
操作VLAN:SWB
Config Qual:N / A

名称:dev
默认网络:否
VLAN ID:3
操作VLAN: SWB
配置质量:N / A




  1. 我实际上要做什么,我需要找到我有多少接口。在上述情况下eth0和eth1。


  2. 我想要验证eth0有ID 0 1


  3. 对于eth0,我需要验证名称prod是否存在,vlan ID 2是否为prod,默认网络是是


  4. 对于eth0,我需要验证是否名称dev存在,vlan ID 3用于dev,而Default Network为No。


通常我会得到eth0 - 20的输出。



我迄今为止尝试实现这一点,并能够使用下面的方法使其工作,但下面的代码是不正确的,因为如果字段被互换,它将无法正常工作。



我实际做的是找到eth0并将值重定向到var 1,var2,var3等,然后使用这些var1, var2,var3来获取我的输出。



但是,当字段交换时,并且当额外的字段被添加到输出文件时,这不会起作用。



(注意下面的代码是我正在尝试的例子)



我需要你的帮助,以正确的方式实现这一点。

  from itertools import islice 
import string
import re
import os
import sys
a = eth0
def silentremove(filename):#remove file
try:
os.remove(filename)
除了OSError作为e:#这将是除了OSError,e :
if e.errno!= errno.ENOENT:#errno.ENOENT = no such文件或目录
raise#如果发生不同的错误,则重新引发异常
file =inputfile.txt
silentremove(file)
with open(vnic1.txt)作为f:#删除空行
在f中的行
如果不是line.isspace():
input_file = open('inputfile.txt','a')
sys.stdout = input_file
sys.stdout.write(line)
input_file.close()
sys.stdout = sys .__ stdout__
d = {}
count = 0
with open('inputfile.txt')as f:
for f中的行:
if(re.search(a,line,re.IGNORECASE)):
var1,var2,var3,var4,var5,var6,var7,var8,var9,var10,var11,var12,var13,var14,var15,var16 = islice(f,16)
key,value = var1.strip ).split(:,1)
d [key] = value
ideth0 =0 1
if(re.search(ideth0,value,re.IGNORECASE)):
count + = 1
key,value = var5.strip()。split(:,1)
d [key] = value
name =prod
if(re.search(name,value,re.IGNORECASE)):
count + = 1
如果count = = 2:
打印工作
打印状态 - {}:格式(a)
打印ID名称
打印{} {}格式(ideth0,name)

其他:
打印失败


解决方案

文字看起来像是YAML,但不是这样,但可能是

  with open(vnic1.txt)as f:
data = f.read()
#make it it yaml-string
data = dat.replace(Name, - Name )#2个空格的目的是
import yaml
data = yaml.load(data)#你现在将整个结构作为一个巨大的dict,利润

这样你就可以得到类似这样的数据

  {
'NIC':[
{'动态MAC地址':'00:00:00:00:00:01 ',
'Ethernet Interface':[{'Config Qual':'N / A',
'Default Network':True,
'Name':'prod',
'操作VLAN':'SWA',
'VLAN ID':2},
{'Config Qual':'N / A',
'默认网络':False,
'名称':'dev',
'操作VLAN':'SWA',
'VLAN ID':3}],
'ID':'0 1'
'Name':'eth0',
'Preference':'NONE'},
{'动态MAC地址':'00:00:00:00:00:11'
'以太网接口':[{'Config Qual':'N / A',
'默认网络':True,
'名称':'prod',
'操作VLAN':'SWB',
'VLAN ID':2},
{'配置Qual':'N / A' b $ b'默认网络':False,
'名称':'dev',
'操作VLAN':'SWB',
'VLAN ID':3}],
'Fabric ID':'1 0',
'Name':'eth1',
'偏好':'NONE'}
]
}

这可能不是您要求的,但一定会更容易导航(至少你有部分正确分隔)


I am very new to python and I need to read below file (Actually below output get it from command ) and print its output.

Below is the file:

NIC:
   Name: eth0
   ID: 0 1
   Dynamic MAC Addr: 00:00:00:00:00:01
   Preference: NONE

   Ethernet Interface:
      Name: prod
      Default Network: Yes
      VLAN ID: 2
      Operational VLAN: SWA
      Config Qual: N/A

      Name: dev
      Default Network: No
      VLAN ID: 3
      Operational VLAN: SWA
      Config Qual: N/A

   Name: eth1
   Fabric ID: 1 0
   Dynamic MAC Addr: 00:00:00:00:00:11
   Preference: NONE
   Ethernet Interface:
      Name: prod
      Default Network: Yes
      VLAN ID: 2
      Operational VLAN: SWB
      Config Qual: N/A

      Name: dev
      Default Network: No
      VLAN ID: 3
      Operational VLAN: SWB
      Config Qual: N/A

  1. What actually i what to achieve is i need to find how many interface i have. In above case eth0 and eth1.

  2. I want verify eth0 has ID 0 1

  3. For eth0, i need to verify whether Name prod exists and vlan ID 2 is for prod and Default Network is Yes

  4. For eth0, i need to verify whether Name dev exists and vlan ID 3 is for dev and Default Network is no.

similarly for all the interface. Usually i will get eth0 - 20 in output.

What i tried so far to achieve this and able to make it work using below method but below code is not at correct because it wont work if fields are interchanged.

What i actually doing is finding eth0 and redirecting below values to var 1, var2 , var3 and so on and then using these var1, var2, var3 to get my output.

but this wont work when fields interchange and when extra fields are added to output file.

(Note below code is example that i am trying)

I need your helps here to achieve this in proper way.

from itertools import islice
import string
import re
import os
import sys
a = "eth0"
def silentremove(filename): # remove file
   try:
       os.remove(filename)
   except OSError as e: # this would be "except OSError, e:" 
       if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory
          raise # re-raise exception if a different error occurred
file = "inputfile.txt"
silentremove(file)
with open("vnic1.txt") as f: # Remove empty lines
   for line in f:
      if not line.isspace():
          input_file = open('inputfile.txt', 'a')
          sys.stdout = input_file
          sys.stdout.write(line)
          input_file.close()
          sys.stdout = sys.__stdout__
d = {}
count = 0
with open('inputfile.txt') as f:
   for line in f:
      if (re.search(a, line, re.IGNORECASE)):
         var1, var2, var3, var4, var5,var6,var7,var8,var9,var10,var11,var12,var13, var14, var15, var16 = islice(f, 16)
         key, value = var1.strip().split(":", 1)
         d[key] = value
         ideth0 = "0 1"
         if (re.search(ideth0, value, re.IGNORECASE)):
            count +=1
         key, value = var5.strip().split(":", 1)
         d[key] = value
         name = "prod"
         if (re.search(name, value, re.IGNORECASE)):
            count +=1
         if count == 2:
            print "Working"
            print "Status-{}:".format(a)
            print "  ID    Name"
            print "  {}    {}".format(ideth0, name)

         else:
          print "Failed"   

解决方案

the text looks la YAML, but it's not, but it could be

with open("vnic1.txt") as f:
   data = f.read()
# makeing it yaml-string
data = dat.replace("  Name","- Name") # the 2 spaces are intended
import yaml
data = yaml.load(data) # you now have the entire structure as a huge dict, profit

this way you'll have in data something like this

{
    'NIC': [
        {'Dynamic MAC Addr': '00:00:00:00:00:01',
         'Ethernet Interface': [{'Config Qual': 'N/A',
                                 'Default Network': True,
                                 'Name': 'prod',
                                 'Operational VLAN': 'SWA',
                                 'VLAN ID': 2},
                                {'Config Qual': 'N/A',
                                 'Default Network': False,
                                 'Name': 'dev',
                                 'Operational VLAN': 'SWA',
                                 'VLAN ID': 3}],
         'ID': '0 1',
         'Name': 'eth0',
         'Preference': 'NONE'},
        {'Dynamic MAC Addr': '00:00:00:00:00:11',
         'Ethernet Interface': [{'Config Qual': 'N/A',
                                 'Default Network': True,
                                 'Name': 'prod',
                                 'Operational VLAN': 'SWB',
                                 'VLAN ID': 2},
                                {'Config Qual': 'N/A',
                                 'Default Network': False,
                                 'Name': 'dev',
                                 'Operational VLAN': 'SWB',
                                 'VLAN ID': 3}],
         'Fabric ID': '1 0',
         'Name': 'eth1',
         'Preference': 'NONE'}
    ]
}

which might not be what you asked for, but will definitely be a lot more easy to navigate (at least you have the sections correctly separated)

这篇关于Python处理文本文件以打印其输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆