zoukankan      html  css  js  c++  java
  • subprocess应用:python原样输出linux信息以及poll()返回值判断

    #!/usr/bin/python3
    # -*- coding: utf-8 -*-
    import os
    import subprocess
    
    
    # 与在命令窗口执行显示效果相同,如有彩色输出可保留,但不能返回结果
    def run(command):
        subprocess.call(command, shell=True)
    
    
    # 实时输出但不可显示彩色,可以返回结果
    def sh(command, print_msg=True):
        p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        lines = []
        for line in iter(p.stdout.readline, b''):
            line = line.rstrip().decode('utf8')
            if print_msg:
                print(">>>", line)
            lines.append(line)
        return lines
    
    
    #print('run():')
    #run("ping www.baidu.com")
    #cmd = 'certbot certonly --no-self-upgrade -d "*.smartfleet.inhandiot.com" -d "smartfleet.inhandiot.com" --manual --preferred-challenges dns --dry-run --manual-auth-hook "/root/workshop/certbot/au.sh python aly add" --manual-cleanup-hook "/root/workshop/certbot/au.sh python aly clean"'
    print('
    
    sh():')
    sh("free -h")
    #sh(cmd)

    另外一种方import subprocess

    def run_shell(shell):
        cmd = subprocess.Popen(shell, stdin=subprocess.PIPE, stderr=subprocess.PIPE,
                               stdout=subprocess.PIPE, universal_newlines=True, shell=True, bufsize=1)
        # 实时输出
        while True:
            line = cmd.stdout.readline()
            print(line, end='')
            if not line:  
                break
    
        return cmd.returncode
    
    
    if __name__ == '__main__':
        print(run_shell("ping www.baidu.com"))

    方法3

    .readline可能导致卡死,官方推荐使用communicate,但是如果还是使用subprocess.PIPE,执行完命令后才能拿到标准输出,替换成sys.stdout就能达到实时输出效果,代码附上

    import subprocess
    import sys
    
    
    def run_shell(shell):
        cmd = subprocess.Popen(shell, stdin=subprocess.PIPE, stderr=sys.stderr, close_fds=True,
                               stdout=sys.stdout, universal_newlines=True, shell=True, bufsize=1)
    
        cmd.communicate()
        return cmd.returncode
    
    
    if __name__ == '__main__':
        print(run_shell("ping www.baidu.com"))

    https://www.cnblogs.com/chenqionghe/p/11532245.html

    https://www.jb51.net/article/201484.htm

    二. subprocess是否执行成功的状态返回值

    本例以一个不存在的目录为例,来测试状态返回值

    import subprocess
    
    
    p = subprocess.Popen("ls /root", stderr=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True, shell=True, bufsize=1)
    
    
    err_msg=p.stderr.read()
    print("错误输出为:",err_msg)
    
    cmd_status=p.poll()
    print(cmd_status) # 目录为/root时返回0, 目录为不存在的/abc时返回2
    while True: line = p.stdout.readline() print(line) if not line: break #return cmd_status

    测试代码如上,poll函数返回码:

    0 正常结束
    1 sleep
    2 子进程不存在
    -15 kill
    None 在运行
    生命的意义在于奉献, 解决各种问题
  • 相关阅读:
    sql in not in 案例用 exists not exists 代替
    根据算法规则进行匹配相似车辆
    随机生成临时车牌号
    无法加载 DLL“ParkCOM.dll”: 找不到指定的模块。 (异常来自 HRESULT:0x8007007E) 终结者
    c# 除掉前三个字符,剩下的4个字符全为数字方为特殊车辆
    UI设计文本框解决Placeholder的在IE10 以下 IE 9 IE8 IE 7 的兼容问题
    EF框架 对字段属性为NULL的空值处理 类型前面加上?保证EF列表读取显示数据不会报异常
    boost::property_tree读取解析.xml文件
    C++ URLencode library
    http与中文编码传输
  • 原文地址:https://www.cnblogs.com/regit/p/14780903.html
Copyright © 2011-2022 走看看