python调用shell脚本的两种方法

本文介绍了使用Python的os模块调用Shell脚本的两种方法:os.system()和os.popen()。os.system()用于执行命令并返回退出状态码,而os.popen()则返回命令的输出内容,适用于需要捕获输出的场景。

python调用shell脚本的两种方法
转载wendzU 发布于2018-04-07 14:33:28 阅读数 6096 收藏
展开

os.system()和os.popen()
1.python调用Shell脚本,有两种方法:os.system()和os.popen(),
前者返回值是脚本的退出状态码,后者的返回值是脚本执行过程中的输出内容。

help(os.system)
Help on built-in function system in module posix:
system(…)
system(command) -> exit_status
Execute the command (a string) in a subshell.

help(os.popen)
Help on built-in function popen in module posix:
popen(…)
popen(command [, mode=‘r’ [, bufsize]]) -> pipe
Open a pipe to/from a command returning a file object.

假定有一个shell脚本test.sh:
song@ubuntu:~$ vi test.sh
song@ubuntu:~$ more test.sh
#!/bin/bash
echo ‘hello python!’
echo ‘hello world!’
exit 1
song@ubuntu:~$

2.1 os.system(command):该方法在调用完shell脚本后,返回一个16位的二进制数,
低位为杀死所调用脚本的信号号码,高位为脚本的退出状态码,
即脚本中exit 1的代码执行后,os.system函数返回值的高位数则是1,如果低位数是0的情况下,
则函数的返回值是0x0100,换算为十进制得到256。
要获得os.system的正确返回值,可以使用位移运算(将返回值右移8位)还原返回值:

import os
os.system("./test.sh")
hello python!
hello world!

n=os.system("./test.sh")
hello python!
hello world!

n
n>>8

2.2 os.popen(command):这种调用方式是通过管道的方式来实现,函数返回一个file对象,
里面的内容是脚本输出的内容(可简单理解为echo输出的内容),使用os.popen调用test.sh的情况:

import os

os.popen("./test.sh")
<open file ‘./test.sh’, mode ‘r’ at 0x7f6cbbbee4b0>

f=os.popen("./test.sh")
f
<open file ‘./test.sh’, mode ‘r’ at 0x7f6cbbbee540>

f.readlines()
[‘hello python!\n’, ‘hello world!\n’]

3》像调用”ls”这样的shell命令,应该使用popen的方法来获得内容,对比如下:

import os
os.system(“ls”) #直接看到运行结果
Desktop Downloads Music Public Templates Videos
Documents examples.desktop Pictures systemExit.py test.sh
0 #返回值为0,表示命令执行成功

n=os.system(‘ls’)
Desktop Downloads Music Public Templates Videos
Documents examples.desktop Pictures systemExit.py test.sh

n
0

n>>8 #将返回值右移8位,得到正确的返回值
0

f=os.popen(‘ls’) #返回一个file对象,可以对这个文件对象进行相关的操作
f
<open file ‘ls’, mode ‘r’ at 0x7f5303d124b0>

f.readlines()
[‘Desktop\n’, ‘Documents\n’, ‘Downloads\n’, ‘examples.desktop\n’, ‘Music\n’, ‘Pictures\n’, ‘Public\n’, ‘systemExit.py\n’, ‘Templates\n’, ‘test.sh\n’, ‘Videos\n’]

总结:os.popen()可以实现一个“管道”,从这个命令获取的值可以继续被使用。因为它返回一个文件对象,可以对这个文件对象进行相关的操作。
但是如果要直接看到运行结果的话,那就应该使用os.system,用了以后,立竿见影!

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) ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值