为什么subprocess.Popen参数长度限制小于OS报告的值?

2024-04-26 10:50:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Linux3.16.0上运行Python3.4.3。我想使用subprocess.Popen来运行一个单参数长的命令(一个复杂的Bash调用),大约200KiB。

根据getconfxargs,这应该在我的限制范围内:

$ getconf ARG_MAX
2097152
$ xargs --show-limits < /dev/null
Your environment variables take up 3364 bytes
POSIX upper limit on argument length (this system): 2091740
POSIX smallest allowable upper limit on argument length (all systems): 4096
Maximum length of command we could actually use: 2088376
Size of command buffer we are actually using: 131072

但是,Python失败的限制非常小:

>>> subprocess.Popen('echo %s > /dev/null' % ('a' * (131072-4096)), shell=True, executable='/bin/bash')
<subprocess.Popen object at 0x7f4613b58410>
>>> subprocess.Popen('echo %s > /dev/null' % ('a' * (262144-4096)), shell=True, executable='/bin/bash')
Traceback (most recent call last):
  [...]
OSError: [Errno 7] Argument list too long

注意,Python限制与“实际使用”命令缓冲区xargs报告大致相同。这表明xargs在某种程度上足够聪明,可以从一个较小的限制开始,并根据需要增加它,但Python不是。

问题:

  1. 为什么Python限制小于操作系统限制2MiB?
  2. 我可以提高Python的限制吗?
  3. 如果是,怎么做?

Tags: ofdev命令onargumentuppernulllength
2条回答

This其他问题与您的类似,但对于Windows。在这种情况下,您可以通过避免shell=True选项来绕过任何shell限制。

否则,您可以提供一个文件列表给subprocess.Popen(),正如在该场景中所做的那样,并且正如@aron Digulla所建议的那样。

单个字符串参数的最大大小限制为131072。它与python无关:

~$ /bin/echo "$(printf "%*s" 131071 "a")">/dev/null
~$ /bin/echo "$(printf "%*s" 131072 "a")">/dev/null
bash: /bin/echo: Argument list too long

实际上是MAX_ARG_STRLEN决定单个字符串的最大大小:

And as additional limit since 2.6.23, one argument must not be longer than MAX_ARG_STRLEN (131072). This might become relevant if you generate a long call like "sh -c 'generated with long arguments'". (pointed out by Xan Lopez and Ralf Wildenhues)

请参阅this discussion of ^{},在“参数数量和一个参数的最大长度”下,以及unix.stackexchange上的this question

你可以在binfmts.h中看到它:

/*
 * These are the maximum length and maximum number of strings passed to the
 * execve() system call.  MAX_ARG_STRLEN is essentially random but serves to
 * prevent the kernel from being unduly impacted by misaddressed pointers.
 * MAX_ARG_STRINGS is chosen to fit in a signed 32-bit integer.
 */
#define MAX_ARG_STRLEN (PAGE_SIZE * 32)
#define MAX_ARG_STRINGS 0x7FFFFFFF

~$ echo $(( $(getconf PAGE_SIZE)*32 )) 
131072

可以传递多个长度为131071的字符串:

subprocess.check_call(['echo', "a"*131071,"b"*131071], executable='/bin/bash',stdout=open("/dev/null","w"))

但是单个字符串arg不能超过131071字节。

相关问题 更多 >