1#
2# File      : win32spawn.py
3# This file is part of RT-Thread RTOS
4# COPYRIGHT (C) 2006 - 2025, RT-Thread Development Team
5#
6#  This program is free software; you can redistribute it and/or modify
7#  it under the terms of the GNU General Public License as published by
8#  the Free Software Foundation; either version 2 of the License, or
9#  (at your option) any later version.
10#
11#  This program is distributed in the hope that it will be useful,
12#  but WITHOUT ANY WARRANTY; without even the implied warranty of
13#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14#  GNU General Public License for more details.
15#
16#  You should have received a copy of the GNU General Public License along
17#  with this program; if not, write to the Free Software Foundation, Inc.,
18#  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19#
20# Change Logs:
21# Date           Author       Notes
22# 2015-01-20     Bernard      Add copyright information
23#
24
25import os
26import subprocess
27
28class Win32Spawn:
29    def spawn(self, sh, escape, cmd, args, env):
30        # deal with the cmd build-in commands which cannot be used in
31        # subprocess.Popen
32        if cmd == 'del':
33            for f in args[1:]:
34                try:
35                    os.remove(f)
36                except Exception as e:
37                    print('Error removing file: ' + e)
38                    return -1
39            return 0
40
41        newargs = ' '.join(args[1:])
42        cmdline = cmd + " " + newargs
43
44        # Make sure the env is constructed by strings
45        _e = dict([(k, str(v)) for k, v in env.items()])
46
47        # Windows(tm) CreateProcess does not use the env passed to it to find
48        # the executables. So we have to modify our own PATH to make Popen
49        # work.
50        old_path = os.environ['PATH']
51        os.environ['PATH'] = _e['PATH']
52
53        try:
54            proc = subprocess.Popen(cmdline, env=_e, shell=False)
55        except Exception as e:
56            print('Error in calling command:' + cmdline.split(' ')[0])
57            print('Exception: ' + os.strerror(e.errno))
58            if (os.strerror(e.errno) == "No such file or directory"):
59                print ("\nPlease check Toolchains PATH setting.\n")
60
61            return e.errno
62        finally:
63            os.environ['PATH'] = old_path
64
65        return proc.wait()
66