Create Directory в Robot Framework

Введение

В этой статье вы можете познакомиться с адаптированной версией Create Directory из библиотеки OperatingSystem.py

Код

Вот как реализовано создание директорий в библиотеке OperatingSystem.py из Robot Framework

self._link для простоты можно заменить на print

self._error на raise RuntimeError

import os def create_directory(self, path): """Creates the specified directory. Also possible intermediate directories are created. Passes if the directory already exists, but fails if the path exists and is not a directory. """ path = self._absnorm(path) if os.path.isdir(path): self._link("Directory '%s' already exists.", path) elif os.path.exists(path): self._error("Path '%s' is not a directory." % path) else: os.makedirs(path) self._link("Created directory '%s'.", path)

Banner image

Под капотом

Разбор того как работает create_directory()

Отброшено всё ООП и сокращена часть с обработкой ошибок.

# OOP is removed from these examples import os from pathlib import Path from unicodedata import normalize UNIXY = os.sep == '/' WINDOWS = not UNIXY if WINDOWS: CASE_INSENSITIVE_FILESYSTEM = True else: try: CASE_INSENSITIVE_FILESYSTEM = os.listdir('/tmp') == os.listdir('/TMP') except OSError: CASE_INSENSITIVE_FILESYSTEM = False def create_directory(path): """Creates the specified directory. Also possible intermediate directories are created. Passes if the directory already exists, but fails if the path exists and is not a directory. """ path = abspath(normalize_path(path)) if os.path.isdir(path): print("Directory '%s' already exists.", path) elif os.path.exists(path): raise RuntimeError("Path '%s' is not a directory." % path) else: os.makedirs(path) print("Created directory '%s'.", path) def normalize_path(path, case_normalize=False): # OperatingSystem.py """Normalizes the given path. - Collapses redundant separators and up-level references. - Converts ``/`` to ``\`` on Windows. - Replaces initial ``~`` or ``~user`` by that user's home directory. - If ``case_normalize`` is given a true value (see `Boolean arguments`) on Windows, converts the path to all lowercase. - Converts ``pathlib.Path`` instances to ``str``. Examples: | ${path1} = | Normalize Path | abc/ | | ${path2} = | Normalize Path | abc/../def | | ${path3} = | Normalize Path | abc/./def//ghi | | ${path4} = | Normalize Path | ~robot/stuff | => - ${path1} = 'abc' - ${path2} = 'def' - ${path3} = 'abc/def/ghi' - ${path4} = '/home/robot/stuff' On Windows result would use ``\`` instead of ``/`` and home directory would be different. """ if isinstance(path, Path): path = str(path) else: path = path.replace('/', os.sep) path = os.path.normpath(os.path.expanduser(path)) # os.path.normcase doesn't normalize on OSX which also, by default, # has case-insensitive file system. Our robot.utils.normpath would # do that, but it's not certain would that, or other things that the # utility do, desirable. if case_normalize: path = os.path.normcase(path) return path or '.' def abspath(path, case_normalize=False): # robotpath.py """Replacement for os.path.abspath with some enhancements and bug fixes. 1. Non-Unicode paths are converted to Unicode using file system encoding. 2. Optionally lower-case paths on case-insensitive file systems. That includes Windows and also OSX in default configuration. 3. Turn ``c:`` into ``c:\`` on Windows instead of ``c:\current\path``. """ path = normpath(path, case_normalize) return normpath(os.path.abspath(path), case_normalize) def normpath(path, case_normalize=False): # robotpath.py """Replacement for os.path.normpath with some enhancements. 1. Convert non-Unicode paths to Unicode using the file system encoding. 2. NFC normalize Unicode paths (affects mainly OSX). 3. Optionally lower-case paths on case-insensitive file systems. That includes Windows and also OSX in default configuration. 4. Turn ``c:`` into ``c:\`` on Windows instead of keeping it as ``c:``. """ if isinstance(path, Path): path = str(path) elif not isinstance(path, str): path = system_decode(path) path = safe_str(path) # Handles NFC normalization on OSX path = os.path.normpath(path) if case_normalize and CASE_INSENSITIVE_FILESYSTEM: path = path.lower() if WINDOWS and len(path) == 2 and path[1] == ':': return path + '\' return path def system_decode(string): # encoding.py return string if isinstance(string, str) else safe_str(string) def safe_str(item): # unic.py return normalize('NFC', _safe_str(item)) def _safe_str(item): # unic.py if isinstance(item, str): return item if isinstance(item, (bytes, bytearray)): # Map each byte to Unicode code point with same ordinal. return item.decode('latin-1') try: return str(item) # Will stop adding dependencies here because ErrorDetails class # is to big for this example. # except Exception: # return _unrepresentable_object(item) except Exception as e: return f'<Unrepresentable object {type(item).__name__}. Error: {e}>' if __name__ == '__main__': create_directory("backup")

Article author: Andrei Olegovich

Related articles
Operating System
RequestsLibrary
XML
Libraries
Robot Framework
Banner image

Search this site

Subscribe to Telegram channel @aofeed to follow new articles and updates to old ones

Go to channel

@aofeed

Ask a question in the Telegram group

@aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: