python中执行shell命令

本文介绍了使用Python执行Shell命令的四种方法:os.system(), os.popen(), commands模块和subprocess模块,并详细解释了每种方法的特点及应用场景。
部署运行你感兴趣的模型镜像

原文出处:https://blog.51cto.com/zhou123/1312791
这里介绍一下python执行shell命令的四种方法:

1、os模块中的os.system()这个函数来执行shell命令

>>> os.system('ls')
anaconda-ks.cfg  install.log  install.log.syslog  send_sms_service.py  sms.py
0

注,这个方法得不到shell命令的输出。

2、popen()#这个方法能得到命令执行后的结果是一个字符串,要自行处理才能得到想要的信息。

>>> import os
>>> str = os.popen("ls").read()
>>> a = str.split("\n")
>>> for b in a:
        print b

这样得到的结果与第一个方法是一样的。

3、commands模块#可以很方便的取得命令的输出(包括标准和错误输出)和执行状态位

import commands
a,b = commands.getstatusoutput('ls')

a是退出状态
b是输出的结果。

>>> import commands
>>> a,b = commands.getstatusoutput('ls')
>>> print a
0
>>> print b
anaconda-ks.cfg
install.log
install.log.syslog

commands.getstatusoutput(cmd)返回(status,output)

commands.getoutput(cmd)只返回输出结果

commands.getstatus(file)返回ls -ld file 的执行结果字符串,调用了getoutput,不建议使用这个方法。

4、subprocess模块

使用subprocess模块可以创建新的进程,可以与新建进程的输入/输出/错误管道连通,并可以获得新建进程执行的返回状态。使用subprocess模块的目的是替代os.system()、os.popen*()、commands.*等旧的函数或模块。

import subprocess

1、subprocess.call(command, shell=True)

#会直接打印出结果。

2、subprocess.Popen(command, shell=True) 也可以是subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) 这样就可以输出结果了。

如果command不是一个可执行文件,shell=True是不可省略的。

shell=True意思是shell下执行command

这四种方法都可以执行shell命令。

您可能感兴趣的与本文相关的镜像

Python3.11

Python3.11

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

Python中调用shell脚本有多种方法,以下为你详细介绍: ### 使用`os.system` `os.system`函数可以直接在Python执行shell命令,若要调用shell脚本,只需将脚本路径作为命令传入即可。 ```python import os # 调用shell脚本 result = os.system("/path/to/your/script.sh") return_code = result >> 8 print(f"脚本执行返回码: {return_code}") ``` 此方法返回值是命令执行后的状态码,高位才是真正的返回码,需右移8位获取[^1]。 ### 使用`subprocess`模块 `subprocess`模块功能更强大,能灵活控制命令执行和输出。 #### `subprocess.run` ```python import subprocess try: # 调用shell脚本 result = subprocess.run(["/path/to/your/script.sh"], capture_output=True, text=True, check=True) print("脚本输出:") print(result.stdout) except subprocess.CalledProcessError as e: print(f"脚本执行出错,返回码: {e.returncode}") print("错误信息:") print(e.stderr) ``` `subprocess.run`会等待命令执行完毕,`capture_output=True`表示捕获脚本的标准输出和标准错误输出,`text=True`表示以文本形式返回输出,`check=True`表示若命令执行失败(返回非零状态码),则抛出`CalledProcessError`异常。 #### `subprocess.Popen` ```python import subprocess # 调用shell脚本 process = subprocess.Popen(["/path/to/your/script.sh"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) # 获取脚本输出 stdout, stderr = process.communicate() # 获取返回码 return_code = process.returncode print(f"脚本执行返回码: {return_code}") if return_code == 0: print("脚本输出:") print(stdout) else: print("错误信息:") print(stderr) ``` `subprocess.Popen`能以更底层的方式控制命令执行,可在命令执行过程中与其进行交互。 ### 使用`sh`模块 `sh`模块是一个方便的库,可让在Python中像调用函数一样调用shell命令。首先需安装`sh`模块: ```bash pip install sh ``` ```python import sh try: # 调用shell脚本 output = sh.bash("/path/to/your/script.sh") print("脚本输出:") print(output) except sh.ErrorReturnCode as e: print(f"脚本执行出错,返回码: {e.exit_code}") print("错误信息:") print(e.stderr) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值