一、python 调用shell知识体系
python一门胶水语言,能够调用各种语言缩写的程序,当前wiki主要使用调用shell/linux命令:
几个关键注意点:
- 输入
字符串形式:cmd通过字符串格式输入,os、subprocess皆支持;特别注意参数传入,按照python的字符串要求传入即可(%s,str.format(),python3 f表达式)。
命令以列表形式传入:当前只有subprocess模块支持
- 执行linux结果
打印执行结果 :os模块默认打印;subprocess.Popen()实例不指定stdout,stderr时候。
返回执行结果状态 :os.system();subprocess.run(cmd).returncode,subprocess.call(cmd),subprocess.check_call(cmd),subprocess.getstatusoutput()[0]
返回执行结果,可以将结果赋值给变量 :os.popen().raeds();subprocess.Popen(cmd,stdout=subprocess.PIPE, stderr=subprocess.PIPE).run(),subprocess.check_output(),subprocess.getoutput(),subprocess.getstatusoutput()[1]
将执行结果打印到文件中:两种思路,一种是通过linux本身自带的重定向写入文件,另一种是使用subprocess指定stdout为本地文件即可
- 两个模块的对比:
返回结果:
os.system(cmd),打印结果,返回执行结果状态(0执行成功);
os.popen(cmd),打印结果,同时返回执行结果(一个打开的文件对象);
subprocess模块可以根据实际需求返回对应的结果。
使用场景:
os模块,常常用于简单的linux命令操作
subprocess模块,长用于shell等大型交付场景使用(个人建议直接使用该模块)
个人建议,无论简单,还是复杂的linux操作,直接使用subprocess模块
二、使用步骤
python源码示例:
# -*- coding:utf-8 -*-
import os, subprocess, time
#该文件测试python嗲用shell的四种方法
current_workspace = os.path.join(os.path.dirname(os.path.abspath(__file__)))
workspace='/mnt/e/00.WORKSPACE/00.Python_Develop/ToolsLibrarByPython'
'''
os.system() 调用的C库
def system(command: StrOrBytesPath) -> int: ... 返回整数,返回0则表示执行成功
# os.system(str) 方法:
# 1.可以执行linux命令,可以加参数
# 2.可以执行shell脚本,也可以加参数
# 3.特别的,重定向可以直接通过linux重定向进行,
# 但是这样重定向输出局限于当前linux执行的服务器,无法重定向到当前程序执行的目录
'''
def excute_shell_by_os_system():
# cmd -> str
status = os.system('ls')
print(status)
#cmd命令,+参数(python str 语法加参数)
status = os.system('find %s -name "*.py"|sort' %workspace) #python str 占位符号
print(status)
status = os.system('find {} -type f'.format(workspace)) #python str.format()
print(status)
status = os.system(f"find {
workspace} -type f") #python str f表达式
print(status)
#cmd 执行shell脚本
status = os.system('./shell_demo.sh')
print(status)
#cmd 执行带有参数的shell脚本
status = os.system('./shell_demo_with_param.sh %s' %workspace)
print(status)
#cmd 执行shell脚本, 重定向到某个文件
status = os.system