Search code examples
pythonargumentssys

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.

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()