簡體   English   中英

在python中讀取多個依賴文件

[英]Reading multiple depended files in python

我正在使用python編寫程序,遇到了一些麻煩。 我的程序應該做的是從文件中讀取一行,對其進行解析,然后將該行的一部分寫入字符串。 然后,它應該在另一個文件中搜索該字符串,並在找到該字符串時打印該行。 然后,它應該向下移動到第一個文件的下一行,並重復該過程,直到讀取了第一個文件中的所有行。

我的代碼如下:

def readermain():
    """called if constant file exists"""

    for line in portslist: #reads printer port list and parses name and port address 
        marker = line.split()
        printername=marker[0]
        address=marker[1]

        for lines in constantfile:
            if address in lines: #if the desired address is in the line
                lineholder=lines.split()
                print (lineholder)
                oldonline=lineholder[4]
                oldutc=lineholder[5]
                status=lineholder[2]
                address=lineholder[1]

問題是, for line in portslist中的第一for line in portslist似乎沒有移到下一行。 它一遍又一遍地打印出同一行。 portslistconstantfile和list都在程序中使用constantfile=open("constantfile.dat").readlines()等聲明了其他位置。我是python的新手,似乎無法弄清楚這里發生了什么。 任何幫助或建議都非常歡迎。

該程序本身很長,我累了總結問題區域,但我將其發布在下面。 這是一項正在進行中的工作,因此我知道還有其他錯誤,是的,這不是可讀性最好的例子。 仍然有很好的建議。

"""Program to pull down list of printers and ping each to see if it is online. 
Will track printers over time, if printer has been offline for over a year it will be listed in a delete file.
This program is designed to run on windows and requires python to be installed. """

import win32com.client, os, time, datetime
from datetime import datetime




computername="(name goes here)"
currentdate=datetime.now()
currentdateutc= (time.mktime(currentdate.timetuple()))

def getPorts(computername):
    """Gets printer name and port name"""

    portslist= open("printerports.txt","w")

    objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator") 
    objSWbemServices = objWMIService.ConnectServer(computername,"root\cimv2") 
    colItems = objSWbemServices.ExecQuery("Select * from Win32_Printer") 
    for objItem in colItems:
        list= objItem.Name + " " + objItem.PortName+"\n"
        portslist.write(list)

    portslist.close()

def pingone(address):
    """Pings address and returns 0 if it is online"""
    pingreturn=os.system("ping -n 1 " + address)
    return (pingreturn)

def pingfive(address):
    """Pings as address five times"""
    pingreturn=os.system("ping -n 5 " + address)
    return (pingreturn)

def online(printername, address, currentdate):
    return str((printername +" at port "+ address+" is online on "+ str(currentdate)+"\n"))

def offline(printername, address, currentdate):
    return str((printername +" at port "+address+" is offline on "+ str(currentdate)+"\n"))

def constantonline(printername, address, currentdate, currentdateutc):
    return str((printername+" "+address+" "+str(0)+" "+str(currentdate)+" "+str(currentdate)+" "+str(currentdateutc)+"\n"))

def constantoffline(printername, address, currentdate, oldonline, oldutc):
    return str((printername+" "+address+" "+str(1)+" "+str(currentdate)+" "+str(oldonline)+" "+str(oldutc)+"\n"))

def removal(printername, address, oldonline):
    return str((printername+" with queue "+address+" has been offline since "+str(oldonline)+"\n"))

def constantfilecheck():
    """Checks for constant file"""
    if os.path.isfile("constantfile.dat")==True:  #checks if a constant file exists. if not one is made
        return True

    else:
        return False

