>> import os >>> os.system( ls ) ..."/>
溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python和shell的結(jié)合與應(yīng)用

發(fā)布時間:2020-07-07 21:13:47 來源:網(wǎng)絡(luò) 閱讀:325 作者:luojun666 欄目:系統(tǒng)運維

函數(shù)模塊

system()
  • 其中最后一個0是這個命令的返回值,為0表示命令執(zhí)行成功。使用system無法將執(zhí)行的結(jié)果保存起來。
    例子:
    >>> import os
    >>> os.system('ls')
    blog.tar     djangoblog.log  managerblog.sh  test.txt
    data         ENV         nginx-1.15.11   wget-log
    0
    popen()

    提示:python3已結(jié)廢棄
    例子:

    >>> import os
    >>> os.popen('ls')
    <os._wrap_close object at 0x7f0acd548b00>
    >>> os.popen('ls').read()
    'blog.tar\ndata\ndb.sql\ndead.letter\nDjangoBlog\ndjangoblog.log\nENV\nfile1\nget-pip.py\nindex.html\nmanagerblog.sh\nnginx-1.15.11\nPython-3.5.2\nstartDjangoBlog.sh\nstart_uwsgi.ini\ntest.txt\nwget-log\nzrlog-2.1.3-b5f0d63-release.war?attname=ROOT.war\n'
    >>> os.popen('ls').read().split('\n')
    ['blog.tar', 'data', 'db.sql', 'dead.letter', 'DjangoBlog', 'djangoblog.log', 'ENV', 'file1', 'get-pip.py', 'index.html', 'managerblog.sh', 'nginx-1.15.11', 'Python-3.5.2', 'startDjangoBlog.sh', 'start_uwsgi.ini', 'test.txt', 'wget-log', 'zrlog-2.1.3-b5f0d63-release.war?attname=ROOT.war', '']

    獲取命令執(zhí)行的結(jié)果,但是沒有命令的執(zhí)行狀態(tài),這樣可以將獲取的結(jié)果保存起來放到list中。

subprocess
  • 可以很方便的取得命令的輸出(包括標準和錯誤輸出)和執(zhí)行狀態(tài)位。
  • commands.getoutput('ls')這個方法只返回執(zhí)行結(jié)果result不返回狀態(tài)。
    提示:subprocess模塊已經(jīng)取代了commands
    例子:
    1、getstatusoutput
    >>> import subprocess
    >>> status,result=subprocess.getstatusoutput('ls')
    >>> status
    0
    >>> result
    'blog.tar\ndata\ndb.sql\ndead.letter\nDjangoBlog\ndjangoblog.log\nENV\nfile1\nget-pip.py\nindex.html\nmanagerblog.sh\nnginx-1.15.11\nPython-3.5.2\nstartDjangoBlog.sh\nstart_uwsgi.ini\ntest.txt\nwget-log\nzrlog-2.1.3-b5f0d63-release.war?attname=ROOT.war'
    >>> result.split('\n')
    ['blog.tar', 'data', 'db.sql', 'dead.letter', 'DjangoBlog', 'djangoblog.log', 'ENV', 'file1', 'get-pip.py', 'index.html', 'managerblog.sh', 'nginx-1.15.11', 'Python-3.5.2', 'startDjangoBlog.sh', 'start_uwsgi.ini', 'test.txt', 'wget-log', 'zrlog-2.1.3-b5f0d63-release.war?attname=ROOT.war']

    2、getoutput

    >>> print(subprocess.getoutput('ls').split('\n') )
    ['blog.tar', 'data', 'db.sql', 'dead.letter', 'DjangoBlog', 'djangoblog.log', 'ENV', 'file1', 'get-pip.py', 'index.html', 'managerblog.sh', 'nginx-1.15.11', 'Python-3.5.2', 'startDjangoBlog.sh', 'start_uwsgi.ini', 'test.txt', 'wget-log', 'zrlog-2.1.3-b5f0d63-release.war?attname=ROOT.war']

    3、call
    執(zhí)行命令,返回狀態(tài)碼(命令正常執(zhí)行返回0,報錯則返回1)

    >>> subprocess.call('ls')
    blog.tar     djangoblog.log  managerblog.sh  test.txt
    data         ENV         nginx-1.15.11   wget-log
    db.sql       file1       Python-3.5.2    zrlog-2.1.3-b5f0d63-release.war?attname=ROOT.war
    dead.letter  get-pip.py      startDjangoBlog.sh
    DjangoBlog   index.html      start_uwsgi.ini
    0

4、check_call
執(zhí)行命令,如果執(zhí)行成功則返回狀態(tài)碼0,否則拋異常

