• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ==============================================================================
15# pylint: disable=g-import-not-at-top
16"""Utilities related to disk I/O."""
17from __future__ import absolute_import
18from __future__ import division
19from __future__ import print_function
20
21import os
22import sys
23
24import six
25
26
27if sys.version_info >= (3, 6):
28
29  def _path_to_string(path):
30    if isinstance(path, os.PathLike):
31      return os.fspath(path)
32    return path
33elif sys.version_info >= (3, 4):
34
35  def _path_to_string(path):
36    import pathlib
37    if isinstance(path, pathlib.Path):
38      return str(path)
39    return path
40else:
41
42  def _path_to_string(path):
43    return path
44
45
46def path_to_string(path):
47  """Convert `PathLike` objects to their string representation.
48
49  If given a non-string typed path object, converts it to its string
50  representation. Depending on the python version used, this function
51  can handle the following arguments:
52  python >= 3.6: Everything supporting the fs path protocol
53    https://www.python.org/dev/peps/pep-0519
54  python >= 3.4: Only `pathlib.Path` objects
55
56  If the object passed to `path` is not among the above, then it is
57  returned unchanged. This allows e.g. passthrough of file objects
58  through this function.
59
60  Args:
61    path: `PathLike` object that represents a path
62
63  Returns:
64    A string representation of the path argument, if Python support exists.
65  """
66  return _path_to_string(path)
67
68
69def ask_to_proceed_with_overwrite(filepath):
70  """Produces a prompt asking about overwriting a file.
71
72  Args:
73      filepath: the path to the file to be overwritten.
74
75  Returns:
76      True if we can proceed with overwrite, False otherwise.
77  """
78  overwrite = six.moves.input('[WARNING] %s already exists - overwrite? '
79                              '[y/n]' % (filepath)).strip().lower()
80  while overwrite not in ('y', 'n'):
81    overwrite = six.moves.input('Enter "y" (overwrite) or "n" '
82                                '(cancel).').strip().lower()
83  if overwrite == 'n':
84    return False
85  print('[TIP] Next time specify overwrite=True!')
86  return True
87