Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get in python the maximum filesystem path length in unix?

In the code I maintain I run across:

from ctypes.wintypes import MAX_PATH

I would like to change it to something like:

try:
    from ctypes.wintypes import MAX_PATH
except ValueError: # raises on linux
    MAX_PATH = 4096 # see comments

but I can't find any way to get the value of max filesystem path from python (os, os.path, sys...) - is there a standard way or do I need an external lib ?

Or there is no analogous as MAX_PATH in linux, at least not a standard among distributions ?


Answer

try:
    MAX_PATH = int(subprocess.check_output(['getconf', 'PATH_MAX', '/']))
except (ValueError, subprocess.CalledProcessError, OSError):
    deprint('calling getconf failed - error:', traceback=True)
    MAX_PATH = 4096
like image 890
Mr_and_Mrs_D Avatar asked Dec 11 '22 20:12

Mr_and_Mrs_D


1 Answers

The way to do it correctly is to use the os.pathconf or os.fpathconf with PC_ prefixed names:

>>> os.pathconf('/', 'PC_PATH_MAX')
4096
>>> os.pathconf('/', 'PC_NAME_MAX')
255

Notice that the maximum length of a path component may vary from directory to another, as it is filesystem dependent, so you might have os.pathconf('/', 'PC_NAME_MAX') as 255 and os.pathconf('/', 'PC_NAME_MAX') as 12, say.

like image 123