【问题标题】:python sys.argv limitations?python sys.argv 限制?
【发布时间】:2011-04-04 01:18:30
【问题描述】:

假设我想运行这样的 python 脚本:python my_script.py MY_INPUT。 在这种情况下,MY_INPUT 将被传输到sys.argv[1]

MY_INPUT 可以包含的字符 个数 有限制吗?

MY_INPUT 可以包含的字符类型是否有限制?

关于MY_INPUT的任何其他限制?

更新:我使用的是 Ubuntu Linux 10.04

【问题讨论】:

  • 实际上,MY_INPUT 转到 sys.argv[1]sys.argv[0] 将包含 'my_script.py'
  • @Tom:谢谢,我更正了上面的代码。

标签: python


【解决方案1】:

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.

【讨论】:

  • 谢谢。可以给出关于type 字符的任何提示?可以给space 吗?可以给tab 吗?
  • @user540009:可以解析的字符没有限制,但是你的shell很可能会将空格解释为参数分隔符;如果这是不可取的,您可以将单个参数括在引号中:python my_script.py 'This is MY_INPUT as one arg' OtherArg
  • @user540009,几乎所有事情都会发生,但是 ascii NUL 字符会终止 argv[] 指针数组指向的每个字符串,因此构造一个包含 '\0' 字节的参数将需要一些努力编码和解码。但是可能有更好的机制来做任何你想做的事情:)
【解决方案2】:

Python 本身对sys.argv 的长度或内容没有任何限制。但是,您的操作系统和/或命令 shell 肯定会。如果不详细考虑您的操作环境,这个问题就无法完全回答。

【讨论】:

  • 知道在处理 Ubuntu Linux 时有什么限制吗?
  • 查看这个问题以获得 Linux 的答案:stackoverflow.com/questions/1480110/…
  • 谢谢。那么给出的字符类型呢?可以包含空格吗?
  • Python 确实对列表施加了限制; sys.maxsize 给出了这个限制。实际上,在创建这么大的列表之前,您的内存就会用完。
猜你喜欢
  • 2012-02-24
  • 1970-01-01
  • 2016-05-23
  • 2021-11-18
  • 2012-02-10
  • 2017-08-17
  • 2011-12-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多