引言
在日常的開發和運維過程中,我們經常需要執行一些命令行操作。Shell命令是Linux/Unix操作系統中非常常見的一種命令行操作方式。Python作為一種腳本編程語言,也提供了豐富的執行Shell命令的方式。
Python shell清屏命令
Python自帶了清空輸出的功能:
import os
os.system('cls' if os.name == 'nt' else 'clear')
Python遠程調用Shell命令
Python的paramiko模塊可以用來連接ssh,並執行遠程命令。
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='remote_host', port=22, username='user', password='passwd')
stdin, stdout, stderr = ssh.exec_command('ls /')
print(stdout.readlines())
ssh.close()
Python調用adb shell命令
如果你經常使用Android手機,那麼你可能知道Android Debug Bridge(adb),它是一個用於與Android設備通信的命令行工具。Python提供了一個名為adb
的模塊,可以讓我們在Python中執行adb命令。
import adb
from adb.client import Client as AdbClient
client = AdbClient(host="127.0.0.1", port=5037)
devices = client.devices()
device = devices[0]
output = device.shell("ls")
print(output)
Python shell命令
最直接也是最基本的方式就是使用Python的os.system()
來執行Shell命令。
import os
os.system('ls')
Python並行執行Shell命令
如果要並行執行多個Shell命令,可以使用Python的subprocess.Popen()
創建子進程。
import subprocess
processes = []
for cmd in ['ls', 'ps', 'df']:
processes.append(subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE))
for process in processes:
process.wait()
print(process.stdout.read())
Python批量執行Shell命令
如果要批量執行多個Shell命令,可以使用Python的subprocess.call()
來執行每個命令。
import subprocess
cmds = ['ls', 'ps', 'df']
for cmd in cmds:
subprocess.call(cmd, shell=True)
Python如何執行Shell命令
Python提供了多種方式來執行Shell命令,從使用os.system()
到subprocess.Popen()
,每種方式都有不同的適用場景和特點。我們可以根據具體的需求選擇合適的方式來執行Shell命令。
Python調用Shell命令返回值處理
Python調用Shell命令後,可以通過subprocess.Popen().communicate()
方法獲取Shell命令的輸出和返回值。
import subprocess
cmd = 'ls'
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
if p.returncode == 0:
print('command success:', stdout)
else:
print('command failed:', stderr)
結語
本文介紹了多種使用Python執行Shell命令的方式,包括清屏、遠程調用、adb命令、基本執行、並行執行、批量執行、返回值處理等內容。希望對你在日常的開發和運維工作中有所幫助。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/241295.html