This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author serhiy.storchaka
Recipients serhiy.storchaka
Date 2019-09-12.18:31:01
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1568313061.34.0.998675763501.issue38144@roundup.psfhosted.org>
In-reply-to
Content
The pattern for the glob() function can be relative and absolute. If it is relative, paths are searched from the current directory. If you want to search them in other directory, you need either change the current directory (which affects other parts of your program) or pass a concatenation of the escaped root directory and a pattern:

   glob.glob(os.path.join(glob.escape(root_dir), pattern))

Most code (even in the stdlib and tools) forget to escape the root directory. It works only until it does not contain metacharacters ('*?[').

When you need paths relative to the root directory, you need to "remove" the root_dir prefix from results (using os.path.relpath() at best).

The proposed PR adds two new parameters in glob.glob() and glob.iglob(): root_dir and dir_fd.

root_dir specifies the root directory for relative pattern. Its effect is the same as chdir before calling glob(). It is similar to the root_dir parameter of shutil.make_archive. For example, you can add py-files in the specified directory to the ZIP archive by:

    with zipfile.ZipFile(archive, 'w') as zf:
        for filename in glob.glob('**/*.py', recursive=True, root_dir=root_dir):
            zf.write(os.path.join(root_dir, filename), arcname=filename)

Adding to archive and copying are simpler if you have paths relative to the specified directory.

The dir_fd parameter is similar to root_dir, but it specifies the root directory as an open directory descriptor instead of a path (as in many os functions). It adds security (nobody can rename and replace the root directory in process) and performance (because of shorter paths).

root_dir and dir_fd can be combined. root_dir is relative to dir_fd and the pattern is relative to root_dir.

If root_dir is absolute, dir_fd is ignored. If the pattern is absolute, root_dir and dir_fd are ignored.
History
Date User Action Args
2019-09-12 18:31:01serhiy.storchakasetrecipients: + serhiy.storchaka
2019-09-12 18:31:01serhiy.storchakasetmessageid: <1568313061.34.0.998675763501.issue38144@roundup.psfhosted.org>
2019-09-12 18:31:01serhiy.storchakalinkissue38144 messages
2019-09-12 18:31:01serhiy.storchakacreate