Search code examples
pythonvariablessubprocesspython-multithreading

File path is not saving after Threading function


I am searching for files with Threading:

import threading
def thread(seconds):
    for root, dirs, files in os.walk('/'):
        for file in files:
            if file == 'Viber.exe':
                viber = os.path.join(root, file) 
                print(viber)
    print("Finish")
threading.Thread(target = thread, args = (1,), daemon = True).start()

And after that I need to open that path:

import subprocess
subprocess.check_output(viber, shell=True)

But I'm getting error:

NameError: name 'viber' is not defined

I don't know what to do, and how to fix it((( Please somebody help!


Solution

  • When you declare the viber variable in a function, python thinks the variable is local and will delete it when the function ends.

    You just need to declare viber as global so the function will not declare it's own variable.

    viber = None   # declare global variable # add this line
    
    import threading
    def thread(seconds):
        global viber    # use global variable  # add this line
        for root, dirs, files in os.walk('/'):
            for file in files:
                if file == 'Viber.exe':
                    viber = os.path.join(root, file) 
                    print(viber)
        print("Finish")
    threading.Thread(target = thread, args = (1,), daemon = True).start()
    
    ###########
    
    import subprocess
    subprocess.check_output(viber, shell=True)  # use global variable