Linux 命令行调用没有从 os.system 返回它应该返回的内容? [英] Linux command-line call not returning what it should from os.system?

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

问题描述

我需要对 linux 进行一些命令行调用并从中获取返回值,但是按以下方式执行只会返回 0,而它应该返回时间值,例如 00:08:19,我正在常规命令行中测试完全相同的调用,它返回时间值 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 .

沿着这条线的一些事情:

Some thing along this line:

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天全站免登陆