博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Run Shell Commands in Python
阅读量:5163 次
发布时间:2019-06-13

本文共 2946 字,大约阅读时间需要 9 分钟。

subprocess.call

This is the recommended way to run shell commands in Python compared with old-fashioned os module. This is a "real-time" method, which means you can get the shell output on the fly, compared with following "subprocess.check_output" method, which collect all output in its return value. This method return the return value of the command, for example:

ret = subprocess.call('ls -l')

where ret=0, while

ret = subprocess.call('cd aaa')

ret=2 when there isn't "aaa" subfolder under CWD.

For ease of use, write a shorthand function:

import subprocessdef run(cmd):    ret = subprocess.call(cmd, shell=True)    if ret != 0:        sys.exit('Exec cmd %s error, return value: %s' %(cmd, str(ret)))

Then you can simply use "run(cmd)" as a shell interface. "run" print command stdout stderr to console stdout, and if there's something wrong during execution, we interrupt it.

subprocess.check_output

A more safe way to run shell command is using "check_output" function. If the return value if not 0, a exception raised, otherwise return the command output.

$ cat myrun.pyimport subprocessdef run(cmd):    return subprocess.check_output(cmd, shell=True)$ python -i myrun.py>>> ret = run('ls -l|grep donno')>>> ret'drwxr-xr-x 6 chad chad 4096 Jan 26 18:18 donno-0.1.10\n-rw-r--r-- 1 chad chad 8716 Jan 27 15:53 donno-0.1.10.tar.gz\n'>>> ret = run('cd aaa')/bin/sh: 1: cd: can't cd to aaaTraceback (most recent call last):  File "
", line 1, in
File "shtest.py", line 3, in run return subprocess.check_output(cmd, shell=True) File "/usr/lib/python2.7/subprocess.py", line 544, in check_output raise CalledProcessError(retcode, cmd, output=output)subprocess.CalledProcessError: Command 'cd aaa' returned non-zero exit status 2

os.system

If it's unnecessary to save command output, this is most convenient way. The output will output to console. You can use space and pipe in command:

>>> import os >>> ret = os.system('ls -l|grep D')

And it will return after the command complete:

>>> ret = os.system('vmstat 3 3')

os.popen

Use this form if you want to save command output.

>>> retfile = os.popen('pwd')>>> ret = retfile.read() >>> ret '/home/lichao\n' >>> retfile 

or write it more compact:

>>> result = os.popen('ls|grep enex').read()

subprocess.Popen

If you want some more powerful tools, use this. You can't use pipe directly in this form. Instead, You have to use subprocess.PIPE:

>>> import subprocess>>> lsres = subprocess.Popen(['ls','-l'], stdout=subprocess.PIPE)>>> grepres = subprocess.Popen(['grep', 'Do'], stdin=lsres.stdout, stdout=subprocess.PIPE)>>> res = grepres.communicate()

communicate() interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. It returns a tuple (stdoutdata, stderrdata).

Deprecated

  • commands.getoutput()

  • commands.getstatusoutput()

转载于:https://www.cnblogs.com/darkmatter/p/3605593.html

你可能感兴趣的文章
Pycharm Error loading package list:Status: 403错误解决方法
查看>>
steps/train_sat.sh
查看>>
转:Linux设备树(Device Tree)机制
查看>>
iOS 组件化
查看>>
(转)Tomcat 8 安装和配置、优化
查看>>
(转)Linxu磁盘体系知识介绍及磁盘介绍
查看>>
tkinter布局
查看>>
命令ord
查看>>
Sharepoint 2013搜索服务配置总结(实战)
查看>>
博客盈利请先考虑这七点
查看>>
使用 XMLBeans 进行编程
查看>>
写接口请求类型为get或post的时,参数定义的几种方式,如何用注解(原创)--雷锋...
查看>>
【OpenJ_Bailian - 2287】Tian Ji -- The Horse Racing (贪心)
查看>>
Java网络编程--socket服务器端与客户端讲解
查看>>
List_统计输入数值的各种值
查看>>
学习笔记-KMP算法
查看>>
Timer-triggered memory-to-memory DMA transfer demonstrator
查看>>
跨域问题整理
查看>>
[Linux]文件浏览
查看>>
64位主机64位oracle下装32位客户端ODAC(NFPACS版)
查看>>