【问题标题】:File path is not saving after Threading function线程功能后文件路径未保存
【发布时间】:2020-08-24 22:35:50
【问题描述】:

我正在使用 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()

然后我需要打开那条路径:

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

但我遇到了错误:

NameError: name 'viber' is not defined

我不知道该怎么做,以及如何解决它(((请有人帮忙!

【问题讨论】:

    标签: python variables subprocess python-multithreading


    【解决方案1】:

    当你在函数中声明viber变量时,python认为该变量是本地变量,在函数结束时将其删除。

    您只需将viber 声明为全局,这样函数就不会声明它自己的变量。

    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
    

    【讨论】:

    • 绝对是最好的!
    猜你喜欢
    • 2014-01-18
    • 1970-01-01
    • 2023-02-13
    • 1970-01-01
    • 2020-08-03
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多