python -- 调用 shell 命令


一个人想像自己不懂得的事很容易浪漫 ——沉默的大多数


前言

有时候写 python 脚本的时候,直接使用 shell 命令的话会事半功倍,不需要自己再另外写函数来实现

参考:https://www.jianshu.com/p/5d999a668e79


os 模块

system 方法

system方法会创建子进程运行外部程序,方法除了返回外部程序的运行结果,还有结束的状态码 1 或 0

>>> import os
>>> os.system("echo 8")
8
0

popen 方法

popen方不仅仅返回结果,还返回一个类文件对象,通过调用该对象的read()或readlines()方法可以读取输出内容

>>> import os
>>> output = os.popen("dir").read()
>>> output
.....
>>>
>>> outputs = os.popen("dir").readlines()
>>> for line in outputs:
...     print(line)

commands 模块

getoutput 方法

这种方法同popend的区别在于popen返回的是一个类文件对象,而本方法将外部程序的输出结果当作字符串返回

# 返回(status, output)
commands.getstatusoutput(command)      
# 只返回输出结果
commands.getoutput(command)                  
# 调用了getoutput,不建议使用此方法
commands.getstatus(file)

subprocess 模块

subprocess 允许你去创建一个新的进程让其执行另外的程序,并与它进行通信,获取标准的输入、标准输出、标准错误以及返回码等

>>> import subprocess
>>> subprocess.call("dir", shell=True)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值