[Python] to call shell script in python, and operating parameters passed -02python shell instance

First, create two shell scripts, test.

  • test_shell_no_para.sh runtime, the parameters need to pass
  • test_shell_2_para.sh run, two parameters need to pass

   test_shell_no_para.sh reads as follows:

   test_shell_2_para.sh follows

Note that use a string variable containing double quotes enclose

   Directly on the results of the command line to run test_shell_2_para.sh as follows: 

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

 

Calling shell by python, the actual operation:

  • Python script by calling test_shell_no_para.sh
In [29]: os.system('./test_shell_no_para.sh')                                   
hello world
Out[29]: 512
  •  call test_shell_2_para.sh python script, passing two arguments, arg1 and 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 曹操 刘备 

 

 

Guess you like

Origin www.cnblogs.com/kaerxifa/p/11976025.html