加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-15 19:38:29 所属栏目:安全 来源:网络整理
导读:给个以前写的例子 #! /usr/bin/env python# class subprocess test of python language# 2015-01-07import subprocessdef popen_test(): # use class subprocess to get child's pid,# return value,stdin,stdout,stderr etc. sPopen = subprocess.Popen("ls

给个以前写的例子

#! /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"",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 ~/",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()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读