写一个使用subprocess的sPopen函数执行shell命令的例子

给个以前写的例子

#! /usr/bin/env python
# class subprocess test of python language
# 2015-01-07

import subprocess

def popen_test():
    # use class subprocess to get child's pid,
    # return value, stdin, stdout, stderr etc.
    sPopen = subprocess.Popen("ls ${HOME}", shell=True, stdout=subprocess.PIPE)
    sPopen.wait() # wait for sPopen's process end 
    
    print("sPopen.pid: ", sPopen.pid)
    print("sPopen.returncode: ", sPopen.returncode)
    print("sPopen.stdin: ", sPopen.stdin)
    print("sPopen.stdout.read(): ", sPopen.stdout.read())
    print("sPopen.stderr: ", sPopen.stderr)
    
    # if ... else statement
    if sPopen.pid == sPopen.pid:
    	print("sPopen.pid == sPopen.pid")
    else:
    	print("sPopen.pid != sPopen.pid")
    	
    # communicate can get stderr and stdout
    out = sPopen.communicate()
    print("sPopen.communicate out: ", out)
    print("sPopen.communicate out[0] = ", out[0], " out[1]", out[1], "\n")

    res = subprocess.Popen("echo \"hello python\"", shell=True, stdout=subprocess.PIPE)
    print("res.stdout.read(): ", res.stdout.read())
    print("res.returncode: ", res.returncode)

def call_test():
    # get return code of shell commands
    retcode = subprocess.call("ls ~/", shell=True, stdout=subprocess.PIPE)
    print("subprocess.call retcode: ", retcode)
    try:
    	res = subprocess.check_call(['ls', '-l'])
    except err:
    	print("subprocess.check_call res: ", res)

if __name__ == "__main__":
    popen_test()
    call_test()

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值