溫馨提示×

python os.system命令如何處理輸入輸出

小樊
142
2024-12-08 01:57:04
欄目: 編程語言

os.system() 函數在 Python 中用于執行系統命令

  1. 使用 subprocess 模塊:

subprocess 模塊提供了更強大和靈活的方式來處理子進程。你可以使用 subprocess.Popen 類來運行命令并獲取輸入輸出。以下是一個示例:

import subprocess

# 定義要執行的命令
command = "your_command_here"

# 創建一個子進程,設置 stdin、stdout 和 stderr
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True)

# 獲取命令的輸出
output, error = process.communicate()

# 等待命令執行完成
process.wait()

if process.returncode != 0:
    print(f"Error occurred: {error}")
else:
    print(f"Output: {output}")
  1. 使用 input()print() 函數與命令進行交互:

如果你需要與正在運行的命令進行交互,例如發送輸入并接收輸出,你可以使用 input() 函數向命令發送數據,并使用 stdout 屬性捕獲輸出。以下是一個示例:

import os

# 定義要執行的命令
command = "your_command_here"

# 創建一個子進程,設置 stdin 為 PIPE,以便我們可以發送輸入
process = os.system(command + " < input_file.txt", shell=True, stdout=subprocess.PIPE)

# 讀取命令的輸出
output = process.stdout.read().decode('utf-8')

# 等待命令執行完成
process.wait()

print(f"Output: {output}")

在這個示例中,我們將輸入數據放入名為 input_file.txt 的文件中,然后將其傳遞給命令。命令的輸出將被捕獲并打印出來。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女