Home > Back-end >  Custom file doesn't work when directory is changed
Custom file doesn't work when directory is changed

Time:10-11

Okay, so I have this interpreter thing that I made out of boredom, but it doesn't work when I change its directory. When I have it in the same folder as the main.py file, it works fine, but when I put it in the test folder, I get an error. UnboundLocalError: local variable 'individual' referenced before assignment This is what handles the argument for the file path:

if __name__ == "__main__":
    argv = sys.argv
    #try:
    if argv[1] != None:
        if argv[1].split("/"):
            target = argv[1].split("/")[len(argv[1].split("/"))-1]
            __main__(target)
        else:
            target = argv[1]
            __main__(target)
    else:
        print("No file specified")
    #except Exception as e:
        #print(e)

This is the main function that reads the file then interprets it:

def __main__(target):
    for file in os.listdir("."):
        if file.endswith(EXTEN):
            with open(os.path.join(os.getcwd(), file)) as f:
                lines = f.readlines()
                for each in lines:
                    individual = each.split()
                
    process_command(individual)

I've already tried searching for what it means, and it's kind of helped me, so I figured this was my last hope.

CodePudding user response:

The error means you're referring to individual before you assign to it. Since the assignment to individual is buried under a few control flow statements, it's possible for you to get to process_command(individual) without going into the loop or reading the file.

Add individual = [] (or None or some other default) at the top of your function to ensure that the variable exists regardless of the value of target or the contents of the file.

CodePudding user response:

This is the relevant block:

with open(os.path.join(os.getcwd(), file)) as f:
                lines = f.readlines()
                for each in lines:
                    individual = each.split()

This code block is Never reached because file.endswith(EXTEN) is never true, or the `os.listdir(".") itself is empty. Also, any file that does reach this block but is empty would also not assign anything to individual. I recommend using a debugger or some print statements to see what files you're iterating through in your main function.

  • Related