python3调用linux/shell—【标准库:os模块&subprocess模块】

一、python 调用shell知识体系

python一门胶水语言,能够调用各种语言缩写的程序,当前wiki主要使用调用shell/linux命令:
在这里插入图片描述

几个关键注意点:

  1. 输入

字符串形式:cmd通过字符串格式输入,os、subprocess皆支持;特别注意参数传入,按照python的字符串要求传入即可(%s,str.format(),python3 f表达式)。
命令以列表形式传入:当前只有subprocess模块支持

  1. 执行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为本地文件即可

  1. 两个模块的对比:

返回结果:
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值