在linux操作系統(tǒng)中,如何利用Python調(diào)用shell命令
首先介紹一下python命令
利用python調(diào)用shell的方法很多
1】os.system(command)
結(jié)果: 執(zhí)行的運(yùn)行command命令,加上command命令執(zhí)行完畢后的退出狀態(tài)。
使用:
import os
os.system(command)
例如 os.system('ls') 和os.system("ls") 執(zhí)行效果一樣
>>> 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進(jìn)程之間的管道。這個函數(shù)的返回值是一個文件對象,可以讀或者寫(由mode決定,mode默認(rèn)是’r')。如果mode為’r',可以使用此函數(shù)的返回值調(diào)用read()來獲取command命令的執(zhí)行結(jié)果。
>>> 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命令打印出來的沒有規(guī)律,利用print命令打印出來的很整齊
4】subporcess 這個模塊 其實(shí)這個方法比較簡單 ,聽說是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 這兩個文件
第一種:假設(shè)存在shell腳本,你想用自己寫的python來運(yùn)行這個shell腳本,通過Python來輸出信息,可以這樣
#!/usr/bin/python
import commands
import subprocess
commands.getoutput('chmod +x test.sh')
output = commands.getoutput('./test.sh')
print output
第二種:存在shell腳本,通過Python來運(yùn)行shell腳本,利用shell腳本里面的輸出信息打印出來,不通過python打印
#!/usr/bin/python
import subprocess
subprocess.call("chmod +x test.sh",shell=True)
subprocess.call("./test.sh",shell=True)
---------------------
作者:嵌入式學(xué)吒
來源:CSDN
原文:https://blog.csdn.net/rong11417/article/details/87613342
版權(quán)聲明:本文為博主原創(chuàng)文章,轉(zhuǎn)載請附上博文鏈接!