Python经常被称作“胶水语言”,因为它能够轻易地操作其他程序,轻易地包装使用其他语言编写的库,也当然可以用Python调用Shell命令。

用Python调用Shell命令有如下几种方式:

第一种:os.system

os.system("The command you want").

这个调用相当直接,且是同步进行的,程序需要阻塞并等待返回。返回值是依赖于系统的,直接返回系统的调用返回值,所以windows和linux是不一样的。

第二种:os.popen

os.popen(command[,mode[,bufsize]])

先给大家看个例子

可以看出,popen方法通过p.read()获取终端输出,而且popen需要关闭close().当执行成功时,close()不返回任何值,失败时,close()返回系统返回值. 可见它获取返回值的方式和os.system不同。

第三种,使用commands ( python3失效)

根据你需要的不同,commands模块有三个方法可供选择。getstatusoutput, getoutput, getstatus。

commands.getstatusoutput(cmd) 返回(status, output).
commands.getoutput(cmd) 只返回输出结果
commands.getstatus(file) 返回ls -ld file的执行结果字符串,调用了getoutput,不建议使用此方法

但是,如上三个方法都不是Python推荐的方法,而且在Python3中其中两个已经消失。

第四种,subprocess《Python文档中目前全力推荐》

subprocess使用起来同样简单:

直接调用命令,返回值即是系统返回。shell=True表示命令最终在shell中运行。Python文档中出于安全考虑,不建议使用shell=True。建议使用Python库来代替shell命令,或使用pipe的一些功能做一些转义。官方的出发点是好的,不过真心麻烦了很多, so....

但是,我使用subprocess失败了

