當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python os.pipe2()用法及代碼示例


Python中的OS模塊提供了與操作係統進行交互的函數。操作係統屬於Python的標準實用程序模塊。該模塊提供了使用依賴於操作係統的函數的便攜式方法。

管道是一種將信息從一個進程傳遞到另一個進程的方法。它僅提供one-way通信,並且傳遞的信息由係統保留,直到被接收進程讀取為止。
os.pipe2()Python中的方法用於創建自動設置了標誌的管道。

用法: os.pipe2(flags)

參數:
flags:flags參數是通過對os.O_NONBLOCK和os.O_CLOEXEC值中的一個或多個進行“或”運算來構造的。

返回類型:此方法返回分別可用於讀取和寫入的一對文件描述符(r,w)。

代碼:使用os.pipe2()方法創建帶有自動設置標誌的管道
# Python program to explain os.pipe2() method  
  
# importing os module  
import os 
  
  
# Create a pipe with 
# flag set automatically 
# os.O_NONBLOCK flag tells  
# that file descriptor  
# is in non-blocking mode 
flags = os.O_NONBLOCK 
r, w = os.pipe2(flags) 
  
# The returned file descriptor r and w 
# can be used for reading and 
# writing respectively. 
  
# We will create a child process 
# and using these file descriptor 
# the parent process will write  
# some text and child process will 
# read the text written by the parent process 
  
# Create a child process 
pid = os.fork() 
  
# pid greater than 0 represents 
# the parent process 
if pid > 0:
  
    # This is the parent process  
    # Closes file descriptor r 
    os.close(r) 
  
    # Write some text to file descriptor w  
    print("Parent process is writing") 
    text = b"Hello child process"
    os.write(w, text) 
    print("Written text:", text.decode()) 
  
      
else:
  
    # This is the child process  
    # Closes file descriptor w 
    os.close(w) 
  
    # Read the text written by parent process 
    print("\nChild Process is reading") 
    r = os.fdopen(r) 
    print("Read text:", r.read())
輸出:
Parent process is writing
Text written:Hello child process

Child Process is reading
Text read:Hello child process

參考: https://docs.python.org/3/library/os.html#os.pipe2



相關用法


注:本文由純淨天空篩選整理自ihritik大神的英文原創作品 Python | os.pipe2() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。