用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 朋友弟弟生日祝福语简短