python和shell的結合與應用

函數模塊

system()

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

    popen()

    提示:python3已結廢棄
    例子:

    >>> 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', '']

    獲取命令執行的結果,但是沒有命令的執行狀態,這樣可以將獲取的結果保存起來放到list中。

subprocess

  • 可以很方便的取得命令的輸出(包括標準和錯誤輸出)和執行狀態位。
  • commands.getoutput('ls')這個方法只返回執行結果result不返回狀態。
    提示:subprocess模塊已經取代了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
    執行命令,返回狀態碼(命令正常執行返回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
執行命令,如果執行成功則返回狀態碼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
執行命令,如果執行成功則返回執行結果,否則拋異常

>>> 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(…)
用於執行復雜的系統命令
參數 註釋

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

在python中調用shell腳本

  • 編寫一個腳本,傳入兩個參數
    [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腳本中調用shell腳本,並傳入參數,注意參數前後要有空格
[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('=====腳本執行結果如下=====')
os.system('/test/test.sh '+arg0+' '+arg1)

[root@VM_0_2_centos test]# python3 mytest.py jluo jluocc.cn
=====file name *.py全路徑=====
mytest.py
=====腳本執行結果如下=====
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
=====腳本執行結果如下=====
this is my test shell jluo jluocc.cn

結束語:
更多精彩內容持續更新中,關注微信公衆號,有你更精彩。
python和shell的結合與應用

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章