用 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("Enter a string to store:" )
   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()

输出

Enter a string to store:Tutorialspoint
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

更新于: 2019 年 7 月 30 日

160 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告