python调用shell该引用到什么类_python调用shell 三种方法和 解决权限问题

一) 调用并且解决权限问题

python脚本: python.sh

#!/usr/bin/python

# -*- coding: utf-8 -*-

import os

a=os.system('ls')

print('权限',a);

a=os.system('chmod 777 * test1.sh')

print('权限2',a);

# file = os.popen("./test1.sh")

# file.read()

a=os.system('sh test1.sh')

print('结果',a)

shell 脚本test1.sh

#!/bin/bash

echo "Hell world!"

exit 2

执行 python 脚本 他们放在一个目录下面 输出结果:

权限 0

权限2 0

Hell world!

结果 512

赋予权限问题解决:(这行代码解决python 中引用权限的问题)

a=os.system('chmod 777 * test1.sh')

二) python 调用shell 的多种方案 和差别

2.1) os.system

os.system

os.system(‘cat /proc/cpuinfo’)

但是发现页面上打印的命令执行结果 0 或者 1,当然不满足需求了。

> 总结: 可以执行就是把shell 的命令 放到 os.system中 , 无法获取返回值 和打印的值

### 2.2) os.popen()

尝试第二种方案 os.popen()

output = os.popen(‘cat /proc/cpuinfo’)

print output.read()

通过os.popen()返回的是 file read 的对象,对其进行读取 read() 操作可以看到执行的输出。但是无法读取程序执行的返回值。

os.popen()

尝试第二种方案 os.popen()

output = os.popen(‘cat /proc/cpuinfo’)

print output.read()

通过os.popen()返回的是 file read 的对象,对其进行读取 read() 操作可以看到执行的输出。但是无法读取程序执行的返回值。

总结: 对其进行读取 read() 操作可以看到执行的输出。但是无法读取程序执行的返回值。

### 2.3 commands.getstatusoutput()

(status, output) = commands.getstatusoutput('cat /proc/cpuinfo')

print status, output

Python Document 中给的一个例子,

>> import commands

>>> commands.getstatusoutput('ls /bin/ls')

(0, '/bin/ls')

>>> commands.getstatusoutput('cat /bin/junk')

(256, 'cat: /bin/junk: No such file or directory')

>>> commands.getstatusoutput('/bin/junk')

(256, 'sh: /bin/junk: not found')

>>> commands.getoutput('ls /bin/ls')

'/bin/ls'

>>> commands.getstatus('/bin/ls')

'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'

python commands 模块在 python3.x 被 subprocess 取代

总结: 一个方法就可以获得到返回值和输出,非常好用。 但是不兼容python2 和python3 同时兼容

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值