用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