gpt4 book ai didi

python - 线程功能后文件路径未保存

转载 作者:行者123 更新时间:2023-12-04 09:00:48 28 4
gpt4 key购买 nike

我正在使用线程搜索文件:

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
我不知道该怎么做,以及如何解决它(((请有人帮忙!

最佳答案

当您声明 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

关于python - 线程功能后文件路径未保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63569568/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com