用Python在后台写入文件
在这里,我们尝试一次执行两项任务,一项在前台,另一项在后台。我们将在后台的文件中输入一些内容,并在其中输入用户输入的数字,以查找它是奇数还是偶数。
通过在多线程中可以在python中的一个程序中执行多个任务
import threading
import time
class AsyncWrite(threading.Thread):
def __init__(self, text, out):
threading.Thread.__init__(self)
self.text = text
self.out = out
def run(self):
f = open(self.out, "a")
f.write(self.text + '\n')
f.close()
time.sleep(3)
print ("Finished Background file write to " + self.out)
def Main():
message = input("输入要存储的字符串:" )
background = AsyncWrite(message,'out.txt')
#print threading.enumerate()
background.start()
print ("The program can continue while it writes in another thread")
num = int(input("Entered number is : "))
if (num%2==0):
print("Entered number is Even")
else:
print("Entered number is ODD")
background.join()
print ("Waited until thread was complete")
# print (threading.enumerate())
if __name__ == '__main__':
Main()输出结果
输入要存储的字符串:Nhooo The program can continue while it writes in another thread Entered number is : 33 Entered number is ODD Finished Background file write to out.txt Waited until thread was complete
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短