ValueError: the environment variable is longer than 32767 characters On Windows, an environment variable string ("name=value" string) is limited to 32,767 characters

时间:2023-03-10 06:21:07
ValueError: the environment variable is longer than 32767 characters   On Windows, an environment variable string ("name=value" string) is limited to 32,767 characters

https://github.com/python/cpython/blob/aa1b8a168d8b8dc1dfc426364b7b664501302958/Lib/test/test_os.py

https://github.com/python/cpython/blob/master/Lib/test/test_os.py#L1122

import os

s=''
for i in range(1<<24):
s+="A" os.environ.setdefault("k",s)

  

os.environ.setdefault("k",s)
File "C:\env\py382\lib\os.py", line 712, in setdefault
self[key] = value
File "C:\env\py382\lib\os.py", line 681, in __setitem__
self.putenv(key, value)
ValueError: the environment variable is longer than 32767 characters

        if sys.platform == "win32":
# On Windows, an environment variable string ("name=value" string)
# is limited to 32,767 characters
longstr = 'x' * 32_768
self.assertRaises(ValueError, os.putenv, longstr, "1")
self.assertRaises(ValueError, os.putenv, "X", longstr)
self.assertRaises(ValueError, os.unsetenv, longstr)