用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
热门推荐
4 甄嬛传祝福语简短
10 新老师祝福语 简短独特
11 新年祝同学祝福语简短
12 生日祝福语简短搞笑女儿
13 迟到的过年祝福语简短
14 妈妈生日祝福语简短温暖
15 宝宝祝福语诗意简短 古文
16 年后祝福语简短走心
17 送离职同事简短祝福语
18 老师新婚快乐祝福语简短