def readermain(portslist, constantfile, counter, oncounter, offcounter):
    """called if constant file exists"""

    for line in portslist: #reads printer port list and parses name and port address 
        print(line)
        marker = line.split()
        printername=marker[0]
        address=marker[1]

        for lines in constantfile:
            print(lines)
            if address in lines: #if the desired address is in the line
                lineholder=lines.split()
                print (lineholder)
                oldonline=lineholder[4]
                oldutc=lineholder[5]
                status=lineholder[2]
                address=lineholder[1]
                #--------------------------------------------------------------------------------------------------------------------------------------------
                print ("Address found in constant file")

                if pingone(address)==0:
                    newconstantfile.write(constantonline(printername, address, currentdate, currentdateutc))
                    onlinefile.write(online(printername, address, currentdate))
                    oncounter += 1
                    counter += 1

                else:
                    if pingfive(address)==0:
                        newconstantfile.write(constantonline(printername, address, currentdate, currentdateutc))
                        onlinefile.write(online(printername, address, currentdate))
                        oncounter += 1
                        counter += 1

                    else:
                        newconstantfile.write(constantoffline(printername, address, currentdate, oldonline, oldutc))
                        offlinefile.write(offline(printername, address, currentdate))
                        offcounter += 1
                        counter += 1
                        if status == 0 and (currentdateutc-oldutc)>=31556926:
                            #-----------------------------------------------------------------------------------------------------------------------------------
                            print("printer older than year")
                            deletefile=open("removefile.txt", "a")
                            deletefile.write(removal(printername, address, oldonline))
                            deletefile.close()
            else:
                #not in constant file
                #------------------------------------------------------------------------------------------------------------------------------------------------
                print("not in constant file")
                if pingone(address)==0:
                    newconstantfile.write(constantonline(printername, address, currentdate, currentdateutc))
                    onlinefile.write(online(printername, address, currentdate))
                    oncounter += 1
                    counter += 1

                else:
                    if pingfive(address)==0:
                        newconstantfile.write(constantonline(printername, address, currentdate, currentdateutc))
                        onlinefile.write(online(printername, address, currrentdate))
                        oncounter += 1
                        counter += 1

                    else:
                        newconstantfile.write(printername+" "+address+" "+str(1)+" "+str(currentdate)+" "+str(oldonline)+" "+str(currentdateutc)+"\n")
                        offlinefile.write(offline(printername, address, currentdate))
                        offcounter += 1
                        counter += 1

def readersecondary(oncounter, offcounter, counter):
    """called if no constant file exists already"""

    for line in portslist: #reads printer port list and parses name and port address 

        marker = line.split()
        printername=marker[0]
        address=marker[1]

        if pingone(address)==0:
            newconstantfile.write(constantonline(printername, address, currentdate, currentdateutc))
            onlinefile.write(online(printername, address, currentdate))
            oncounter += 1
            counter += 1

        else:
            if pingfive(address)==0:
                newconstantfile.write(constantonline(printername, address, currentdate, currentdateutc))
                onlinefile.write(online(printername, address, currrentdate))
                oncounter += 1
                counter += 1

            else:
                newconstantfile.write(printername+" "+address+" "+str(1)+" "+str(currentdate)+" "+str(currentdate)+" "+str(currentdateutc)+"\n")
                offlinefile.write(offline(printername, address, currentdate))
                offcounter += 1
                counter += 1
    return counter, oncounter, offcounter
def rename():
    """Deleates old constant file and renames newconstantfile to constantfile"""
    if constantfilecheck() is True:
        os.system("del constantfile.dat")

    os.system("ren newconstantfile.dat constantfile.dat")
    os.system("del printerports.txt")

#_______________________________________________________________________________________________________________
#END OF FUNCTIONS
#_______________________________________________________________________________________________________________


oncounter=0
offcounter=0
counter=0

print ("Getting ports from server\n")   
getPorts(computername)

portslist=open("printerports.txt", "r").readlines()
newconstantfile=open("newconstantfile.dat", "w")
onlinefile=open("onlinefile.txt", "w")
offlinefile=open("offlinefile.txt", "w")

print ("checking for constant file")
if constantfilecheck() == True:
    constantfile=open("constantfile.dat").readlines()
    print("calling reader main")
    readermain(portslist, constantfile, counter, oncounter, offcounter)
    constantfile.close()
elif constantfilecheck() == False:
    print("calling reader secondary")
    readersecondary(oncounter, offcounter, counter)

offlinefile.write("\nTotal Printers Scanned: "+str(counter))
offlinefile.write("\nPrinters online: "+str(oncounter))
offlinefile.write("\nPrinters offline: "+str(offcounter))
onlinefile.write("\nTotal Printers Scanned: "+str(counter))
onlinefile.write("\nPrinters online: "+str(oncounter))
onlinefile.write("\nPrinters offline: "+str(offcounter))

portslist.close()
newconstantfile.close()
onlinefile.close()
offlinefile.close()

rename() #calls rename function

我知道我不應該使用os.system,但這應該是一個快速又骯臟的小項目。 該程序旨在長時間(幾年)內跟蹤大量打印機(成千上萬個)的在線狀態。 通過對從打印服務器提取的打印機列表執行ping操作,並在常量文件中記錄日期,聯機狀態和端口名稱來實現此目的。

