From 4c6346cc3e48d4c31da2362d25431b4668604454 Mon Sep 17 00:00:00 2001 From: Yih-Dar <2521628+ydshieh@users.noreply.github.com> Date: Tue, 21 Feb 2023 09:39:15 +0100 Subject: [PATCH] Fix `get_class_in_module` (#21709) Fix get_class_in_module Co-authored-by: ydshieh --- src/transformers/dynamic_module_utils.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/transformers/dynamic_module_utils.py b/src/transformers/dynamic_module_utils.py index 1e606572fd..7e43b27d46 100644 --- a/src/transformers/dynamic_module_utils.py +++ b/src/transformers/dynamic_module_utils.py @@ -154,7 +154,17 @@ def get_class_in_module(class_name, module_path): shutil.copy(f"{module_dir}/{module_file_name}", tmp_dir) # On Windows, we need this character `r` before the path argument of `os.remove` cmd = f'import os; os.remove(r"{module_dir}{os.path.sep}{module_file_name}")' - subprocess.run(["python", "-c", cmd]) + # We don't know which python binary file exists in an environment. For example, if `python3` exists but not + # `python`, the call `subprocess.run(["python", ...])` gives `FileNotFoundError` (about python binary). Notice + # that, if the file to be removed is not found, we also have `FileNotFoundError`, but it is not raised to the + # caller's process. + try: + subprocess.run(["python", "-c", cmd]) + except FileNotFoundError: + try: + subprocess.run(["python3", "-c", cmd]) + except FileNotFoundError: + pass # copy back the file that we want to import shutil.copyfile(f"{tmp_dir}/{module_file_name}", f"{module_dir}/{module_file_name}")