[Python]在python中調用shell腳本,並傳入參數-02python操作shell實例


首先創建2個shell腳本文件,測試用.

  • test_shell_no_para.sh 運行時,不需要傳遞參數
  • test_shell_2_para.sh 運行時,需要傳遞2個參數

   test_shell_no_para.sh 內容如下:

   test_shell_2_para.sh內容如下

注意含有變量的字符串要用 雙引號 括起來

   直接在命令行運行 test_shell_2_para.sh 執行結果如下: 

wangju@wangju-HP-348-G4:~$ sh test_shell_2_para.sh 'para1' 'para2' hello world para1 para2 

 腳本說明:

shell腳本參數化采用$0,$1,$2..等方式獲取腳本命令行傳入的參數,值得注意的是,$0獲取到的是腳本路徑以及腳本名,后面按順序獲取參數,當參數超過10個時(包括10個),需要使用${10},${11}....才能獲取到參數,但是一般很少會超過10個參數的情況。

shell腳本參數化的方式參照:shell中腳本參數傳遞的兩種方式

通過python調用shell,實際操作:

  • 通過python 調用test_shell_no_para.sh腳本
In [29]: os.system('./test_shell_no_para.sh') hello world Out[29]: 512
  •  python 調用test_shell_2_para.sh腳本,並傳入2個參數 arg1和arg2
In [31]: arg1='pyarg1' In [32]: arg2='pyarg2' In [35]: os.system('./test_shell_2_para.sh '+arg1+' '+arg2) hello world pyarg1 pyarg2 Out[35]: 0

注意:參數前后要有空格

如果參數前后沒有空格會報下面的錯:

命令行會將參數也視為腳本名字的一部分

  •   在shell腳本中調用shell腳本,並傳入參數(重點掌握)

  先創建1個python腳本,內容如下:

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] os.system('./test_shell_2_para.sh '+arg0+' '+arg1)

  執行python腳本,效果如下:

wangju@wangju-HP-348-G4:~$ python3 pp.py Please Input Two Arguments wangju@wangju-HP-348-G4:~$ python3 pp.py 曹操 劉備 hello world 曹操 劉備 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM