简体   繁体   中英

Python Import file module into another

I am trying to import a variable called log_entry_counts from a python file called data_processed.py into anothe file in the same directory called failed_hmac.py to do some percentage calculations but after importing, i am not able to access the variables inside the imported module(file). Here is the first file name data_processed.py . import os from datetime import datetime, timedelta from collections import Counter

def dataCount(folderName):
    #count = 0
    log_entry_counts = Counter()
    today_date = datetime.today()
    date_ranges = [
                    ('30 Days', today_date - timedelta(days=30)),
                   # ('3 months', today-date - timedelta(days=90)),
                    #('year', today-date - timedelta(days=365))
                  ]
    for path, dirs, files in os.walk(folderName):
        for dirname in dirs:
            log_date = (os.path.join(path, dirname))

        for items in files:
            if items != ".DS_Store":
                try:
                    log_date = datetime.strptime(path[39:47], '%m%d%Y')
                    for text, dr in date_ranges:
                        if log_date >= dr:
                            log_entry_counts[text] += 1
                except ValueError:
                    print 'This line has a problem:', log_date

    total = 0

    print log_entry_counts['30 Days'] 

def main():

    filePath = 'file.txt'

    hmacCount(filePath)

if __name__ == "__main__":

    main()

It loops through a folder and count files inside all subfolders. The other file name failed_hmac.py is as follows

import os, sys
from datetime import datetime, timedelta
from collections import Counter
import data_processed

def hmacCount(fileName):
    # Get the last failed hmac date
    fileHandle = open('file.txt',"r")
    lineList = fileHandle.readlines()
    fileHandle.close()
    lastLine = lineList[-1]
    lastDate = datetime.strptime(lastLine[:10], '%m/%d/%Y')

    with open(fileName) as f_input:

        logEntryCounts = Counter()

        #today_date = datetime.today() - timedelta(days=14)
                #print today_date
        dateRanges = [
                    ('30 Days', lastDate - timedelta(days=30)),
                    #('3 months', lastDate - timedelta(days=90)),
                    #('One year', lastDate - timedelta(days=330))
                  ]

        for line in f_input:

            #Stop Processing if there are no more lines
            if not line:

                break

            if "Following hmac" in line:

                try:
                    logDate = datetime.strptime(line[:10], '%m/%d/%Y')

                    for text, dr in dateRanges:

                        if logDate >= dr:

                            logEntryCounts[text] += 1

                except ValueError:

                    print 'This line has a problem:', logDate

    total = 0

    hmacData = float(logEntryCounts['30 Days'])

    print logEntryCounts['30 Days']

# Call The function
def main():

    filePath = 'file.txt'

    hmacCount(filePath)

if __name__ == "__main__":

    main()  

The goal is to import data_processed.py into failed_hmac.py and use the variables logEntryCounts and log_entry_counts to perform some percentage calculations but i kept getting logEntryCounts not defined error

data_entry_logs is a variable inside a function in data_processed.py . You will have to modify your code to call the function data_processed.dataCount() and return the value, so that you will be able to use the variable.

In data_processed.py :

def dataCount(folderName):
    #your code
    return log_entry_counts

In failed_hmac.py :

Replace

hmacData = float(logEntryCounts['30 Days'])

with

hmacData = float(data_processed.dataCount(...)['30 Days'])

Another approach, which I think is the cleaner approach would be to declare both these functions in a class, as specifed in this question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM