我正在使用線程搜索文件:import threadingdef 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 subprocesssubprocess.check_output(viber, shell=True)但我收到錯誤:NameError: name 'viber' is not defined我不知道該怎么做,以及如何解決它(((請有人幫忙!
1 回答

青春有我
TA貢獻1784條經驗 獲得超8個贊
當您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
添加回答
舉報
0/150
提交
取消