小编Sim*_*ser的帖子

为什么getpwuid和getgrgid会有不同的行为?

在Python 2.7,3.4和3.5中,grp.getgrgid能够接受一个字符串:

from grp import getgrgid
print(getgrgid('0'))
Run Code Online (Sandbox Code Playgroud)

但是,pwd.getpwuid不能这样做:

from pwd import getpwuid
print(getpwuid('0'))

Traceback (most recent call last):
  File "getpwuid_test.py", line 2, in <module>
    print(getpwuid('0'))
TypeError: an integer is required
Run Code Online (Sandbox Code Playgroud)

这是因为在内部Modules/pwdmodule.c,getpwuid使用PyNumber_ParseTuple转换器PyNumber_Index来获取Python整数,并在失败时引发异常.

然而,在Modules/grpmodule.c,grp_getgrgid应用PyNumber_Long (或者PyNumber_Int一个老足够的Python)作为转换第一,并作为文件说,在https://docs.python.org/3/c-api/number.html,这是运行的等效int(o),可以将字符串转换为整数.只有这样才能PyNumber_Index通过辅助函数给予它_Py_Gid_Converter

造成这种差异的原因是什么?这是基于历史的故意选择吗?

这种行为getgrgid似乎更有帮助,奇怪的是它并不适用于这两种功能.在这种不良行为getgrgidgetpwuid

python cpython python-2.7 python-3.x

7
推荐指数
1
解决办法
379
查看次数

为什么`subprocess.check_call(...,stderr = sys.stdout)`在Python 2.6中失败?

Python 2.6.9 (unknown, Mar  7 2016, 11:15:18) 
[GCC 5.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> import subprocess
>>> subprocess.check_call(['echo', 'hi'], stderr=sys.stdout)
echo: write error: Bad file descriptor
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/subprocess.py", line 488, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['echo', 'hi']' returned non-zero exit status 1
Run Code Online (Sandbox Code Playgroud)

这个命令subprocess.check_call(['echo', 'hi'], stderr=sys.stdout)在Python 2.7和Python 3中运行得很好.什么是Python 2.6做的不同?

python python-2.6

7
推荐指数
1
解决办法
293
查看次数

标签 统计

python ×2

cpython ×1

python-2.6 ×1

python-2.7 ×1

python-3.x ×1