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)

Под капотом

Разбор того как работает 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")

Автор статьи: Андрей Олегович

Похожие статьи
Основы
Архитектура
Библиотеки
Переменные: set, reassign…
if else: Условные операторы
in: Оператор принадлежности к списку
Циклы
Перенос на новую строку
[Tags]: теги
JSON
Передача аргументов в кейворд
Evaluate
Поддержка Robot в PyCharm
Ошибки

Поиск по сайту

Подпишитесь на Telegram канал @aofeed чтобы следить за выходом новых статей и обновлением старых

Перейти на канал

@aofeed

Задать вопрос в Телеграм-группе

@aofeedchat

Контакты и сотрудничество:
Рекомендую наш хостинг beget.ru
Пишите на info@urn.su если Вы:
1. Хотите написать статью для нашего сайта или перевести статью на свой родной язык.
2. Хотите разместить на сайте рекламу, подходящую по тематике.
3. Реклама на моём сайте имеет максимальный уровень цензуры. Если Вы увидели рекламный блок недопустимый для просмотра детьми школьного возраста, вызывающий шок или вводящий в заблуждение - пожалуйста свяжитесь с нами по электронной почте
4. Нашли на сайте ошибку, неточности, баг и т.д. ... .......
5. Статьи можно расшарить в соцсетях, нажав на иконку сети: