Python 执行系统命令后并获取返回值

  • Post author:
  • Post category:python

使用os.system

import os, subprocess

In [33]: result = os.system('tasklist')

In [34]: print(result)
0
# 返回0

使用os.popen

In [30]: result = os.popen('tasklist')

In [31]: result = result.read()

In [32]: for line in result.splitlines()[:5]:
    ...:     print(line)
    ...:

映像名称                       PID 会话名              会话#       内存使用
========================= ======== ================ =========== ============
System Idle Process              0 Services                   0         24 K
System                           4 Services                   0         64 K

使用subprocess.Popen

In [37]: p = subprocess.Popen('tasklist', shell=True, stdout=subprocess.PIPE)

In [38]: out, err = p.communicate()


#此处需要对line的内容进行解码
In [39]: for line in out.splitlines()[:6]:
    ...:     print(line.decode('gbk'))
    ...:

映像名称                       PID 会话名              会话#       内存使用
========================= ======== ================ =========== ============
System Idle Process              0 Services                   0         24 K
System                           4 Services                   0         64 K
smss.exe                       400 Services                   0         76 K

版权声明:本文为huiyanshizhu原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。