Linux 命令行调用没有从 os.system 返回它应该返回的内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3791465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Linux command-line call not returning what it should from os.system?
提问by Rick
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.
我需要对 linux 进行一些命令行调用并从中获取返回值,但是按照下面的操作只是0
在它应该返回时间值时返回,例如00:08:19
,我正在常规命令行中测试完全相同的调用,它返回时间价值,00:08:19
所以我对我做错了什么感到困惑,因为我认为这是如何在 python 中做到这一点。
import os
retvalue = os.system("ps -p 2993 -o time --no-headers")
print retvalue
采纳答案by pyfunc
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.
返回的是执行该命令的返回值。您在直接执行时看到的是 stdout 中命令的输出。返回 0 表示执行没有错误。
Use popen etc for capturing the output .
使用 popen 等来捕获输出。
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
or
或者
import os
p = os.popen('command',"r")
while 1:
line = p.readline()
if not line: break
print line
ON SO : Popen and python
ON SO:Popen 和 python
回答by JoshD
If you're only interested in the output from the process, it's easiest to use subprocess' check_outputfunction:
如果您只对流程的输出感兴趣,那么使用subprocess 的 check_output函数是最简单的:
output = subprocess.check_output(["command", "arg1", "arg2"]);
Then output holds the program output to stdout. Check the link above for more info.
然后输出将程序输出保存到标准输出。查看上面的链接以获取更多信息。
回答by George
okey I believe the fastest way it would be
好的,我相信这是最快的方式
import os
print(os.popen('command').readline())
x = _
print(x)
回答by vikkyhacks
Your code returns 0
if the execution of the commands passed is successful and non zero if it fails. The following program works on python2.7, haven checked 3 and versions above. Try this code.
0
如果传递的命令执行成功,您的代码将返回,如果失败则返回非零。以下程序适用于python2.7,已检查3及以上版本。试试这个代码。
>>> import commands
>>> ret = commands.getoutput("ps -p 2993 -o time --no-headers")
>>> print ret
回答by Yauhen Yakimovich
Yes it's counter-intuitive and does not seem very pythonic, but it actually just mimics the unix API design, where these calld are C POSIX functions. Check man 3 popen
&& man 3 system
是的,它是违反直觉的,看起来不是很 Pythonic,但它实际上只是模仿了 unix API 设计,其中调用的是 C POSIX 函数。检查man 3 popen
&&man 3 system
Somewhat more convenient snippet to replace os.systemthat I use:
替换我使用的os.system 的更方便的代码段:
from subprocess import (PIPE, Popen)
def invoke(command):
'''
Invoke command as a new system process and return its output.
'''
return Popen(command, stdout=PIPE, shell=True).stdout.read()
result = invoke('echo Hi, bash!')
# Result contains standard output (as you expected it in the first place).
回答by IonicBurger
The simplest way is like this:
最简单的方法是这样的:
import os
retvalue = os.popen("ps -p 2993 -o time --no-headers").readlines()
print retvalue
This will be returned as a list
这将作为列表返回
回答by Coriolis Force
This is an old thread, but purely using os.system
, the following's a valid way of accessing the data returned by the ps
call. Note: it does use a pipe to write the data to a file on disk. AndOP didn't specifically ask for a solution using os.system
.
这是一个旧线程,但纯粹使用os.system
,以下是访问ps
调用返回的数据的有效方法。注意:它确实使用管道将数据写入磁盘上的文件。并且OP 并没有特别要求使用os.system
.
>>> os.system("ps > ~/Documents/ps.txt")
0 #system call is processed.
>>> os.system("cat ~/Documents/ps.txt")
PID TTY TIME CMD
9927 pts/0 00:00:00 bash
10063 pts/0 00:00:00 python
12654 pts/0 00:00:00 sh
12655 pts/0 00:00:00 ps
0
accordingly,
因此,
>>> os.system("ps -p 10063 -o time --no-headers > ~/Documents/ps.txt")
0
>>> os.system("cat ~/Documents/ps.txt")
00:00:00
0
No idea why they are all returning zeroes though.
不知道为什么他们都返回零。
回答by Asif Hasnain
For your requirement, Popen function of subprocess python module is the answer. For example,
对于您的要求,子进程 python 模块的 Popen 函数就是答案。例如,
import subprocess
..
process = subprocess.Popen("ps -p 2993 -o time --no-headers", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
print stdout
回答by Joe
I can not add a comment to IonicBurgerbecause I do not have "50 reputation" so I will add a new entry. My apologies. os.popen()is the best for multiple/complicated commands (my opinion) and also for getting the return value in addition to getting stdout like the following more complicated multiple commands:
我无法向IonicBurger添加评论,因为我没有“50 声誉”,所以我将添加一个新条目。我很抱歉。 os.popen()最适合多个/复杂的命令(我的观点),并且除了像以下更复杂的多个命令一样获取 stdout 之外,还可以获取返回值:
import os
out = [ i.strip() for i in os.popen(r"ls *.py | grep -i '.*file' 2>/dev/null; echo $? ").readlines()]
print " stdout: ", out[:-1]
print "returnValue: ", out[-1]
This will list all python files that have the word 'file'anywhere in their name. The [...]is a list comprehension to remove (strip) the newline character from each entry. The echo $?is a shell command to show the return status of the last command executed which will be the grep command and the last item of the list in this example. the 2>/dev/nullsays to print the stderrof the grepcommand to /dev/nullso it does not show up in the output. The 'r'before the 'ls'command is to use the raw string so the shell will not interpret metacharacters like '*'incorrectly. This works in python 2.7. Here is the sample output:
这将列出名称中任何位置带有“文件”一词的所有 python 文件。的[...]是一个列表理解从每个条目中删除(条)的换行符。该回声$?是一个 shell 命令,用于显示执行的最后一个命令的返回状态,在此示例中将是 grep 命令和列表的最后一项。在2>的/ dev / null的说,打印STDERR的的的grep命令的/ dev / null的,因此不会在输出中出现。在“R”的前“ls”的命令是使用原始字符串,因此外壳不会像解释元字符“*”不正确。这适用于python 2.7。这是示例输出:
stdout: ['fileFilter.py', 'fileProcess.py', 'file_access..py', 'myfile.py']
returnValue: 0
回答by Sanjay Chakraborty
using commands module
import commands
"""
Get high load process details
"""
result = commands.getoutput("ps aux | sort -nrk 3,3 | head -n 1")
print result -- python 2x
print (result) -- python 3x