用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 婆婆高寿祝福语大全简短