溫馨提示×

python怎么調用命令行

小億
115
2024-12-07 07:41:30
欄目: 編程語言

在Python中,你可以使用subprocess模塊來調用命令行。subprocess模塊提供了多種函數來執行外部命令和與其交互。以下是一些常用的方法:

  1. 使用subprocess.run()執行一個命令并等待它完成:
import subprocess

result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
print(result.stdout)
  1. 使用subprocess.Popen()執行一個命令并與其進行交互:
import subprocess

process = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
stdout, stderr = process.communicate()
print(stdout)
print(stderr)
  1. 使用subprocess.check_output()執行一個命令并獲取其輸出(僅適用于Python 2.7及更早版本):
import subprocess

output = subprocess.check_output(['ls', '-l'])
print(output.decode('utf-8'))

請注意,這些示例中的命令是用于類Unix系統的(如Linux和macOS)。如果你正在使用Windows系統,你需要將命令和參數更改為適用于Windows的命令。

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