在Python中,可以使用subprocess
模塊中的run
函數來執行系統命令或腳本。以下是一些執行腳本的技巧:
import subprocess
result = subprocess.run(["ls", "-l"], stdout=subprocess.PIPE)
print(result.stdout.decode())
result = subprocess.run(["ls", "non_existent_file"], stdout=subprocess.PIPE)
if result.returncode != 0:
print("Command failed with error code:", result.returncode)
result = subprocess.run("ls *.txt", shell=True, stdout=subprocess.PIPE)
print(result.stdout.decode())
name = "Alice"
result = subprocess.run(["./hello.sh", name], stdout=subprocess.PIPE)
print(result.stdout.decode())
result = subprocess.run(["ls", "non_existent_file"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if result.returncode != 0:
print("Error:", result.stderr.decode())
result = subprocess.run(["ls"], cwd="/path/to/directory", stdout=subprocess.PIPE)
print(result.stdout.decode())
這些技巧可以幫助你更方便地執行系統命令或腳本,并處理相應的輸出和錯誤信息。請注意安全性,盡量避免直接在腳本中執行用戶輸入的命令。