免费视频淫片aa毛片_日韩高清在线亚洲专区vr_日韩大片免费观看视频播放_亚洲欧美国产精品完整版

打開APP
userphoto
未登錄

開通VIP,暢享免費(fèi)電子書等14項(xiàng)超值服

開通VIP
在linux操作系統(tǒng)中,如何利用Python調(diào)用shell命令

在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)載請附上博文鏈接!

本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊舉報(bào)
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
用shell同時(shí)啟動多個python腳本
如何利用python調(diào)用shell腳本
python中執(zhí)行命令的3種方法小結(jié)
Python執(zhí)行系統(tǒng)命令的方法
用 Python 替代 Bash 腳本
如何高效地向Redis插入大量的數(shù)據(jù)
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長圖 關(guān)注 下載文章
綁定賬號成功
后續(xù)可登錄賬號暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服