首页 技术 正文
技术 2022年11月17日
0 收藏 668 点赞 4,706 浏览 1106 个字

首先创建2个shell脚本文件,测试用.

  • test_shell_no_para.sh 运行时,不需要传递参数
  • test_shell_2_para.sh 运行时,需要传递2个参数

[Python]在python中调用shell脚本,并传入参数-02python操作shell实例

   test_shell_no_para.sh 内容如下:

[Python]在python中调用shell脚本,并传入参数-02python操作shell实例

   test_shell_2_para.sh内容如下

注意含有变量的字符串要用 双引号 括起来

[Python]在python中调用shell脚本,并传入参数-02python操作shell实例

  直接在命令行运行 test_shell_2_para.sh 执行结果如下:

wangju@wangju-HP--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 []: os.system('./test_shell_no_para.sh')
hello world
Out[]:
  • python 调用test_shell_2_para.sh脚本,并传入2个参数 arg1和arg2
In []: arg1='pyarg1'                                                          In []: arg2='pyarg2' In []: os.system('./test_shell_2_para.sh '+arg1+' '+arg2)
hello world pyarg1 pyarg2
Out[]:

注意:参数前后要有空格

如果参数前后没有空格会报下面的错:

命令行会将参数也视为脚本名字的一部分

[Python]在python中调用shell脚本,并传入参数-02python操作shell实例

  • 在shell脚本中调用shell脚本,并传入参数(重点掌握)

  先创建1个python脚本,内容如下:

import os
import sysif 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--G4:~$ python3 pp.py
Please Input Two Arguments
wangju@wangju-HP--G4:~$ python3 pp.py 曹操 刘备
hello world 曹操 刘备
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,105
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,582
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,429
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,200
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,836
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,919