Python script to read ini file and return value accordingly

Hi Experts,
Would like to achieve below using python function. Could anyone help please

1. Python script (a function/def) to accept an argument. E.g. Instance_id1 or Instance_id2 or Instance_id3.
2.  Script to locate relevant instance section in the ini file. (sample file below).
3. Get always_on_start_time, always_on_finish_time, and current system time.
4. Then identify current time is not within start/finish time.
3.  If within, start/finish time, return true, else false.

We will have to further execute few more task based on above return string.

Thanks in advance.

Sample ini file
[instance_id1]
always_on_start_time=04:00
always_on_finish_time=06:00

[instance_id2]
always_on_start_time=11:00
always_on_finish_time=13:00

[instance_id3]
always_on_start_time=18:00
always_on_finish_time=21:00

Open in new window

enthuguyAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ArionPython CoderCommented:
This code works in python 3.x:


import configparser #This module comes pre-installed with python
from datetime import datetime #So does this one

config = configparser.ConfigParser() #Create the config parsing object

config.read('config.ini') #reads the config file

def readInstance(instance):
    if instance in config.sections(): #checks if the given instance actually exists in the config file
        startTime = int(config[instance]["always_on_start_time"].replace(":", "")) #read the specific config data and then convert it into an integer
        finishTime = int(config[instance]["always_on_finish_time"].replace(":", "")) # repeat process for ending
        currTime = int(datetime.now().strftime('%H:%M').replace(":", "")) # get current Time
        if startTime > currTime or finishTime < currTime: 
            return False
        else:
            return True
    else:
        raise Exception("Instance: '"+instance+"' does not exist in the ini file!") #Will raise an error if the instance doesn't exist, (optional, you can just make it return False if you prefer)
 

print(readInstance("instance_id1"))

Open in new window


Compacted version of the code: (The first is designed more to make it easier to understand)

import configparser 
from datetime import datetime 

config = configparser.ConfigParser()

config.read('config.ini') 

def readInstance(instance):
    if instance in config.sections(): 
        startTime = int(config[instance]["always_on_start_time"].replace(":", "")) 
        finishTime = int(config[instance]["always_on_finish_time"].replace(":", "")) 
        currTime = int(datetime.now().strftime('%H%M'))
        if startTime > currTime or finishTime < currTime: 
            return False
        else:
            return True
    else:
        raise Exception("Instance: '"+instance+"' does not exist in the ini file!")

Open in new window

enthuguyAuthor Commented:
Thanks a lot Arion. Much appreciated.

Will update you
enthuguyAuthor Commented:
Hi Arion, how to invoke this pls? I tried below but getting nothing :)

from windows
python.exe validateInstance.py instance_id2

Open in new window

SD-WAN: Making It Work for You

As bandwidth requirements and Internet costs grow, businesses naturally want to manage budgets by reducing reliance on their most expensive connection types. Learn more about how to make SD-WAN work for your business in our on-demand webinar!

ArionPython CoderCommented:
Ok, to parse arguments into a python file you also require the parseargs module. (I also slightly modified it so if it errors out it will just print the error instead of a useless traceback.

import configparser
import argparse #Argparse allows you to parse arguments into a file through the command line
from datetime import datetime


parser = argparse.ArgumentParser(description='Process ini files') #Create the parser object

parser.add_argument('file', help='Enter the location of the .ini file that you want to process') #Add the file you want to read into
parser.add_argument('instance', help='Enter the instance of the .ini file that you want to check') # Enter the instance you want to read

args = parser.parse_args() #Read the parsed args

file = args.file #deposit them into variables
instance = args.instance #same as above

#Everything below is the same
config = configparser.ConfigParser()
config.read(file) 

def readInstance(instance):
    if instance in config.sections(): 
        startTime = int(config[instance]["always_on_start_time"].replace(":", "")) 
        finishTime = int(config[instance]["always_on_finish_time"].replace(":", "")) 
        currTime = int(datetime.now().strftime('%H%M'))
        if startTime > currTime or finishTime < currTime: 
            return False
        else:
            return True
    else:
        print("Either the specified file is not a ini file or it doesnt contain the specified instance.")
        return None

print(readInstance(instance))

Open in new window


Once agian, more compact:

import configparser, argparse
from datetime import datetime

parser = argparse.ArgumentParser(description='Process ini files')

parser.add_argument('file', help='Enter the location of the .ini file that you want to process')
parser.add_argument('instance', help='Enter the instance of the .ini file that you want to check')

args = parser.parse_args()
file = args.file
instance = args.instance

config = configparser.ConfigParser()
config.read(file) 

def readInstance(instance):
    if instance in config.sections(): 
        startTime = int(config[instance]["always_on_start_time"].replace(":", "")) 
        finishTime = int(config[instance]["always_on_finish_time"].replace(":", "")) 
        currTime = int(datetime.now().strftime('%H%M'))
        if startTime > currTime or finishTime < currTime: 
            return False
        else:
            return True
    else:
        print("Either the specified file is not a ini file or it doesnt contain the specified instance.")
        return None

print(readInstance(instance))

Open in new window


To run the program, from the command line:

python.exe validateInstance.py config.ini instance_id2

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
enthuguyAuthor Commented:
Once again thanks a lot Arion, that was really helpful
enthuguyAuthor Commented:
HI Arion
sorry, could you help me with this timing value pls
for some reason, it is not picking up this value

[i-064409857a03920aa]
always_on_start_time=23:00
always_on_finish_time=02:00
ArionPython CoderCommented:
python.exe validateInstance.py config.ini i-064409857a03920aa

Open in new window


This command worked for me, make sure you specify the correct filename (I set it to config.ini but it depends on what your ini file is called)
enthuguyAuthor Commented:
Apologies,
I was trying this script on AWS and the server was in US region

All good :)
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
aws-cli

From novice to tech pro — start learning today.