>>> subprocess.check_call('ls')
blog.tar     djangoblog.log  managerblog.sh  test.txt
data         ENV         nginx-1.15.11   wget-log
db.sql       file1       Python-3.5.2    zrlog-2.1.3-b5f0d63-release.war?attname=ROOT.war
dead.letter  get-pip.py      startDjangoBlog.sh
DjangoBlog   index.html      start_uwsgi.ini
0
>>> subprocess.check_call('ls luojun')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/python3/lib/python3.5/subprocess.py", line 576, in check_call
    retcode = call(*popenargs, **kwargs)
  File "/usr/local/python3/lib/python3.5/subprocess.py", line 557, in call
    with Popen(*popenargs, **kwargs) as p:
  File "/usr/local/python3/lib/python3.5/subprocess.py", line 947, in __init__
    restore_signals, start_new_session)
  File "/usr/local/python3/lib/python3.5/subprocess.py", line 1551, in _execute_child
    raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'ls luojun'

5、check_output
執(zhí)行命令,如果執(zhí)行成功則返回執(zhí)行結(jié)果,否則拋異常

>>> subprocess.check_output('ls')
b'blog.tar\ndata\ndb.sql\ndead.letter\nDjangoBlog\ndjangoblog.log\nENV\nfile1\nget-pip.py\nindex.html\nmanagerblog.sh\nnginx-1.15.11\nPython-3.5.2\nstartDjangoBlog.sh\nstart_uwsgi.ini\ntest.txt\nwget-log\nzrlog-2.1.3-b5f0d63-release.war?attname=ROOT.war\n'
>>> subprocess.check_output('ls luojun')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/python3/lib/python3.5/subprocess.py", line 626, in check_output
    **kwargs).stdout
  File "/usr/local/python3/lib/python3.5/subprocess.py", line 693, in run
    with Popen(*popenargs, **kwargs) as process:
  File "/usr/local/python3/lib/python3.5/subprocess.py", line 947, in __init__
    restore_signals, start_new_session)
  File "/usr/local/python3/lib/python3.5/subprocess.py", line 1551, in _execute_child
    raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'ls luojun'

6、subprocess.Popen(…)
用于執(zhí)行復(fù)雜的系統(tǒng)命令
參數(shù) 注釋

args shell命令,可以是字符串或者序列類型(如:list,元組)
bufsize 指定緩沖。0 無緩沖,1 行緩沖,其他 緩沖區(qū)大小,負值 系統(tǒng)緩沖
stdin, stdout, stderr 分別表示程序的標準輸入、輸出、錯誤句柄
preexec_fn 只在Unix平臺下有效,用于指定一個可執(zhí)行對象(callable object),它將在子進程運行之前被調(diào)用
close_sfs 在windows平臺下,如果close_fds被設(shè)置為True,則新創(chuàng)建的子進程將不會繼承父進程的輸入、輸出、錯誤管道。所以不能將close_fds設(shè)置為True同時重定向子進程的標準輸入、輸出與錯誤(stdin, stdout, stderr)。
shell 同上
cwd 用于設(shè)置子進程的當(dāng)前目錄
env 用于指定子進程的環(huán)境變量。如果env = None,子進程的環(huán)境變量將從父進程中繼承。
universal_newlines 不同系統(tǒng)的換行符不同,True -> 同意使用 \n
startupinfo 只在windows下有效,將被傳遞給底層的CreateProcess()函數(shù),用于設(shè)置子進程的一些屬性,如:主窗口的外觀,進程的優(yōu)先級等等
createionflags 同上

在python中調(diào)用shell腳本

  • 編寫一個腳本,傳入兩個參數(shù)
    [root@VM_0_2_centos test]# vim test.sh
    [root@VM_0_2_centos test]# cat test.sh
    #!/bin/bash
    echo "this is my test shell ${1} ${2}"
    exit 0
    [root@VM_0_2_centos test]# chmod +x test.sh
    [root@VM_0_2_centos test]# /test/test.sh jluo jluocc.cn
    this is my test shell jluo jluocc.cn
  • 在python腳本中調(diào)用shell腳本,并傳入?yún)?shù),注意參數(shù)前后要有空格
[root@VM_0_2_centos test]# vim mytest.py
[root@VM_0_2_centos test]# cat mytest.py 
#! /usr/bin/env python3
import os
import sys

if(len(sys.argv)<3):
    print("please input two arguments")
    sys.exit(1)
arg0 = sys.argv[1]
arg1 = sys.argv[2]
print('=====file name *.py全路徑=====')
print(sys.argv[0])
print('=====腳本執(zhí)行結(jié)果如下=====')
os.system('/test/test.sh '+arg0+' '+arg1)

[root@VM_0_2_centos test]# python3 mytest.py jluo jluocc.cn
=====file name *.py全路徑=====
mytest.py
=====腳本執(zhí)行結(jié)果如下=====
this is my test shell jluo jluocc.cn
[root@VM_0_2_centos test]# python3 /test/mytest.py jluo jluocc.cn
=====file name *.py全路徑=====
/test/mytest.py
=====腳本執(zhí)行結(jié)果如下=====
this is my test shell jluo jluocc.cn

結(jié)束語:
更多精彩內(nèi)容持續(xù)更新中,關(guān)注微信公眾號,有你更精彩。
python和shell的結(jié)合與應(yīng)用

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI