Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

start script with arguments sys.argv

Im trying to start this script with a argument.

When i start the script from a terminal i want to type "python test.py C:\Users\etc\etc\log.log count" to run func1 or error to run func3.

I have try to play around with sys.argv / sys.argv[2] but i cant get it to work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import sys



def func1():
    
    count = 0
    with open(r'C:\Users\etc\etc\log.log') as logfile:
        lines = logfile.readlines()
    for error in lines:
        count += error.count('[error]')  
    print('errors', count)

def func3():

    import re
    
    with open(r'C:\Users\etc\etc\log.log') as logfile:
        for line in map(str.strip, logfile):
            m = re.findall('\[.*?\]', line)
            if len(m) > 1 and m[1] in ('[error]'):
                offset = line.find(m[1]) + len(m[1]) + 1
                print(m[0], line[offset:])


if __name__ == '__main__':
    
    func1()
    func3()

>Solution :

sys.argv is a list containing the arguments passed to the program. The first item is the file name, the rest are the arguments so to get the first argument you use sys.argv[1].
Because the first argument isn’t necessarily provided, I’ve used a try/except block to catch the possible IndexError. You can handle this however you like.
You can then just use an if statement to decide which function to run.

import sys

def func1():
    
    count = 0
    with open(r'C:\Users\etc\etc\log.log') as logfile:
        lines = logfile.readlines()
    for error in lines:
        count += error.count('[error]')  
    print('errors', count)

def func3():

    import re
    
    with open(r'C:\Users\etc\etc\log.log') as logfile:
        for line in map(str.strip, logfile):
            m = re.findall('\[.*?\]', line)
            if len(m) > 1 and m[1] in ('[error]'):
                offset = line.find(m[1]) + len(m[1]) + 1
                print(m[0], line[offset:])


if __name__ == '__main__':
    try:
        arg = sys.argv[1]
    except: pass
    else:
        if arg == "count":
            func1()
        elif arg == "error":
            func3() 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading