Robot Framework
robotio.py
Go to the documentation of this file.
1 # Copyright 2008-2015 Nokia Networks
2 # Copyright 2016- Robot Framework Foundation
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 
16 import io
17 import os.path
18 
19 from robot.errors import DataError
20 
21 from .error import get_error_message
22 from .robottypes import is_pathlike
23 
24 
25 def file_writer(path=None, encoding='UTF-8', newline=None, usage=None):
26  if not path:
27  return io.StringIO(newline=newline)
28  if is_pathlike(path):
29  path = str(path)
30  create_destination_directory(path, usage)
31  try:
32  return io.open(path, 'w', encoding=encoding, newline=newline)
33  except EnvironmentError:
34  usage = '%s file' % usage if usage else 'file'
35  raise DataError("Opening %s '%s' failed: %s"
36  % (usage, path, get_error_message()))
37 
38 
39 def binary_file_writer(path=None):
40  if path:
41  if is_pathlike(path):
42  path = str(path)
43  return io.open(path, 'wb')
44  f = io.BytesIO()
45  getvalue = f.getvalue
46  f.getvalue = lambda encoding='UTF-8': getvalue().decode(encoding)
47  return f
48 
49 
50 def create_destination_directory(path, usage=None):
51  if is_pathlike(path):
52  path = str(path)
53  directory = os.path.dirname(path)
54  if directory and not os.path.exists(directory):
55  try:
56  os.makedirs(directory, exist_ok=True)
57  except EnvironmentError:
58  usage = '%s directory' % usage if usage else 'directory'
59  raise DataError("Creating %s '%s' failed: %s"
60  % (usage, directory, get_error_message()))
def get_error_message()
Returns error message of the last occurred exception.
Definition: error.py:34
def binary_file_writer(path=None)
Definition: robotio.py:39
def file_writer(path=None, encoding='UTF-8', newline=None, usage=None)
Definition: robotio.py:25
def create_destination_directory(path, usage=None)
Definition: robotio.py:50