0

I'm not sure if there's an answer to this but I thought I'd ask. This could very well be something Python just won't do.

I've written a small function to create a date/time stamped text file in a specific folder as a sort of log. I'm writing a lot of file transfer scripts that will be automated so I wanted a way to keep track of when they've actually run. I've also set it up to split a script name, passed into the function using os.path.basename(__file__). Here's my code for creating the log files (filepath replaced as it's a business file structure):

def loggerauto(fileNameRaw):

    name, ext = fileNameRaw.split('.')
    jobName = name
    
    now = datetime.now()
    dateStamp = now.strftime("%y.%m.%d-%H.%M")
    fileNam = jobName + " " + dateStamp
    logPath = "PATH"

    fileList = glob.glob(logPath + jobName + "*", recursive=True)

    for filePath in fileList:
        try:
            os.remove(filePath)
        except OSError:
            print("Error deleting old file!")

    print("Writing " + jobName + " log file...")
    logfile = open(logPath + fileNam + ".txt", "w")
    logfile.close
    print("Done!")

In a nutshell, it takes in the file name, splits it to remove the extension. Uses that as the name of the log file and adds the time and date. It checks for a file with the same job name in the folder and deletes it if it exists. Then creates a new one with the current time and date.

I've set this up in a separate module so I can just call it in all my scripts (much easier than pasting this code into 20 scripts) but I currently have to call it like this:

tt.loggerauto(os.path.basename(__file__))

I want to make it more user friendly and have it automatically get the name of the running script and pass it into the function, so you can call it like this:

tt.loggerauto()

If I put the os.path.etc line in the function code, it gets the name of the module the function is in, which makes sense. I can't think of a way to get the running script file name automatically. Is there any way to do this?

TomCrow
  • 47
  • 8
  • I believe this https://stackoverflow.com/questions/3711184/how-to-use-inspect-to-get-the-callers-info-from-callee-in-python contains the answer you are looking for – Ranika Nisal Jul 23 '20 at 12:18

1 Answers1

0

Importing inspect helps in identifying the calling function's filename.

inspect.stack() returns following data

[FrameInfo(frame=<frame object at 0x2817808>, filename='/home/logeshwaran/ins2.py', lineno=6, function='loggerauto', code_context=['    print(inspect.stack())\n'], index=0), FrameInfo(frame=<frame object at 0x7f0286681828>, filename='ins1.py', lineno=2, function='<module>', code_context=['loggerauto()\n'], index=0)]

Calling the jobname with inspect does the task

from datetime import datetime
import glob
import os
import inspect
def loggerauto():

    jobName = inspect.stack()[1][1]

    now = datetime.now()
    dateStamp = now.strftime("%y.%m.%d-%H.%M")
    fileNam = jobName + " " + dateStamp
    logPath = "PATH"

    fileList = glob.glob(logPath + jobName + "*", recursive=True)

    for filePath in fileList:
        try:
            os.remove(filePath)
        except OSError:
            print("Error deleting old file!")

    print("Writing " + jobName + " log file...")
    logfile = open(logPath + fileNam + ".txt", "w")
    logfile.close
    print("Done!")

This can now be called as below

loggerauto()

Reference: https://docs.python.org/3/library/inspect.html

Logesh
  • 53
  • 1
  • 8