python 利用python的subprocess模塊執行外部命令,獲取返回值


有時執行dos命令需要保存返回值

需要導入庫subprocess

import subprocess

p = subprocess.Popen('ping www.baidu.com', shell=True, stdout=subprocess.PIPE) out, err = p.communicate() print out.splitlines()[24:27] for line in out.splitlines(): print line

splitlines 是個列表

可以切片操作

完整代碼:

# 利用python的subprocess模塊執行外部命令, 並捕獲stdout, stderr的輸出:
# Python代碼
import subprocess


# print ’popen3:’

def external_cmd(cmd, msg_in=''):
    try:
        proc = subprocess.Popen(cmd,
                                shell=True,
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                )
        stdout_value, stderr_value = proc.communicate(msg_in)
        return stdout_value, stderr_value
    except ValueError as err:
        # log("ValueError: %s" % err)
        return None, None
    except IOError as err:
        # log("IOError: %s" % err)
        return None, None


if __name__ == '__main__':
    stdout_val, stderr_val = external_cmd('ls -l')
    print 'Standard Output: %s' % stdout_val
    print 'Standard Error: %s' % stderr_val

輸出:

Standard Output: 
Standard Error: 'ls' 不是內部或外部命令,也不是可運行的程序
或批處理文件。


Process finished with exit code 0

部分內容來自網絡

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM