溫馨提示×

Python system函數執行腳本的技巧

小樊
100
2024-07-17 20:30:51
欄目: 編程語言

在Python中,可以使用subprocess模塊中的run函數來執行系統命令或腳本。以下是一些執行腳本的技巧:

  1. 執行簡單的命令或腳本:
import subprocess

result = subprocess.run(["ls", "-l"], stdout=subprocess.PIPE)
print(result.stdout.decode())
  1. 檢查命令的返回值:
result = subprocess.run(["ls", "non_existent_file"], stdout=subprocess.PIPE)
if result.returncode != 0:
    print("Command failed with error code:", result.returncode)
  1. 在shell中執行命令(可以使用通配符等特殊字符):
result = subprocess.run("ls *.txt", shell=True, stdout=subprocess.PIPE)
print(result.stdout.decode())
  1. 傳遞參數給腳本:
name = "Alice"
result = subprocess.run(["./hello.sh", name], stdout=subprocess.PIPE)
print(result.stdout.decode())
  1. 獲取命令的輸出和錯誤信息:
result = subprocess.run(["ls", "non_existent_file"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if result.returncode != 0:
    print("Error:", result.stderr.decode())
  1. 設置工作目錄:
result = subprocess.run(["ls"], cwd="/path/to/directory", stdout=subprocess.PIPE)
print(result.stdout.decode())

這些技巧可以幫助你更方便地執行系統命令或腳本,并處理相應的輸出和錯誤信息。請注意安全性,盡量避免直接在腳本中執行用戶輸入的命令。

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