Linux命令行调用没有从os.system返回什么? [英] Linux command-line call not returning what it should from os.system?

查看:261
本文介绍了Linux命令行调用没有从os.system返回什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要对linux进行一些命令行调用并从中获取返回值,但是当它应该返回时间值(例如00:08:19)时,如下所示只是返回0,我正在测试完全相同的值在常规命令行中调用,它返回时间值00:08:19,所以我对我做错了感到困惑,因为我认为这是在python中的处理方法.

I need to make some command line calls to linux and get the return from this, however doing it as below is just returning 0 when it should return a time value, like 00:08:19, I am testing the exact same call in regular command line and it returns the time value 00:08:19 so I am confused as to what I am doing wrong as I thought this was how to do it in python.

import os
retvalue = os.system("ps -p 2993 -o time --no-headers")
print retvalue

推荐答案

返回的是执行此命令的返回值.直接执行命令时看到的是stdout中命令的输出.返回0表示执行没有错误.

What gets returned is the return value of executing this command. What you see in while executing it directly is the output of the command in stdout. That 0 is returned means, there was no error in execution.

使用popen等捕获输出.

Use popen etc for capturing the output .

这方面的一些事情:

import subprocess as sub
p = sub.Popen(['your command', 'arg1', 'arg2', ...],stdout=sub.PIPE,stderr=sub.PIPE)
output, errors = p.communicate()
print output

import os
p = os.popen('command',"r")
while 1:
    line = p.readline()
    if not line: break
    print line

正在运行: Popen和python

这篇关于Linux命令行调用没有从os.system返回什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