用 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 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.