Python,os.system为命令行调用(linux)不返回应该什么? [英] Python, os.system for command-line call (linux) not returning what it should?

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

问题描述

我需要对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. Any advice is appreciated.

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

ON SO: Popen和python

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

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