python sys.argv 的限制?

14 投票
3 回答
14566 浏览
提问于 2025-04-16 15:01

假设我想运行一个Python脚本,命令是:python my_script.py MY_INPUT

在这个例子中,MY_INPUT 会被传递到 sys.argv[1] 里。

那么,MY_INPUT 的字符数量有没有限制呢?

还有,MY_INPUT 的字符类型有没有限制呢?

关于 MY_INPUT 还有其他的限制吗?

更新:我使用的是Ubuntu Linux 10.04。

3 个回答

0

我做了个简单的测试,

squid.py $(find . -name '*.java' | head -n 480) 这个命令成功了481个,失败了。 我上移了一个目录,长度是16个字符,所以每个结果我去掉了17个字符。 接着我又试了这个命令:../squid.py $(find . -name '*.java' | head -n 638),结果成功了,失败了639个。 看起来发生的事情似乎和所有参数的总大小有关。

为了测试这个,我用了一个工具wc

find . -name '*.java' | head -n 480 | wc
find . -name '*.java' | head -n 481 | wc

在下一个目录里。

find . -name '*.java' | head -n 638 | wc
find . -name '*.java' | head -n 639 | wc

结果。

$ find . -name '*.java' | head -n638 | wc
    638     638   32665
$ find . -name '*.java' | head -n639 | wc
    639     639   32705
$ cd ..
$ find . -name '*.java' | head -n480 | wc
    480     480   33328
$ find . -name '*.java' | head -n481 | wc
    481     481   33396

所以这看起来和32K非常接近,正如其他评论所说,这个结果很依赖于系统,这次是在Windows 10的git bash上进行的。

3

Python本身对sys.argv的长度或内容没有任何限制。但是,你的操作系统和命令行工具肯定会有一些限制。要想完全回答这个问题,需要详细了解你所使用的环境。

15

argv的大小是受到操作系统限制的,不同的操作系统限制的大小差别很大。引用一下Linux的execve(2)手册:

Limits on size of arguments and environment
   Most Unix implementations impose some limit on the total size
   of the command-line argument (argv) and environment (envp)
   strings that may be passed to a new program.  POSIX.1 allows an
   implementation to advertise this limit using the ARG_MAX
   constant (either defined in <limits.h> or available at run time
   using the call sysconf(_SC_ARG_MAX)).

   On Linux prior to kernel 2.6.23, the memory used to store the
   environment and argument strings was limited to 32 pages
   (defined by the kernel constant MAX_ARG_PAGES).  On
   architectures with a 4-kB page size, this yields a maximum size
   of 128 kB.

   On kernel 2.6.23 and later, most architectures support a size
   limit derived from the soft RLIMIT_STACK resource limit (see
   getrlimit(2)) that is in force at the time of the execve()
   call.  (Architectures with no memory management unit are
   excepted: they maintain the limit that was in effect before
   kernel 2.6.23.)  This change allows programs to have a much
   larger argument and/or environment list.  For these
   architectures, the total size is limited to 1/4 of the allowed
   stack size.  (Imposing the 1/4-limit ensures that the new
   program always has some stack space.)  Since Linux 2.6.25, the
   kernel places a floor of 32 pages on this size limit, so that,
   even when RLIMIT_STACK is set very low, applications are
   guaranteed to have at least as much argument and environment
   space as was provided by Linux 2.6.23 and earlier.  (This
   guarantee was not provided in Linux 2.6.23 and 2.6.24.)
   Additionally, the limit per string is 32 pages (the kernel
   constant MAX_ARG_STRLEN), and the maximum number of strings is
   0x7FFFFFFF.

撰写回答