【发布时间】:2020-01-29 18:25:42
【问题描述】:
我尝试在我编写的工具中实现多线程,但我得到了意想不到的结果。
这是工作代码:
#Import modules
import os
import time
import sys
#Params
print("___________Auto ShutApp___________\n")
print("Type the AppName then the time before app will shut")
apptokill = str(input("\nWhich App you'd like to Shut: "))
Time = int(input("\nHow long before App should stop(in minutes): "))
def timeS(arg): #arg = time in seconds
time.sleep(arg*60)
def killer(apptokill, Time):
timeS(Time)
os.system("pkill %s"%(apptokill))
killer(apptokill, Time)
这很好用,但我想知道它什么时候会杀死一个应用,所以我添加了一个新功能
def Timer():
time_start = time.time()
seconds = 0
minutes = 0
while True:
try:
sys.stdout.write("\rTimer have start since {minutes} Minutes {seconds} Seconds".format(minutes=minutes, seconds=seconds))
sys.stdout.flush()
time.sleep(1)
seconds = int(time.time() - time_start) - minutes * 60
if seconds >= 60:
minutes += 1
seconds = 0
except KeyboardInterrupt:
break
这个也很好用,但如果我放置该函数,它将运行 killer 或 Timer - 不能同时运行。
然后我尝试了一些多线程,添加以下代码:
if __name__ == "__main__":
t1 = threading.Thread(target=killer, name='t1')
t2 = threading.Thread(target=Timer, name='t2')
t1.start()
t2.start()
t1.join()
t2.join()
但是从这段代码中我得到了这个错误:
Traceback (most recent call last):
File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner
self.run()
File "/usr/lib/python3.7/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
TypeError: killer() missing 2 required positional arguments: 'apptokill' and 'Time'
我假设apptokill 保存在内存中,所以Time 也是如此。我完全迷路了。
【问题讨论】:
标签: python multithreading