##// END OF EJS Templates
Merge pull request #1709 from jstenar/arg_split_fix...
Min RK -
r6821:b9c986f5 merge
parent child Browse files
Show More
@@ -1,185 +1,185 b''
1 """Windows-specific implementation of process utilities.
1 """Windows-specific implementation of process utilities.
2
2
3 This file is only meant to be imported by process.py, not by end-users.
3 This file is only meant to be imported by process.py, not by end-users.
4 """
4 """
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2010-2011 The IPython Development Team
7 # Copyright (C) 2010-2011 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 from __future__ import print_function
16 from __future__ import print_function
17
17
18 # stdlib
18 # stdlib
19 import os
19 import os
20 import sys
20 import sys
21 import ctypes
21 import ctypes
22 import msvcrt
22 import msvcrt
23
23
24 from ctypes import c_int, POINTER
24 from ctypes import c_int, POINTER
25 from ctypes.wintypes import LPCWSTR, HLOCAL
25 from ctypes.wintypes import LPCWSTR, HLOCAL
26 from subprocess import STDOUT
26 from subprocess import STDOUT
27
27
28 # our own imports
28 # our own imports
29 from ._process_common import read_no_interrupt, process_handler, arg_split as py_arg_split
29 from ._process_common import read_no_interrupt, process_handler, arg_split as py_arg_split
30 from . import py3compat
30 from . import py3compat
31 from . import text
31 from . import text
32 from .encoding import DEFAULT_ENCODING
32 from .encoding import DEFAULT_ENCODING
33
33
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35 # Function definitions
35 # Function definitions
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37
37
38 class AvoidUNCPath(object):
38 class AvoidUNCPath(object):
39 """A context manager to protect command execution from UNC paths.
39 """A context manager to protect command execution from UNC paths.
40
40
41 In the Win32 API, commands can't be invoked with the cwd being a UNC path.
41 In the Win32 API, commands can't be invoked with the cwd being a UNC path.
42 This context manager temporarily changes directory to the 'C:' drive on
42 This context manager temporarily changes directory to the 'C:' drive on
43 entering, and restores the original working directory on exit.
43 entering, and restores the original working directory on exit.
44
44
45 The context manager returns the starting working directory *if* it made a
45 The context manager returns the starting working directory *if* it made a
46 change and None otherwise, so that users can apply the necessary adjustment
46 change and None otherwise, so that users can apply the necessary adjustment
47 to their system calls in the event of a change.
47 to their system calls in the event of a change.
48
48
49 Example
49 Example
50 -------
50 -------
51 ::
51 ::
52 cmd = 'dir'
52 cmd = 'dir'
53 with AvoidUNCPath() as path:
53 with AvoidUNCPath() as path:
54 if path is not None:
54 if path is not None:
55 cmd = '"pushd %s &&"%s' % (path, cmd)
55 cmd = '"pushd %s &&"%s' % (path, cmd)
56 os.system(cmd)
56 os.system(cmd)
57 """
57 """
58 def __enter__(self):
58 def __enter__(self):
59 self.path = os.getcwdu()
59 self.path = os.getcwdu()
60 self.is_unc_path = self.path.startswith(r"\\")
60 self.is_unc_path = self.path.startswith(r"\\")
61 if self.is_unc_path:
61 if self.is_unc_path:
62 # change to c drive (as cmd.exe cannot handle UNC addresses)
62 # change to c drive (as cmd.exe cannot handle UNC addresses)
63 os.chdir("C:")
63 os.chdir("C:")
64 return self.path
64 return self.path
65 else:
65 else:
66 # We return None to signal that there was no change in the working
66 # We return None to signal that there was no change in the working
67 # directory
67 # directory
68 return None
68 return None
69
69
70 def __exit__(self, exc_type, exc_value, traceback):
70 def __exit__(self, exc_type, exc_value, traceback):
71 if self.is_unc_path:
71 if self.is_unc_path:
72 os.chdir(self.path)
72 os.chdir(self.path)
73
73
74
74
75 def _find_cmd(cmd):
75 def _find_cmd(cmd):
76 """Find the full path to a .bat or .exe using the win32api module."""
76 """Find the full path to a .bat or .exe using the win32api module."""
77 try:
77 try:
78 from win32api import SearchPath
78 from win32api import SearchPath
79 except ImportError:
79 except ImportError:
80 raise ImportError('you need to have pywin32 installed for this to work')
80 raise ImportError('you need to have pywin32 installed for this to work')
81 else:
81 else:
82 PATH = os.environ['PATH']
82 PATH = os.environ['PATH']
83 extensions = ['.exe', '.com', '.bat', '.py']
83 extensions = ['.exe', '.com', '.bat', '.py']
84 path = None
84 path = None
85 for ext in extensions:
85 for ext in extensions:
86 try:
86 try:
87 path = SearchPath(PATH, cmd + ext)[0]
87 path = SearchPath(PATH, cmd + ext)[0]
88 except:
88 except:
89 pass
89 pass
90 if path is None:
90 if path is None:
91 raise OSError("command %r not found" % cmd)
91 raise OSError("command %r not found" % cmd)
92 else:
92 else:
93 return path
93 return path
94
94
95
95
96 def _system_body(p):
96 def _system_body(p):
97 """Callback for _system."""
97 """Callback for _system."""
98 enc = DEFAULT_ENCODING
98 enc = DEFAULT_ENCODING
99 for line in read_no_interrupt(p.stdout).splitlines():
99 for line in read_no_interrupt(p.stdout).splitlines():
100 line = line.decode(enc, 'replace')
100 line = line.decode(enc, 'replace')
101 print(line, file=sys.stdout)
101 print(line, file=sys.stdout)
102 for line in read_no_interrupt(p.stderr).splitlines():
102 for line in read_no_interrupt(p.stderr).splitlines():
103 line = line.decode(enc, 'replace')
103 line = line.decode(enc, 'replace')
104 print(line, file=sys.stderr)
104 print(line, file=sys.stderr)
105
105
106 # Wait to finish for returncode
106 # Wait to finish for returncode
107 return p.wait()
107 return p.wait()
108
108
109
109
110 def system(cmd):
110 def system(cmd):
111 """Win32 version of os.system() that works with network shares.
111 """Win32 version of os.system() that works with network shares.
112
112
113 Note that this implementation returns None, as meant for use in IPython.
113 Note that this implementation returns None, as meant for use in IPython.
114
114
115 Parameters
115 Parameters
116 ----------
116 ----------
117 cmd : str
117 cmd : str
118 A command to be executed in the system shell.
118 A command to be executed in the system shell.
119
119
120 Returns
120 Returns
121 -------
121 -------
122 None : we explicitly do NOT return the subprocess status code, as this
122 None : we explicitly do NOT return the subprocess status code, as this
123 utility is meant to be used extensively in IPython, where any return value
123 utility is meant to be used extensively in IPython, where any return value
124 would trigger :func:`sys.displayhook` calls.
124 would trigger :func:`sys.displayhook` calls.
125 """
125 """
126 # The controller provides interactivity with both
126 # The controller provides interactivity with both
127 # stdin and stdout
127 # stdin and stdout
128 import _process_win32_controller
128 import _process_win32_controller
129 _process_win32_controller.system(cmd)
129 _process_win32_controller.system(cmd)
130
130
131
131
132 def getoutput(cmd):
132 def getoutput(cmd):
133 """Return standard output of executing cmd in a shell.
133 """Return standard output of executing cmd in a shell.
134
134
135 Accepts the same arguments as os.system().
135 Accepts the same arguments as os.system().
136
136
137 Parameters
137 Parameters
138 ----------
138 ----------
139 cmd : str
139 cmd : str
140 A command to be executed in the system shell.
140 A command to be executed in the system shell.
141
141
142 Returns
142 Returns
143 -------
143 -------
144 stdout : str
144 stdout : str
145 """
145 """
146
146
147 with AvoidUNCPath() as path:
147 with AvoidUNCPath() as path:
148 if path is not None:
148 if path is not None:
149 cmd = '"pushd %s &&"%s' % (path, cmd)
149 cmd = '"pushd %s &&"%s' % (path, cmd)
150 out = process_handler(cmd, lambda p: p.communicate()[0], STDOUT)
150 out = process_handler(cmd, lambda p: p.communicate()[0], STDOUT)
151
151
152 if out is None:
152 if out is None:
153 out = ''
153 out = ''
154 return out
154 return out
155
155
156 try:
156 try:
157 CommandLineToArgvW = ctypes.windll.shell32.CommandLineToArgvW
157 CommandLineToArgvW = ctypes.windll.shell32.CommandLineToArgvW
158 CommandLineToArgvW.arg_types = [LPCWSTR, POINTER(c_int)]
158 CommandLineToArgvW.arg_types = [LPCWSTR, POINTER(c_int)]
159 CommandLineToArgvW.res_types = [POINTER(LPCWSTR)]
159 CommandLineToArgvW.restype = POINTER(LPCWSTR)
160 LocalFree = ctypes.windll.kernel32.LocalFree
160 LocalFree = ctypes.windll.kernel32.LocalFree
161 LocalFree.res_type = HLOCAL
161 LocalFree.res_type = HLOCAL
162 LocalFree.arg_types = [HLOCAL]
162 LocalFree.arg_types = [HLOCAL]
163
163
164 def arg_split(commandline, posix=False, strict=True):
164 def arg_split(commandline, posix=False, strict=True):
165 """Split a command line's arguments in a shell-like manner.
165 """Split a command line's arguments in a shell-like manner.
166
166
167 This is a special version for windows that use a ctypes call to CommandLineToArgvW
167 This is a special version for windows that use a ctypes call to CommandLineToArgvW
168 to do the argv splitting. The posix paramter is ignored.
168 to do the argv splitting. The posix paramter is ignored.
169
169
170 If strict=False, process_common.arg_split(...strict=False) is used instead.
170 If strict=False, process_common.arg_split(...strict=False) is used instead.
171 """
171 """
172 #CommandLineToArgvW returns path to executable if called with empty string.
172 #CommandLineToArgvW returns path to executable if called with empty string.
173 if commandline.strip() == "":
173 if commandline.strip() == "":
174 return []
174 return []
175 if not strict:
175 if not strict:
176 # not really a cl-arg, fallback on _process_common
176 # not really a cl-arg, fallback on _process_common
177 return py_arg_split(commandline, posix=posix, strict=strict)
177 return py_arg_split(commandline, posix=posix, strict=strict)
178 argvn = c_int()
178 argvn = c_int()
179 result_pointer = CommandLineToArgvW(py3compat.cast_unicode(commandline.lstrip()), ctypes.byref(argvn))
179 result_pointer = CommandLineToArgvW(py3compat.cast_unicode(commandline.lstrip()), ctypes.byref(argvn))
180 result_array_type = LPCWSTR * argvn.value
180 result_array_type = LPCWSTR * argvn.value
181 result = [arg for arg in result_array_type.from_address(result_pointer)]
181 result = [arg for arg in result_array_type.from_address(ctypes.addressof(result_pointer.contents))]
182 retval = LocalFree(result_pointer)
182 retval = LocalFree(result_pointer)
183 return result
183 return result
184 except AttributeError:
184 except AttributeError:
185 arg_split = py_arg_split
185 arg_split = py_arg_split
General Comments 0
You need to be logged in to leave comments. Login now