>>> import subprocess
>>> subprocess.call("cat %s |grep %s > %s " % ("/home/www/running/os-app-api/nohup.out","2019-10-28","~/nohup-2019-10-28.out"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python3.6/subprocess.py", line 287, in call
with Popen(*popenargs, **kwargs) as p:
File "/usr/lib64/python3.6/subprocess.py", line 729, in __init__
restore_signals, start_new_session)
File "/usr/lib64/python3.6/subprocess.py", line 1364, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'cat /home/www/running/os-app-api/nohup.out |grep 2019-10-28 > ~/nohup-2019-10-28.out ': 'cat /home/www/running/os-app-api/nohup.out |grep 2019-10-28 > ~/nohup-2019-10-28.out '

但是。。我可以直接运行在shell里面:

同样的 我用os.system 去运行,也确实产生了。。好奇

>>> import os
>>> os.system("cat %s |grep %s > %s " % ("/home/www/running/os-app-api/nohup.out","2019-10-28","~/nohup-2019-10-28.out"))
256

源码研究:

这里面最为重要的几个参数是:.
args:要执行的shell命令,或者是命令的列表;
bufsize:缓冲区大小;。
stdin、stdout、stderr:表示程序的标准输入、标准输出以及错误输出。
shell:是否直接执行命令,如果设置为True就表示可以直接执行;
cwd:当前的工作目录;
env:子进程环境变量;

案例:

subprocess模块里面还有一项功能比较强大的支持在于可以直接使用标准输入、标准输出和错误输出进行进程的数据通讯操作。

    例如,在Python安装完成之后都会存在有交互式的编程环境,那么本次将通过程序调用交互式编程环境。

直接操作python命令行,在python命令行中直接输入程序。

def main():
subp_popen=subprocess.Popen("python.exe",stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE) subp_popen.stdin.write("print('subp_popen.stdin.write1')\n".encode())
subp_popen.stdin.write("print('subp_popen.stdin.write2')\n".encode())
subp_popen.stdin.write(("print('subp_popen.stdin.write3'+1)").encode())
subp_popen.stdin.close() cmd_out=subp_popen.stdout.read()
subp_popen.stdout.close()
print(cmd_out.decode()) cmd_err=subp_popen.stderr.read()
subp_popen.stderr.close()
print(cmd_err) if __name__ == '__main__': main()

结果:

用Python调用Shell命令的更多相关文章

  1. python 调用 shell 命令方法

    python调用shell命令方法 1.os.system(cmd) 缺点:不能获取返回值 2.os.popen(cmd) 要得到命令的输出内容,只需再调用下read()或readlines()等   ...

  2. python 调用shell命令三种方法

    #!/usr/bin/python是告诉操作系统执行这个脚本的时候,调用/usr/bin下的python解释器: #!/usr/bin/env python这种用法是为了防止操作系统用户没有将pyth ...

  3. python 调用 shell 命令

    记录 python 调用 shell 命令的方法 加载 os 模块, 使用 os 类 import os; os.system("ls /");

  4. python 调用shell命令的方法

    在python程序中调用shell命令,是件很酷且常用的事情…… 1. os.system(command) 此函数会启动子进程,在子进程中执行command,并返回command命令执行完毕后的退出 ...

  5. python调用shell命令

    1.subprocess介绍 官方推荐 subprocess模块,os.system(command) 这个废弃了 亲测 os.system 使用sed需要进行字符转义,非常麻烦 python3 su ...

  6. Python 调用 Shell命令

    python程序中调用shell命令,是件很酷且常用的事情今天来总结一下   1.使用os模块 的  system         此函数会启动子进程,在子进程中执行command,并返回comman ...

  7. Python调用shell命令常用方法

    Python调用shell指令 方法一.使用os模块的system方法:os.system(cmd),其返回值是shell指令运行后返回的状态码,int类型,0表示shell指令成功执行,256表示未 ...

  8. (转载)python调用shell命令之os 、commands、subprocess

    linux系统下进入python交互式环境: 一.os 模块 1.1.os模块的exec方法簇: python交互界面中: In [1]: import os In [2]: os.exec os.e ...

  9. python调用shell命令之三慷慨法

    preface: 忙于近期的任务,须要用到libsvm的一些命令.如在终端执行java svm_train train_file model_file. pythonsubset.py file tr ...

随机推荐

  1. vlan端口类型

    交换机三种链路类型:access.trunk.hybrid. access类型只属于一个VLAN,一般用于连接计算机端口. trunk类型可以允许多个vlan通过,可以接收和发送多个vlan的报文,一 ...

  2. 处理idea加载不到Spring的xml或者properties配置文件

    在pom文件的 标签钱添加以下代码 <!--防止ieda加载不到xml或者properties文件开始--> <resources> <resource> < ...

  3. 【LOJ】#3087. 「GXOI / GZOI2019」旅行者

    LOJ#3087. 「GXOI / GZOI2019」旅行者 正着求一遍dij,反着求一遍,然后枚举每条边,从u到v,如果到u最近的点和v能到的最近的点不同,那么可以更新答案 没了 #include ...

  4. windows下将多个文件合并成一个文件,将ts文件变成MP3格式

    ①:先把全部的ts文件下载下来放到指定文件夹,这里我是放在桌面的ls里 ②:从cmd进去找到桌面的路径,也可以像我这样直接在桌面的路径上敲cmd进入: ③:直接合并使用命令“copy /b ls\*. ...

  5. PATB1040/A1093 有几个PAT

    题目描述 The string APPAPT contains two PAT's as substrings. The first one is formed by the 2nd, the 4th ...

  6. P1541 乌龟棋(动态规划)

    (点击此处查看原题) 题意 此处有n个位置,记为1~n,每个位置上都对应一个权值,乌龟从编号为1的位置出发,利用m张爬行卡片到达位置n,爬行卡牌有四种,分别可以让乌龟移动1,2,3,4步,并保证将m张 ...

  7. VC/MFC 进程间通信方法总结

    摘   要   随着人们对应用程序的要求越来越高,单进程应用在许多场合已不能满足人们的要求.编写多进程 / 多线程程序成为现代程序设计的一个重要特点,在多进程程序设计中,进程间的通信是不可避免的. M ...

  8. logid让你的请求完整可追溯

    今天是在博客园开园的第一天 一时间其实并不能想起来到底该写什么文章,其实想写的东西挺多 今天就以logid这个主题开始吧,网上写这个的文章似乎不多,但是的确是在实际生产中相当重要的一个能力,也是容易被 ...

  9. JS实现点击查看密码功能,再次点击隐藏密码!

    <table border='1'> <tr> <td>aaaa</td> <td onclick="myFunction(this.i ...

  10. 怎样理解 Vue 组件中 data 必须为函数 ?

    组件意在 复用 , 若为 对象, 则会相互干扰. 且 Vue 不允许此事发生, 规定必须为函数, 否则报错. 原理如下 对象 // 模拟创建组件 var Component= function() { ...