加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

commands.getstatusoutput的错误返回值和shell中的不一样?

发布时间:2020-12-15 19:47:27 所属栏目:安全 来源:网络整理
导读:该问题是一个博主的问答,在此记录一下,原文地址:http://bbs.chinaunix.net/thread-3666310-1-1.html 博主问题: 看下面例子,执行cat file命令(file文件不存在),shell中的返回值是 1 ,而python的commands.getstatusoutput返回值是 256 ,如何才能获得

该问题是一个博主的问答,在此记录一下,原文地址:http://bbs.chinaunix.net/thread-3666310-1-1.html

博主问题:

看下面例子,执行cat file命令(file文件不存在),shell中的返回值是1,而python的commands.getstatusoutput返回值是256,如何才能获得和shell中一致的返回值?

[root@myssl ~]# cat file
cat: file: 没有那个文件或目录
[root@myssl ~]# echo $?
1
[root@myssl ~]#
[root@myssl ~]# python
Python 2.4.3 (#1,Jun 11 2009,14:09:37) 
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help","copyright","credits" or "license" for more information.
>>> import commands
>>> commands.getstatusoutput('cat file')
(256,'cat: file: xc3xbbxd3xd0xc4xc7xb8xf6xcexc4xbcxfexbbxf2xc4xbfxc2xbc')
>>>

回答:

其实这个返回值256就是十六进制的0x100,其高位就是1。

这是调用了os.wait()的缘故(*nix下)。

类似的,如果你输入一个不存在的程序,比如xxx。

shell中的$?返回为127,在这里会显示32512,正是十六进制的0x7f00,其高位0x7f就是十进制的127。

另外,使用os.system('command')也有同样的效果。

至于为什么会这样,
os.wait()

    Wait for completion of a child process,and return a tuple containing its pid and exit status indication: a 16-bit number,whose low byte is the signal number that killed the process,and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced.
复制代码
这是系统函数wait()这么实现的缘故,从某种角度来说,你也可以认为这是python的一个小bug,没有把这个返回值做进一步处理。当然,最初没有做进一步处理,也可能有另外的考量。

--------------------------

要取出这个返回值,对该值进行右移8位操作就可以了。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读