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 取代
https://blog.csdn.net/ronnyjiang/article/details/53333538
总结: 一个方法就可以获得到返回值和输出,非常好用。 但是不兼容python2 和python3 同时兼容