這是portslist文件中的一行: artp002 10.40.80.18格式化為“名稱端口”

這是常量文件的示例:`artp002 10.40.80.18 0 2012-08-30 13:32:34.787000 2012-08-30 13:32:34.787000 1346347954.0'格式為“名稱端口date_last_checked last_online_date time_in_utc

這是程序運行時的輸出:

Getting ports from server

checking for constant file
calling reader main
artp002 10.40.80.18

artp002 10.40.80.18 0 2012-08-30 13:32:34.787000 2012-08-30 13:32:34.787000 1346347954.0

['artp002', '10.40.80.18', '0', '2012-08-30', '13:32:34.787000', '2012-08-30', '13:32:34.787000', '1346347954.0']
Address found in constant file

Pinging 10.40.80.18 with 32 bytes of data:
Reply from 10.40.80.18: bytes=32 time=6ms TTL=61

Ping statistics for 10.40.80.18:
    Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 6ms, Maximum = 6ms, Average = 6ms
artp002 10.40.80.18 0 2012-08-30 13:32:34.787000 2012-08-30 13:32:34.787000 1346347954.0

['artp002', '10.40.80.18', '0', '2012-08-30', '13:32:34.787000', '2012-08-30', '13:32:34.787000', '1346347954.0']
Address found in constant file

Pinging 10.40.80.18 with 32 bytes of data:
Reply from 10.40.80.18: bytes=32 time=6ms TTL=61

Ping statistics for 10.40.80.18:
    Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 6ms, Maximum = 6ms, Average = 6ms
artp002 10.40.80.18 0 2012-08-30 13:32:34.787000 2012-08-30 13:32:34.787000 1346347954.0

['artp002', '10.40.80.18', '0', '2012-08-30', '13:32:34.787000', '2012-08-30', '13:32:34.787000', '1346347954.0']
Address found in constant file

Pinging 10.40.80.18 with 32 bytes of data:
Reply from 10.40.80.18: bytes=32 time=6ms TTL=61

以下是for line in portslist: print (line)print (line)輸出print (line)print (line) for line in portslist:

Getting ports from server

checking for constant file
calling reader main
artp002 10.40.80.18

artp002 10.40.80.18 0 2012-08-30 13:32:34.787000 2012-08-30 13:32:34.787000 1346347954.0

['artp002', '10.40.80.18', '0', '2012-08-30', '13:32:34.787000', '2012-08-30', '13:32:34.787000', '1346347954.0']
Address found in constant file

Pinging 10.40.80.18 with 32 bytes of data:
Reply from 10.40.80.18: bytes=32 time=8ms TTL=61

Ping statistics for 10.40.80.18:
    Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 8ms, Maximum = 8ms, Average = 8ms
artp011 artp011.printers.xxxxxx.edu 0 2012-08-30 13:32:34.787000 2012-08-30 13:32:34.787000 1346347954.0

not in constant file

Pinging 10.40.80.18 with 32 bytes of data:
Reply from 10.40.80.18: bytes=32 time=8ms TTL=61

讀取文件的所有file_object.seek(0) ,必須使用file_object.seek(0)將光標倒回到起點。 否則,進一步嘗試讀取行將返回None 我在下面更正了您的代碼,請參閱最后一行:

def readermain():
    """called if constant file exists"""

    for line in portslist: #reads printer port list and parses name and port address 
        marker = line.split()
        printername=marker[0]
        address=marker[1]

        for lines in constantfile:
            if address in lines: #if the desired address is in the line
                lineholder=lines.split()
                print (lineholder)
                oldonline=lineholder[4]
                oldutc=lineholder[5]
                status=lineholder[2]
                address=lineholder[1]

        constantfile.seek(0) # rewinds the file

使您的代碼更易於閱讀和測試,然后您將發現問題更容易。 特別地:

  • 為變量的名稱命名:
    • for port_info in portlines:
    • for printer_details in consntantfile:
  • 用下划線將變量名稱中的單詞分開:
    • printer_name ,而不是printername
    • old_utc ,不是old_utc
  • 與其依賴於像portlinesconstantfile這樣的全局變量,不如將它們作為參數傳遞給該函數。 然后,您可以使用少量數據調用此函數,然后手動調試問題。
  • 向我們提供了兩個文件的內容以及程序的輸出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM