首页 > 系统相关 >python之执行shell命令

python之执行shell命令

时间:2022-12-10 05:11:05浏览次数:38  
标签:输出 shell python subprocess 命令 ls output

python 执行shell命令,且执行完后将shell端的输出返回

subprocess

import subprocess

# 要执行的命令
command = "ls -l"

# 执行命令,并获取输出
output = subprocess.run(command, shell=True, stdout=subprocess.PIPE)

# 获取输出并解码
output = output.stdout.decode("utf-8")

# 输出结果
print(output)

​ 在这段代码中,我们使用 subprocess.run() 方法执行了 ls -l 命令,并将结果保存在 output 变量中。然后,我们调用了 stdout.decode() 方法将输出解码为字符串,并打印结果。
注意,在调用 subprocess.run() 时,我们传入了两个参数:shell=True 和 stdout=subprocess.PIPE。shell=True 表示要使用 shell 来执行命令,而 stdout=subprocess.PIPE 则表示将命令的标准输出保存在 output.stdout 中。

os.system()

import os

# 要执行的命令
command = "ls -l"

# 执行命令
output = os.system(command)

# 输出结果
print(output)

​ os.system() 方法执行了 ls -l 命令,并将结果保存在 output 变量中。然后,我们打印了 output 的值。
虽然使用 os.system() 方法可以执行 shell 命令,但它没有 subprocess.run() 方法那么强大。例如,os.system() 方法无法将命令的标准输出保存在变量中,因此无法对输出进行进一步的处理。
因此,如果您需要对命令的输出进行进一步的处理,建议使用 subprocess 模块。如果只需要执行命令,则可以使用 os.system() 方法。

sh

# 安装sh库
!pip install sh

from sh import ls

# 执行ls -l命令
output = ls("-l")

# 输出结果
print(output)

pexpect

# 安装pexpect库
!pip install pexpect

import pexpect

# 要执行的命令
command = "ls -l"

# 执行命令
output = pexpect.run(command)

# 输出结果
print(output)

​ 如果要从性能的角度考虑,推荐使用 subprocess 模块来执行 shell 命令。相比于其他方法,subprocess 模块能够更快地执行命令,并且可以将命令的标准输出保存在变量中,方便进一步的处理。

标签:输出,shell,python,subprocess,命令,ls,output
From: https://www.cnblogs.com/nwnusun/p/16970717.html

相关文章