Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
python os.walk traversal problem
#!/usr/bin/python3
"""
os.walk traversal problem
"""
import os
import sys
import logging
import tempfile
def _error(exc):
raise exc
def test_walk_recursion_limit():
" os.walk has to raise RecursionError "
tmpdirname = tempfile.mkdtemp(prefix='python-walk-test-')
os.chdir(tmpdirname)
for _ in range(sys.getrecursionlimit() + 1):
os.mkdir('x')
os.chdir('x')
os.chdir(tmpdirname)
for _ in os.walk(tmpdirname, onerror=_error):
pass
def test_walk_file_name_too_long():
" os.walk has to raise OSError(36, 'File name too long') "
tmpdirname = tempfile.mkdtemp(prefix='python-walk-test-')
os.chdir(tmpdirname)
names = []
while True:
name = 'x' * 10
names.append(name)
os.mkdir(name)
os.chdir(name)
full_path = os.path.join(tmpdirname, os.sep.join(names))
if len(full_path) > os.pathconf(tmpdirname, 'PC_PATH_MAX'):
break
os.chdir(tmpdirname)
for _ in os.walk(tmpdirname, onerror=_error):
pass
try:
test_walk_recursion_limit()
except RecursionError as e:
logging.error(e)
try:
test_walk_file_name_too_long()
except OSError as e:
logging.error(e.strerror)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.