linux中如何利用Python来调用shell命令及其运行shell脚本

在linux操作系统中,如何利用Python调用shell命令

首先介绍一下python命令

利用python调用shell的方法很多

1】os.system(command)

结果:  执行的运行command命令,加上command命令执行完毕后的退出状态。

使用:

import os

os.system(command)

例如  os.system('ls') 和os.system("ls") 执行效果一样

>>> import os 
>>> os.system('ls')
py_shell.py  test.py  test.sh
0
>>> os.system("ls")
py_shell.py  test.py  test.sh
0

 2】os.popen(command,mode)

打开一个与command进程之间的管道。这个函数的返回值是一个文件对象,可以读或者写(由mode决定,mode默认是’r')。如果mode为’r',可以使用此函数的返回值调用read()来获取command命令的执行结果。

>>> import os
>>> p = os.popen('ls')
>>> p.read()
'py_shell.py\ntest.py\ntest.sh\n'
>>> p.close()

3】 commands模块,可以使用 getstatusoutput,getoutput,getstatus

>>> import commands
>>> commands.getstatusoutput('ls -l')
(0, '\xe6\x80\xbb\xe7\x94\xa8\xe9\x87\x8f 12\n-rwxrwxr-x 1 tarena tarena 541  2\xe6\x9c\x88 18 12:55 py_shell.py\n-rwxrwxr-x 1 tarena tarena  37 11\xe6\x9c\x88  6 15:04 test.py\n-rwxrwxr-x 1 tarena tarena  33  2\xe6\x9c\x88 18 12:45 test.sh')

>>> (status,output) = commands.getstatusoutput('ls -l')
>>> print status,output
0 总用量 12
-rwxrwxr-x 1 tarena tarena 541  2月 18 12:55 py_shell.py
-rwxrwxr-x 1 tarena tarena  37 11月  6 15:04 test.py
-rwxrwxr-x 1 tarena tarena  33  2月 18 12:45 test.sh

可以看出不通过python的print命令打印出来的没有规律,利用print命令打印出来的很整齐 

4】subporcess 这个模块  其实这个方法比较简单 ,听说是python3极力推荐的

来看看怎么用

>>> import subprocess
>>> subprocess.call("ls -l",shell=True)
总用量 12
-rwxrwxr-x 1 tarena tarena 541  2月 18 12:55 py_shell.py
-rwxrwxr-x 1 tarena tarena  37 11月  6 15:04 test.py
-rwxrwxr-x 1 tarena tarena  33  2月 18 12:45 test.sh
0

别忘了引入模块   import  模块名 

来看下目录下文件

tarena@ubuntu:~/test/python$ pwd
/home/tarena/test/python
tarena@ubuntu:~/test/python$ ls
py_shell.py  test.py  test.sh

这里用到py_shell.py和test.sh 这两个文件

第一种:假设存在shell脚本,你想用自己写的python来运行这个shell脚本,通过Python来输出信息,可以这样

#!/usr/bin/python

import commands
import subprocess

commands.getoutput('chmod +x test.sh')
output = commands.getoutput('./test.sh')

print output

第二种:存在shell脚本,通过Python来运行shell脚本,利用shell脚本里面的输出信息打印出来,不通过python打印

#!/usr/bin/python
import subprocess

subprocess.call("chmod +x test.sh",shell=True)
subprocess.call("./test.sh",shell=True)

猜你喜欢

转载自blog.csdn.net/rong11417/article/details/87613342