python调用shell脚本
1. 传入参数
- python文件
import os
import sys
if len(sys.argv) < 3
print("Please input two arguments")
sys.exit(1)
argv1 = "name"
argv2 = "age"
os.system('./test.sh '+arg1+' '+arg2) # 注意空格,sh后面有空格,参数之间也有空格;注意单引号,最后一个参数右侧无单引号
#命令行运行
python test.py
可以套用python传递参数,二次传递给shell脚本:
import os
import sys
if len(sys.argv) < 3
print("Please input two arguments")
sys.exit(1)
argv1 = sys.argv[1]
argv2 = sys.argv[2]
os.system('./test.sh '+arg1+' '+arg2)
#命令行运行
python test.py name age
- shell文件
#! /bin/bash
echo "a test of arguments from python to shell"
echo "argv[1] = " $1
echo "argv[2] = " $2
-
运行结果
ps:0为os.system()函数的返回值,0表示执行成功。
2. 获取shell脚本结果
- os.system()函数获取shell脚本的执行状态,int型,返回值为0时执行成功,返回值为256时执行失败。
import os
val = os.system('bash test.sh')
print(val)
- os.popen()函数以文件形式获取shell脚本执行的结果,可以使用readlines()读取结果
import os
data = os.popen('bash test.sh')
for item in data.readlines():
print(item)
网友评论